hud-sdk 1.6.23 → 1.6.24

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.
@@ -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 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,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=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,r(n(2887),t),r(n(2570),t);var s=n(2210);Object.defineProperty(t,"SDK_MODULE_NAME",{enumerable:!0,get:function(){return s.SDK_MODULE_NAME}}),r(n(7089),t);var a=n(5453);Object.defineProperty(t,"SDK_VERSION",{enumerable:!0,get:function(){return a.SDK_VERSION}})},2570:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateDynamicConfig=function(e,t,n){const s=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!s.success)return n.error("Dynamic configuration not updated - Invalid configuration override",{remoteConfigParseResult:s,remoteConfig:e}),t.dynamicConfig;const a=r(t.dynamicConfig,s.data);return void 0!==a.enableInvestigation&&a.enableInvestigation!==t.dynamicConfig.enableInvestigation&&(n.info("Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:a.enableInvestigation}),t.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=a.enableInvestigation)),a};const i=n(2887);function r(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 s=e[i],a=t[i];n[i]=r(s,a)}return n}},2887:function(e,t,n){var i,r=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=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,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=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||(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),a=0;a<n.length;a++)"default"!==n[a]&&r(t,e,n[a]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.HudFailedReadConfigError=t.hudConfig=t.HudDynamicConfigSchema=void 0,t.getModulesToTraceFromEnv=function(){const e=process.env.HUD_MONITOR_MODULES||process.env.HUD_INCLUDE_MODULES;if(e)return e.split(",")},t.getFrameworksToEnableFromEnv=function(){const e=process.env.HUD_ENABLE_FRAMEWORKS;let t;if(e)try{t=o.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)},t.getConfigContent=function(){if(process.env.HUD_CONFIG)return{content:process.env.HUD_CONFIG,source:"HUD_CONFIG"};const e=function(){try{const e=process.env.HUD_CONFIG_PATH;if(e)return l.existsSync(e)?e:void 0;let t=__dirname,n=0;for(;"/"!==t&&n<10;){const e=`${t}/hud.config`;if(l.existsSync(e))return e;t=u.dirname(t),n++}}catch{return}}();if(e)try{return{content:l.readFileSync(e,"utf8"),source:e}}catch(t){throw new h(e,t.code)}};const o=n(8528),l=a(n(9896)),u=a(n(6928)),d=n(1569),c="globalThis._hudMark";t.HudDynamicConfigSchema=d.z.object({aggregationInterval:d.z.number(),aggregationFirstSendTimeout:d.z.number(),enableInvestigation: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(),totalInvestigationTimeWindowMs:d.z.number().int().positive(),maxUniqLogs: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())});const m=process.env.HUD_ENABLE_INVESTIGATION,p=process.env.HUD_HOST||"https://api-prod.hud.io",g=process.env.HUD_LOG_DIR,f="_HUD",v=process.env.HUD_LOG_TO_FILE,b={sink:{url:p,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"},logger:{default:{levels:{app:"warn",worker:"warn",instrument:"warn"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},investigation:{objectVersion:"1.0.1",store:{type:"s3"},limits:{executionFlowMaxLength:100,exceptionMaxLength:100},maxStringLength:1024,maxArrayLength:100,maxObjectDepth:10},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"},disableRuntimeInstrumentation:{value:!1,source:"DEFAULT"}},loggerWorkerPortSizeLimit:1e4,customerLoggerLevel:"info",logDirectory:g,invocationSampling:new Map([[[300n,null],100],[[200n,300n],50],[[100n,200n],25],[[0n,100n],10]]),callerResetInterval:36e5,modeInterval:3e5,logsSendInterval:6e4,logPerfInterval:3e5,endpointsInterval:3e4,endpointsFirstSendWaitTime:12e4,lazyEndpointsInterval:18e5,staticNextJsEndpointsInterval:1e4,staticNextJsEndpointsMaxAttempts:12,huddBinWidth:1.2,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:"94a210f3-861c-4e18-ab27-6b6c19437c9d",wrapVarPrefix:f,functionIdVarName:`${f}_fid`,frameworksToPatch:new Map([["express",{framework:o.availableFrameworks.express,enable:!0,version:"<=5",patcher:"express",enableEsbuild:!0}],[u.join("express","lib","application.js"),{framework:o.availableFrameworks.express,enable:!0,version:"<=5",patcher:"expressApplication",enableEsbuild:!0}],["router",{framework:o.availableFrameworks.express,enable:!0,version:"^2.0.0",patcher:"router",enableEsbuild:!0}],["koa",{framework:o.availableFrameworks.koa,enable:!0,version:"^2.0.0",patcher:"koa"}],["http",{framework:o.availableFrameworks.http,enable:!0,version:"*",patcher:"http"}],["https",{framework:o.availableFrameworks.https,enable:!0,version:"*",patcher:"http"}],["next/dist/server/base-server",{framework:o.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextjs"}],["next/dist/server/lib/module-loader/route-module-loader",{framework:o.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsModuleLoader"}],["next/dist/server/web/spec-extension/adapters/next-request",{framework:o.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextRequestAdapter"}],["next/dist/server/config",{framework:o.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsConfig"}],["@nestjs/core/router/router-execution-context",{framework:o.availableFrameworks.nestjs,enable:!0,version:"*",patcher:"nestjsRouterExecutionContext"}],["kafkajs",{framework:o.availableFrameworks.kafkajs,enable:"win32"!==process.platform,version:">=1.4.0",patcher:"kafkajs"}],["@nestjs/microservices/context/rpc-context-creator",{framework:o.availableFrameworks.nestjs,enable:"win32"!==process.platform,version:">=7.0.0",patcher:"nestjsRpcContextCreator"}],[["@codegenie/serverless-express","src","frameworks","express.js"].join(u.sep),{framework:o.availableFrameworks.codegenieServerlessExpress,enable:!0,version:"^4.1.0",patcher:"codeGenieServerlessExpress",enableEsbuild:!0}],["@codegenie/serverless-express",{framework:o.availableFrameworks.codegenieServerlessExpress,enable:!0,enableEsbuild:!0}],["sqs-consumer",{framework:o.availableFrameworks.sqs,enable:!0,version:"*",patcher:"sqsConsumer",extraInfo:{mondayVersion:">=6.1.0",bbcVersion:">=7.5.0"}}],["serverless-http",{framework:o.availableFrameworks.serverlessHttp,enable:!0,enableEsbuild:!0}],[u.join("serverless-http","lib","framework","get-framework.js"),{framework:o.availableFrameworks.serverlessHttp,enable:!0,version:"^2.7.0",patcher:"serverlessHttp",enableEsbuild:!0}]]),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,enableInvestigation:"true"===m,investigationRateLimits:{maxSameInvestigations:2,sameInvestigationTimeWindowMs:36e5,maxTotalInvestigations:25,totalInvestigationTimeWindowMs:216e5,maxUniqLogs:2},machineMetricsInterval:1e4,reingestInterval:3e4,extraHeaders:[],blacklistParams:[],censorshipRegexes:[],forensicsBlacklistFields:[],forensicsWhitelistFields:[]},machineMetricsSavedLength:2,isInvestigationEnabledByEnv:void 0!==m,suppressTraces:!0,lambdaMinimunMemory:1024,lambdaBaseGivenTime:400,lambdaExtraGivenTimePerRequest:50,lambdaMaxGivenTime:700,throttleStatusCode:202,functionsToInstrument:[{moduleName:"pg",fileToFunctionsMapping:{[u.join(u.sep,"pg","lib","client.js")]:["query","connect","end"]}},{moduleName:"axios",fileToFunctionsMapping:{[u.join(u.sep,"axios","dist","node","axios.cjs")]:["request"]}},{moduleName:"typeorm",fileToFunctionsMapping:{[u.join(u.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",esbuildPluginMessagePrefix:"ESBuild plugin ",esbuildMark:"/*modifiedByHudESBuildPlugin-",esbuildMarkLength:67,esbuildUploadSourceMapTimeout:15e3,esbuildPluginLogsChunkSize:100,esbuildPluginLogsBatchSize:10,pluginsLogEndpoint:"https://yqp37dddrsewm6wdwwpwfraxqm0shdmx.lambda-url.eu-central-1.on.aws/",fileless:"true"!==v,uninstrumentedFilesLogThreshold:2,tsNodeConfigTimeout:1e4,allowedEditExtensions:[".ts",".cts",".mts",".js",".cjs",".mjs"],nextJsMarkVarName:c,nextJsMarkStatement:`${c} = "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;class h extends Error{path;code;constructor(e,t){super(),this.path=e,this.code=t}}t.HudFailedReadConfigError=h},5453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SDK_VERSION=void 0,t.SDK_VERSION="1.6.23"},6928:e=>{e.exports=require("path")},7089:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ObjectStoreConfigSchema=void 0;const i=n(1569),r=i.z.object({type:i.z.literal("s3")}),s=i.z.object({type:i.z.literal("disk"),path:i.z.string()});t.ObjectStoreConfigSchema=i.z.union([r,s])},8528:e=>{e.exports=require("./dto")},9896:e=>{e.exports=require("fs")}},t={};return function n(i){var r=t[i];if(void 0!==r)return r.exports;var s=t[i]={exports:{}};return e[i].call(s.exports,s,s.exports,n),s.exports}(2509)})());
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 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,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=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,r(n(2887),t),r(n(2570),t);var s=n(2210);Object.defineProperty(t,"SDK_MODULE_NAME",{enumerable:!0,get:function(){return s.SDK_MODULE_NAME}}),r(n(7089),t);var a=n(5453);Object.defineProperty(t,"SDK_VERSION",{enumerable:!0,get:function(){return a.SDK_VERSION}})},2570:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateDynamicConfig=function(e,t,n){const s=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!s.success)return n.error("Dynamic configuration not updated - Invalid configuration override",{remoteConfigParseResult:s,remoteConfig:e}),t.dynamicConfig;const a=r(t.dynamicConfig,s.data);return void 0!==a.enableInvestigation&&a.enableInvestigation!==t.dynamicConfig.enableInvestigation&&(n.info("Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:a.enableInvestigation}),t.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=a.enableInvestigation)),a};const i=n(2887);function r(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 s=e[i],a=t[i];n[i]=r(s,a)}return n}},2887:function(e,t,n){var i,r=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=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,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=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||(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),a=0;a<n.length;a++)"default"!==n[a]&&r(t,e,n[a]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.HudFailedReadConfigError=t.hudConfig=t.HudDynamicConfigSchema=void 0,t.getModulesToTraceFromEnv=function(){const e=process.env.HUD_MONITOR_MODULES||process.env.HUD_INCLUDE_MODULES;if(e)return e.split(",")},t.getFrameworksToEnableFromEnv=function(){const e=process.env.HUD_ENABLE_FRAMEWORKS;let t;if(e)try{t=o.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)},t.getConfigContent=function(){if(process.env.HUD_CONFIG)return{content:process.env.HUD_CONFIG,source:"HUD_CONFIG"};const e=function(){try{const e=process.env.HUD_CONFIG_PATH;if(e)return l.existsSync(e)?e:void 0;let t=__dirname,n=0;for(;"/"!==t&&n<10;){const e=`${t}/hud.config`;if(l.existsSync(e))return e;t=u.dirname(t),n++}}catch{return}}();if(e)try{return{content:l.readFileSync(e,"utf8"),source:e}}catch(t){throw new h(e,t.code)}};const o=n(8528),l=a(n(9896)),u=a(n(6928)),d=n(1569),c="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(),investigationRateLimits:d.z.object({maxSameInvestigations:d.z.number().int().positive(),sameInvestigationTimeWindowMs:d.z.number().int().positive(),maxTotalInvestigations:d.z.number().int().positive(),totalInvestigationTimeWindowMs:d.z.number().int().positive(),maxUniqLogs: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())});const m=process.env.HUD_ENABLE_INVESTIGATION,p=process.env.HUD_HOST||"https://api-prod.hud.io",g=process.env.HUD_LOG_DIR,f="_HUD",v=process.env.HUD_LOG_TO_FILE,b={sink:{url:p,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"},logger:{default:{levels:{app:"warn",worker:"warn",instrument:"warn"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},investigation:{objectVersion:"1.0.1",store:{type:"s3"},limits:{executionFlowMaxLength:100,exceptionMaxLength:100},maxStringLength:1024,maxArrayLength:100,maxObjectDepth:10},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"},disableRuntimeInstrumentation:{value:!1,source:"DEFAULT"}},loggerWorkerPortSizeLimit:1e4,customerLoggerLevel:"info",logDirectory:g,invocationSampling:new Map([[[300n,null],100],[[200n,300n],50],[[100n,200n],25],[[0n,100n],10]]),callerResetInterval:36e5,modeInterval:3e5,logsSendInterval:6e4,logPerfInterval:3e5,endpointsInterval:3e4,endpointsFirstSendWaitTime:12e4,lazyEndpointsInterval:18e5,staticNextJsEndpointsInterval:1e4,staticNextJsEndpointsMaxAttempts:12,huddBinWidth:1.2,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:"94a210f3-861c-4e18-ab27-6b6c19437c9d",wrapVarPrefix:f,functionIdVarName:`${f}_fid`,frameworksToPatch:new Map([["express",{framework:o.availableFrameworks.express,enable:!0,version:"<=5",patcher:"express",enableEsbuild:!0}],[u.join("express","lib","application.js"),{framework:o.availableFrameworks.express,enable:!0,version:"<=5",patcher:"expressApplication",enableEsbuild:!0}],["router",{framework:o.availableFrameworks.express,enable:!0,version:"^2.0.0",patcher:"router",enableEsbuild:!0}],["koa",{framework:o.availableFrameworks.koa,enable:!0,version:"^2.0.0",patcher:"koa"}],["http",{framework:o.availableFrameworks.http,enable:!0,version:"*",patcher:"http"}],["https",{framework:o.availableFrameworks.https,enable:!0,version:"*",patcher:"http"}],["next/dist/server/base-server",{framework:o.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextjs"}],["next/dist/server/lib/module-loader/route-module-loader",{framework:o.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsModuleLoader"}],["next/dist/server/web/spec-extension/adapters/next-request",{framework:o.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextRequestAdapter"}],["next/dist/server/config",{framework:o.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsConfig"}],["@nestjs/core/router/router-execution-context",{framework:o.availableFrameworks.nestjs,enable:!0,version:"*",patcher:"nestjsRouterExecutionContext"}],["kafkajs",{framework:o.availableFrameworks.kafkajs,enable:"win32"!==process.platform,version:">=1.4.0",patcher:"kafkajs"}],["@nestjs/microservices/context/rpc-context-creator",{framework:o.availableFrameworks.nestjs,enable:"win32"!==process.platform,version:">=7.0.0",patcher:"nestjsRpcContextCreator"}],[["@codegenie/serverless-express","src","frameworks","express.js"].join(u.sep),{framework:o.availableFrameworks.codegenieServerlessExpress,enable:!0,version:"^4.1.0",patcher:"codeGenieServerlessExpress",enableEsbuild:!0}],["@codegenie/serverless-express",{framework:o.availableFrameworks.codegenieServerlessExpress,enable:!0,enableEsbuild:!0}],["sqs-consumer",{framework:o.availableFrameworks.sqs,enable:!0,version:"*",patcher:"sqsConsumer",extraInfo:{mondayVersion:">=6.1.0",bbcVersion:">=7.5.0"}}],["serverless-http",{framework:o.availableFrameworks.serverlessHttp,enable:!0,enableEsbuild:!0}],[u.join("serverless-http","lib","framework","get-framework.js"),{framework:o.availableFrameworks.serverlessHttp,enable:!0,version:"^2.7.0",patcher:"serverlessHttp",enableEsbuild:!0}]]),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"===m,investigationRateLimits:{maxSameInvestigations:2,sameInvestigationTimeWindowMs:36e5,maxTotalInvestigations:25,totalInvestigationTimeWindowMs:216e5,maxUniqLogs:2},machineMetricsInterval:1e4,reingestInterval:3e4,extraHeaders:[],blacklistParams:[],censorshipRegexes:[],forensicsBlacklistFields:[],forensicsWhitelistFields:[]},machineMetricsSavedLength:2,isInvestigationEnabledByEnv:void 0!==m,suppressTraces:!0,lambdaMinimunMemory:1024,lambdaBaseGivenTime:400,lambdaExtraGivenTimePerRequest:50,lambdaMaxGivenTime:700,throttleStatusCode:202,functionsToInstrument:[{moduleName:"pg",fileToFunctionsMapping:{[u.join(u.sep,"pg","lib","client.js")]:["query","connect","end"]}},{moduleName:"axios",fileToFunctionsMapping:{[u.join(u.sep,"axios","dist","node","axios.cjs")]:["request"]}},{moduleName:"typeorm",fileToFunctionsMapping:{[u.join(u.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",esbuildPluginMessagePrefix:"ESBuild plugin ",esbuildMark:"/*modifiedByHudESBuildPlugin-",esbuildMarkLength:67,esbuildUploadSourceMapTimeout:15e3,esbuildPluginLogsChunkSize:100,esbuildPluginLogsBatchSize:10,pluginsLogEndpoint:"https://yqp37dddrsewm6wdwwpwfraxqm0shdmx.lambda-url.eu-central-1.on.aws/",fileless:"true"!==v,uninstrumentedFilesLogThreshold:2,tsNodeConfigTimeout:1e4,allowedEditExtensions:[".ts",".cts",".mts",".js",".cjs",".mjs"],nextJsMarkVarName:c,nextJsMarkStatement:`${c} = "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;class h extends Error{path;code;constructor(e,t){super(),this.path=e,this.code=t}}t.HudFailedReadConfigError=h},5453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SDK_VERSION=void 0,t.SDK_VERSION="1.6.24"},6928:e=>{e.exports=require("path")},7089:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ObjectStoreConfigSchema=void 0;const i=n(1569),r=i.z.object({type:i.z.literal("s3")}),s=i.z.object({type:i.z.literal("disk"),path:i.z.string()});t.ObjectStoreConfigSchema=i.z.union([r,s])},8528:e=>{e.exports=require("./dto")},9896:e=>{e.exports=require("fs")}},t={};return function n(i){var r=t[i];if(void 0!==r)return r.exports;var s=t[i]={exports:{}};return e[i].call(s.exports,s,s.exports,n),s.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 r=t();for(var i in r)("object"==typeof exports?exports:e)[i]=r[i]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,r){var i,o=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,o)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=i(e),s=0;s<r.length;s++)"default"!==r[s]&&o(t,e,r[s]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=s(r(523)),d=r(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}}},5119:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.init=void 0;const o=i(r(6281));t.init=o.default},5809:e=>{e.exports=require("./config")},5994:function(e,t,r){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=r(8167),n=r(2546),s=r(5809),a=r(8269),d=r(523),c=r(6281),l=i(r(7320));function g(){globalThis.hudInstrumentationOccured&&d.customer_logger.log(n.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;constructor(e,t,r,i){this.apiKey=e,this.service=t,this.startTime=r,this.tags=i}startFailed(e){e instanceof n.HudSessionThrottle?(d.customer_logger.log(n.UserLogs.InitIdleMode()),(0,c._detachAndTerminate)(!1,!1)):e instanceof n.HudInitNetworkError&&e.originalAxiosErrorCode?(d.customer_logger.log((0,n.getNetworkError)(e.originalAxiosErrorCode)),(0,c._detachAndTerminate)(!1,!1)):(d.app_logger.error("Failed to start worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,n.setFirstError)(e.code),(0,c._detachAndTerminate)())}async _registerLambdaExtension(){const e=await(0,n.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),d.customer_logger.log(n.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(o.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,n.next)(e).then(async()=>{d.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}})}catch(e){throw this.startFailed(e),e}else await this.startMessenger(void 0)}async _start(){if(!this.messenger)throw new n.HudInitError("Messenger not initialized");try{await this.messenger.checkWorkerInitialized(s.hudConfig.workerTimeout),await this._initDynamicConfig(),globalThis.hudMetricsIndicator=setTimeout(g,s.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof n.HudSessionThrottle)throw e;throw d.app_logger.error("Failed to starting worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=n.myRequire.resolve(`${s.SDK_MODULE_NAME}/worker`),r={...process.env};delete r.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:r});let a;try{a=new l.default(i),await a.checkWorker(s.hudConfig.workerTimeout)}catch(e){if(e instanceof n.HudSessionThrottle)throw d.app_logger.info("Worker started in idle mode - session throttled"),e;throw d.app_logger.error("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?(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,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,r){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void o.app_logger.warn("Already ran init!");if(globalThis.hudRunMutex=!0,(0,d.clearInitGuard)(),!o.app_logger.isValid()||!o.customer_logger.isValid())return(0,c.setFirstError)((new c.HudBadLoggerError).code),void h(!0,!0);(0,i.updateUserConfigFromInit)(e,t,r);const l=(0,d.validateAndGetUserInput)();if(!l)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return;if(o.app_logger.info("Initializing hud",{userConfig:Object.entries(s.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),g=new n.MainThread(l.apiKey,l.service,globalThis.hudStartTime,s.hudConfig.userConfig.tags?.value),await g.start(),g.messenger&&(0,c.safeCall)(o.app_logger,g.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 c.HudSessionThrottle)return;o.app_logger.error("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.error("Something went wrong in init & e.stack raised an exception")}h()}},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t._detachAndTerminate=h;const i=r(2546),o=r(523),n=r(5994),s=r(5809),a=r(8528),d=r(8269),c=r(2546),l=r(7274);let g,u=!1;function h(e=!0,t=!1){(0,d.detachHud)(e,t),g&&(0,c.safeCall)(o.app_logger,g.terminateMessenger());const r=(0,d.getLambdaExtensionId)();r&&!u&&(u=!0,(0,c.safeCall)(o.app_logger,(0,i.nextLoopDummy)(r))),(0,d.clearUserIndicatorsTimeouts)(),(0,l.resetCallers)()}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._liftExceptions=s,t.prepCalls=function(e,t){const r=(new Date).toISOString(),n=[];return Object.entries(hudCalls).map(([i,a])=>{Object.entries(a).forEach(([a,d])=>{Object.entries(d).forEach(([d,c])=>{try{if(0===c.sampledCount)return;const o={function_id:i,wrapped_flow_id:d||void 0,wrapped_caller_id:a||void 0,timestamp:r,timeslice:e,exceptions:s(c.exceptions),count:c.count-c.lastSentCounter,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};n.push(o),function(e){e.lastSentCounter=e.count,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(c)}catch(e){o.app_logger.error("Failed preparing invocation, skipping",{func:i,wrappedCaller:a,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})})}),n.length>0&&(0,i.clearMetricsIndicator)(),n},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])for(const r in globalThis.hudCalls[e][t])n(globalThis.hudCalls[e][t][r])};const i=r(8269),o=r(523);function n(e){e.lastSentCounter-=e.count,e.count=0}function s(e){const t={};for(const r in e)t[r]=[{count:e[r]}];return t}},7320:function(e,t,r){var i,o=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,o)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=i(e),s=0;s<r.length;s++)"default"!==r[s]&&o(t,e,r[s]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=s(r(523)),d=s(r(6460)),c=r(5809),l=r(2546),g=r(8528),u=r(2546),h=r(7131),f=r(8269),m=r(2546),p=r(7274),v=r(2702),w=r(8269),k=r(2546),y=r(6281),C=r(2546),b=r(6261),_=a.app_logger,E=m.safeCall.bind(m.safeCall,_);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;abortController;workerKeepaliveGuard;constructor(e){this.worker=e,this.abortController=new AbortController,(0,b.setMaxListeners)(20,this.abortController.signal),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.log(m.UserErrorLogs.ApiKeyDenied(c.hudConfig.userConfig.key?.source)),_.error("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,y._detachAndTerminate)()}catch(e){_.error("Error stopping hud",{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,(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 r={msg:e,content:t};this.worker.postMessage(r)}async checkWorker(e){const t=["started"];let r;try{r=await this.getMessageFromWorker(t,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;r=await this.getMessageFromWorker(t,e/2,!1)}if(!r)throw new m.HudInitError("Worker not started");return r}async checkWorkerInitialized(e){let t;const r=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(r,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;t=await this.getMessageFromWorker(r,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!==g.HudSessionInitStatus.success)throw new m.HudInitError("Worker not initialized successfully");return t}async start(){switch(c.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case g.HudRunningMode.enabled:_.info("Enabled mode"),E(this.getMode()),E(this.startPeriodicTasks()),E(this.periodicSendMetrics()),E(this.periodicSendProcessedFiles()),E(this.periodicSendEndpoints()),E(this.periodicSendLazyEndpoints()),E(this.periodicSendKafkaJS()),E(this.periodicSendSqs()),E(this.sendStaticNextJsEndpointsOnce()),E(this.periodicSaveMachineMetrics()),E(this.periodicSendReingest()),E(this.resetCallerCounters()),E(this.periodicResetGlobalInvestigationCounter()),E(this.periodicResetInvestigationDedupingCache()),E(this.sendLogsPeriodically(c.hudConfig.logsSendInterval)),E(this.sendRuntime()),E(this.sendPatchedModules()),E(this.sendPreloadedModules()),E(this.dumpModulesAfterWhile(6e4)),E((0,m.loopLogThreadPerformance)(_,c.hudConfig.logPerfInterval,this.abortController.signal));break;case g.HudRunningMode.disabled:_.info("Disabled mode"),E(this.getMode());break;case g.HudRunningMode.detached:_.info("Detached"),(0,y._detachAndTerminate)(!1,!1),this.stop();break;default:_.error("Running mode not handled")}}async getMessageFromWorker(e,t,r=!1,i){let o;e=Array.isArray(e)?e:[e];const n=new AbortController,s=()=>{n.abort()};this.abortController.signal.addEventListener("abort",s);const a=d.setTimeout(t,void 0,{signal:n.signal,ref:r}),c=t=>{try{e.includes(t.msg)&&(o=t,n.abort(),_.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.worker.on("message",c).unref(),i&&this.worker.postMessage(i);try{throw await a,_.warn("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",s),this.worker.off("message",c)}return o}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 periodicSendProcessedFiles(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;let r=!0;await this.setupPeriodicTask(e,t,()=>{if(r){r=!1;try{this._updateTsNodeConfig()&&_.info("ts-node config updated from periodicSendProcessedFiles")}catch{return!1}}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,w.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,w.getSqsQueues)();return e.length>0&&this._sendArray("SqsQueue",e),!0},"periodicSendSqs")}async periodicSendMetrics(){const e=new h.SketchManager(c.hudConfig.huddBinWidth),t=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,r=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,r,t=>{try{const e=(0,w.getClosedInvestigations)();e.length>0&&this._sendArray("Investigations",e)}catch(e){_.error("Failed sending investigations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const r=(0,p.prepCalls)(t,e);r.length>0&&this._sendArray("Invocations",r)}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 periodicSendEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.hudConfig.endpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendEndpoints(),!0),"periodicSendEndpoints")}async periodicSendLazyEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.hudConfig.lazyEndpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendLazyEndpoints(),!0),"periodicSendLazyEndpoints")}sendLazyEndpoints(){const e=(0,w.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)}async terminateWorker(){try{const e=(0,k.suppressTraces)(a.renewFileTransports),t=a.getSavedLogs(),r=e();await this.getMessageFromWorker("terminated",c.hudConfig.workerGrace,!1,{msg:"Terminate",content:{grace:c.hudConfig.workerGrace,logBuffers:t,logFiles:Array.from(r)}})}catch(e){if(!(e instanceof m.HudTimeoutError))throw _.error("Unexpected error, terminating worker"),await this.worker.terminate(),e;_.error("Grace period timeout, terminating worker"),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:r.c[r.s]?.filename};this._sendObject("Runtime",e)}async startPeriodicTasks(){this._sendObject("StartPeriodicTasks",{})}async sendPreloadedModules(){globalThis.hudLoadedModules?this._sendObject("PreInitLoadedModules",{modules:globalThis.hudLoadedModules}):_.warn("Didn't get module, weird....")}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(k.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=(0,k.suppressTraces)(a.renewFileTransports),t=a.getSavedLogs();for(const e of t)try{this._sendObject("Logs",{logs:e})}catch(e){_.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}const r=e();r.size>0&&this._sendObject("LogFilename",{filenames:r})}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,r,i){function o(e){let t=!0;try{t=r(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}),o(e)){for await(const e of(0,u.unrefSetInterval)(t,void 0,{signal:this.abortController.signal}))if(!o(t))return void _.warn("Periodic task failed, stopping task",{firstRun:!1,taskName:i})}else _.warn("Periodic task failed, stopping task",{firstRun:!0,taskName:i})}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,w.setGlobalInvestigationTracking)(0)}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,w.resetInvestigationDedupingCache)()}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,C.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,y._detachAndTerminate)(!1),e}}async sendStaticNextJsEndpointsOnce(){if(!(0,l.isNextJsApp)())return;const e=c.hudConfig.staticNextJsEndpointsInterval,t=c.hudConfig.staticNextJsEndpointsMaxAttempts;let r=0;for await(const i of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){if(r++,_.debug("Attempting to send static next.js endpoints",{attemptCount:r}),(0,w.isNextConfigExtracted)()&&!this.staticNextJsEndpointsSent){_.info("Sending static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)()}),this.staticNextJsEndpointsSent=!0;const e=(0,w.getNextConfig)();this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify(e)});break}if(r>t){_.warn("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)(),attemptCount:r});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 r(i){var o=t[i];if(void 0!==o)return o.exports;var n=t[i]={exports:{}};return e[i].call(n.exports,n,n.exports,r),n.exports}return r.c=t,r(r.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 r=t();for(var i in r)("object"==typeof exports?exports:e)[i]=r[i]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,r){var i,o=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,o)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=i(e),s=0;s<r.length;s++)"default"!==r[s]&&o(t,e,r[s]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=s(r(523)),d=r(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}}},5119:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.init=void 0;const o=i(r(6281));t.init=o.default},5809:e=>{e.exports=require("./config")},5994:function(e,t,r){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=r(8167),n=r(2546),s=r(5809),a=r(8269),d=r(523),c=r(6281),g=i(r(7320));function l(){globalThis.hudInstrumentationOccured&&d.customer_logger.log(n.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;constructor(e,t,r,i){this.apiKey=e,this.service=t,this.startTime=r,this.tags=i}startFailed(e){e instanceof n.HudSessionThrottle?(d.customer_logger.log(n.UserLogs.InitIdleMode()),(0,c._detachAndTerminate)(!1,!1)):e instanceof n.HudInitNetworkError&&e.originalAxiosErrorCode?(d.customer_logger.log((0,n.getNetworkError)(e.originalAxiosErrorCode)),(0,c._detachAndTerminate)(!1,!1)):(d.app_logger.error("Failed to start worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,n.setFirstError)(e.code),(0,c._detachAndTerminate)())}async _registerLambdaExtension(){const e=await(0,n.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),d.customer_logger.log(n.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(o.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,n.next)(e).then(async()=>{d.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}})}catch(e){throw this.startFailed(e),e}else await this.startMessenger(void 0)}async _start(){if(!this.messenger)throw new n.HudInitError("Messenger not initialized");try{await this.messenger.checkWorkerInitialized(s.hudConfig.workerTimeout),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 n.HudSessionThrottle)throw e;throw d.app_logger.error("Failed to starting worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=n.myRequire.resolve(`${s.SDK_MODULE_NAME}/worker`),r={...process.env};delete r.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:r});let a;try{a=new g.default(i),await a.checkWorker(s.hudConfig.workerTimeout)}catch(e){if(e instanceof n.HudSessionThrottle)throw d.app_logger.info("Worker started in idle mode - session throttled"),e;throw d.app_logger.error("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?(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,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,r){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void o.app_logger.warn("Already ran init!");if(globalThis.hudRunMutex=!0,(0,d.clearInitGuard)(),!o.app_logger.isValid()||!o.customer_logger.isValid())return(0,c.setFirstError)((new c.HudBadLoggerError).code),void h(!0,!0);(0,i.updateUserConfigFromInit)(e,t,r);const g=(0,d.validateAndGetUserInput)();if(!g)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return;if(o.app_logger.info("Initializing hud",{userConfig:Object.entries(s.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new n.MainThread(g.apiKey,g.service,globalThis.hudStartTime,s.hudConfig.userConfig.tags?.value),await l.start(),l.messenger&&(0,c.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 c.HudSessionThrottle)return;o.app_logger.error("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.error("Something went wrong in init & e.stack raised an exception")}h()}},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t._detachAndTerminate=h;const i=r(2546),o=r(523),n=r(5994),s=r(5809),a=r(8528),d=r(8269),c=r(2546),g=r(7274);let l,u=!1;function h(e=!0,t=!1){(0,d.detachHud)(e,t),l&&(0,c.safeCall)(o.app_logger,l.terminateMessenger());const r=(0,d.getLambdaExtensionId)();r&&!u&&(u=!0,(0,c.safeCall)(o.app_logger,(0,i.nextLoopDummy)(r))),(0,d.clearUserIndicatorsTimeouts)(),(0,g.resetCallers)()}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._liftExceptions=s,t.prepCalls=function(e,t){const r=(new Date).toISOString(),n=[];return Object.entries(hudCalls).map(([i,a])=>{Object.entries(a).forEach(([a,d])=>{Object.entries(d).forEach(([d,c])=>{try{if(0===c.sampledCount)return;const o={function_id:i,wrapped_flow_id:d||void 0,wrapped_caller_id:a||void 0,timestamp:r,timeslice:e,exceptions:s(c.exceptions),count:c.count-c.lastSentCounter,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};n.push(o),function(e){e.lastSentCounter=e.count,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(c)}catch(e){o.app_logger.error("Failed preparing invocation, skipping",{func:i,wrappedCaller:a,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})})}),n.length>0&&(0,i.clearMetricsIndicator)(),n},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])for(const r in globalThis.hudCalls[e][t])n(globalThis.hudCalls[e][t][r])};const i=r(8269),o=r(523);function n(e){e.lastSentCounter-=e.count,e.count=0}function s(e){const t={};for(const r in e)t[r]=[{count:e[r]}];return t}},7320:function(e,t,r){var i,o=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,o)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=i(e),s=0;s<r.length;s++)"default"!==r[s]&&o(t,e,r[s]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=s(r(523)),d=s(r(6460)),c=r(5809),g=r(2546),l=r(8528),u=r(2546),h=r(7131),f=r(8269),m=r(2546),p=r(7274),v=r(2702),w=r(8269),k=r(2546),y=r(6281),C=r(2546),b=r(6261),_=a.app_logger,E=m.safeCall.bind(m.safeCall,_);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;abortController;workerKeepaliveGuard;constructor(e){this.worker=e,this.abortController=new AbortController,(0,b.setMaxListeners)(20,this.abortController.signal),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.log(m.UserErrorLogs.ApiKeyDenied(c.hudConfig.userConfig.key?.source)),_.error("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,y._detachAndTerminate)()}catch(e){_.error("Error stopping hud",{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,(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 r={msg:e,content:t};this.worker.postMessage(r)}async checkWorker(e){const t=["started"];let r;try{r=await this.getMessageFromWorker(t,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;r=await this.getMessageFromWorker(t,e/2,!1)}if(!r)throw new m.HudInitError("Worker not started");return r}async checkWorkerInitialized(e){let t;const r=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(r,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;t=await this.getMessageFromWorker(r,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"),E(this.getMode()),E(this.startPeriodicTasks()),E(this.periodicSendMetrics()),E(this.highFrequencySendInvestigations()),E(this.periodicSendProcessedFiles()),E(this.periodicSendEndpoints()),E(this.periodicSendLazyEndpoints()),E(this.periodicSendKafkaJS()),E(this.periodicSendSqs()),E(this.sendStaticNextJsEndpointsOnce()),E(this.periodicSaveMachineMetrics()),E(this.periodicSendReingest()),E(this.resetCallerCounters()),E(this.periodicResetGlobalInvestigationCounter()),E(this.periodicResetInvestigationDedupingCache()),E(this.sendLogsPeriodically(c.hudConfig.logsSendInterval)),E(this.sendRuntime()),E(this.sendPatchedModules()),E(this.sendPreloadedModules()),E(this.dumpModulesAfterWhile(6e4)),E((0,m.loopLogThreadPerformance)(_,c.hudConfig.logPerfInterval,this.abortController.signal));break;case l.HudRunningMode.disabled:_.info("Disabled mode"),E(this.getMode());break;case l.HudRunningMode.detached:_.info("Detached"),(0,y._detachAndTerminate)(!1,!1),this.stop();break;default:_.error("Running mode not handled")}}async getMessageFromWorker(e,t,r=!1,i){let o;e=Array.isArray(e)?e:[e];const n=new AbortController,s=()=>{n.abort()};this.abortController.signal.addEventListener("abort",s);const a=d.setTimeout(t,void 0,{signal:n.signal,ref:r}),c=t=>{try{e.includes(t.msg)&&(o=t,n.abort(),_.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.worker.on("message",c).unref(),i&&this.worker.postMessage(i);try{throw await a,_.warn("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",s),this.worker.off("message",c)}return o}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 periodicSendProcessedFiles(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;let r=!0;await this.setupPeriodicTask(e,t,()=>{if(r){r=!1;try{this._updateTsNodeConfig()&&_.info("ts-node config updated from periodicSendProcessedFiles")}catch{return!1}}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,w.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,w.getSqsQueues)();return e.length>0&&this._sendArray("SqsQueue",e),!0},"periodicSendSqs")}async periodicSendMetrics(){const e=new h.SketchManager(c.hudConfig.huddBinWidth),t=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,r=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,r,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 r=(0,p.prepCalls)(t,e);r.length>0&&this._sendArray("Invocations",r)}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,w.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 periodicSendLazyEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.hudConfig.lazyEndpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendLazyEndpoints(),!0),"periodicSendLazyEndpoints")}sendLazyEndpoints(){const e=(0,w.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)}async terminateWorker(){try{const e=(0,k.suppressTraces)(a.renewFileTransports),t=a.getSavedLogs(),r=e();await this.getMessageFromWorker("terminated",c.hudConfig.workerGrace,!1,{msg:"Terminate",content:{grace:c.hudConfig.workerGrace,logBuffers:t,logFiles:Array.from(r)}})}catch(e){if(!(e instanceof m.HudTimeoutError))throw _.error("Unexpected error, terminating worker"),await this.worker.terminate(),e;_.error("Grace period timeout, terminating worker"),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:r.c[r.s]?.filename};this._sendObject("Runtime",e)}async startPeriodicTasks(){this._sendObject("StartPeriodicTasks",{})}async sendPreloadedModules(){globalThis.hudLoadedModules?this._sendObject("PreInitLoadedModules",{modules:globalThis.hudLoadedModules}):_.warn("Didn't get module, weird....")}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(k.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=(0,k.suppressTraces)(a.renewFileTransports),t=a.getSavedLogs();for(const e of t)try{this._sendObject("Logs",{logs:e})}catch(e){_.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}const r=e();r.size>0&&this._sendObject("LogFilename",{filenames:r})}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,r,i){function o(e){let t=!0;try{t=r(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}),o(e)){for await(const e of(0,u.unrefSetInterval)(t,void 0,{signal:this.abortController.signal}))if(!o(t))return void _.warn("Periodic task failed, stopping task",{firstRun:!1,taskName:i})}else _.warn("Periodic task failed, stopping task",{firstRun:!0,taskName:i})}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,w.setGlobalInvestigationTracking)(0)}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,w.resetInvestigationDedupingCache)()}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,C.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,y._detachAndTerminate)(!1),e}}async sendStaticNextJsEndpointsOnce(){if(!(0,g.isNextJsApp)())return;const e=c.hudConfig.staticNextJsEndpointsInterval,t=c.hudConfig.staticNextJsEndpointsMaxAttempts;let r=0;for await(const i of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){if(r++,_.debug("Attempting to send static next.js endpoints",{attemptCount:r}),(0,w.isNextConfigExtracted)()&&!this.staticNextJsEndpointsSent){_.info("Sending static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)()}),this.staticNextJsEndpointsSent=!0;const e=(0,w.getNextConfig)();this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify(e)});break}if(r>t){_.warn("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)(),attemptCount:r});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 r(i){var o=t[i];if(void 0!==o)return o.exports;var n=t[i]={exports:{}};return e[i].call(n.exports,n,n.exports,r),n.exports}return r.c=t,r(r.s=5119)})());
2
2
  //# sourceMappingURL=core.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 r=t();for(var n in r)("object"==typeof exports?exports:e)[n]=r[n]}}(global,()=>(()=>{var e={336:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5809),o=r(523),s=r(2822),i=r(8949),a=r(8901),c=r(714);class u extends c.FrameworkPatcher{_patch(e){return this._patchSendRequest(e),o.instrument_logger.info("Patched @codegenie/serverless-express/src/frameworks/express.js successfully"),e}_patchSendRequest(e){const t=e.sendRequest;e.sendRequest=function(e){let r,i;const c=a.HttpEndpointMetric.createUsableMetric();try{if(r=e.request,i=e.response,!r||!i)return t.call(this,e);c.start(),c.setRequestAttributes(r),r[n.hudConfig.metricSymbol]=c}catch(e){o.instrument_logger.error("Failed to start flowMetric during sendRequest patching",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}const u=(0,s.runWithInvestigation)(()=>t.call(this,e));try{i.once("finish",function(){try{(0,s.finishHttpInvestigation)(r,i,c),c.setResponseAttributes(i),c.end()}catch(e){o.instrument_logger.error("Failed to end flowMetric during sendRequest patching",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})}catch(e){o.instrument_logger.error("Failed to end flowMetric during sendRequest patching",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return u},(0,i.copyPropertiesToTarget)(t,e.sendRequest)}}t.default=u},486:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5809),o=r(8269),s=r(2546),i=r(523),a=r(8949),c=r(828),u=r(714);class d extends u.FrameworkPatcher{_patch(e){return this._patchConsumer(e),i.instrument_logger.info("Patched KafkaJS successfully"),e}_patchConsumer(e){const t=e.Kafka.prototype.consumer;e.Kafka.prototype.consumer=function(...e){const r=t.apply(this,e);try{const t=new Map,o=[],s=[];!function(e,t){const r=e.subscribe;e.subscribe=async function(...e){const n=await r.apply(this,e);try{const r=e[0].topics;r?r.forEach(e=>{t.push(e)}):e[0].topic?t.push(e[0].topic):i.instrument_logger.warn("No topic found in KafkaJS.Consumer.subscribe",{args:e[0]})}catch(e){i.instrument_logger.error("Error in patching KafkaJS.Consumer.subscribe",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return n},(0,a.copyPropertiesToTarget)(r,e.subscribe)}(r,s),function(e,t,r,o,s){const u=e.run;function d(e,u){const d="eachBatch"===u;for(const e of s)p(e,o,t,r,u);const m=function(e,t,r){return n=>{const o=n[0],s=r?o.batch.topic:o.topic;return function(e,t,r,n){const o=e.get(g(r,n));if(o)return o;for(const e of t)if(e.isBatch===n&&e.pattern.test(r))return e.flowId;i.instrument_logger.warn("No flowId found for topic",{topicName:r,isBatch:n})}(e,t,s,r)}}(t,r,d),h=function(e){return(t,r,o)=>{const s=c.KafkaJSMetric.createUsableMetric();s.start(),s.setFlowId(t);const i=o[0];void 0!==i&&void 0!==i.message&&(i.message[n.hudConfig.metricSymbol]=s);const a=e?i.batch.partition:i.partition,u=e?i.batch.messages[0]?.timestamp:i.message?.timestamp;s.addPartition(a),s.addProducedTimestamp(u),r.flowMetric=s}}(d),_=(0,a.wrapFlow)(m,e[u],!0,h,l,f);e[u]=_}e.run=async function(...e){try{const t=e[0];t.eachMessage&&d(t,"eachMessage"),t.eachBatch&&d(t,"eachBatch")}catch(e){i.instrument_logger.error("Error in patching KafkaJS.Consumer.run",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return await u.apply(this,e)},(0,a.copyPropertiesToTarget)(u,e.run)}(r,t,o,e[0].groupId,s)}catch(e){i.instrument_logger.error("Error in patching KafkaJS.Consumer",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return r},(0,a.copyPropertiesToTarget)(t,e.Kafka.prototype.consumer)}}function l(e,t){const r=t.flowMetric;r?r.end():i.instrument_logger.warn("No flowMetric found for message",{flowId:e})}function f(e,t,r){const n=t.flowMetric;n?(n.setError(r),n.end()):i.instrument_logger.warn("No flowMetric found for message",{flowId:e})}function g(e,t){return e+"|"+t}function p(e,t,r,n,i){const a=(0,s.generateKafkaFlowId)(e,t,i),c={flow_id:a,topic_name:e.toString(),group_id:t,pulling_type:i};(0,o.storeKafkaJSTopicDeclaration)(c),function(e,t,r,n,o){"string"==typeof r?e.set(g(r,n),o):t.push({pattern:r,isBatch:n,flowId:o})}(r,n,e,"eachBatch"===i,a)}t.default=d},523:e=>{"use strict";e.exports=require("./logger")},646:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(523),o=r(8949),s=r(5128),i=r(714);class a extends i.FrameworkPatcher{_patch(e){return this._patchCreate(e),n.instrument_logger.info("Patched NestJS RouterExecutionContext successfully"),e}_patchCreate(e){const t=e.RouterExecutionContext.prototype.create;e.RouterExecutionContext.prototype.create=function(...e){try{const t=e[0],r=e[1];"function"==typeof t.constructor&&"function"==typeof r?e[1]=(0,s.wrapLinkedFunction)(r):n.instrument_logger.error("Invalid args in NestJS RouterExecutionContext.create",{args:e})}catch(e){n.instrument_logger.error("Error in NestJS RouterExecutionContext patcher",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t.apply(this,e)},(0,o.copyPropertiesToTarget)(t,e.RouterExecutionContext.prototype.create)}}t.default=a},714:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.FrameworkPatcher=void 0,t.isSupportedVersion=f,t.extractModuleVersion=g,t.getFrameworkPatcher=function(e){return new(r(2828)(`./${e}`).default)};const a=r(2546),c=r(523),u=r(9896),d=i(r(6928)),l=r(8064);function f(e,t){return""===e||l.satisfies(l.coerce(e),t)}function g(e){try{const t=(0,u.readFileSync)(d.join(e,"package.json"),{encoding:"utf8"}),r=JSON.parse(t).version;return"string"==typeof r?r:""}catch{c.instrument_logger.info("Failed extracting version",{baseDir:e})}return""}t.FrameworkPatcher=class{patch(e,t,r,n,o=this.constructor.name){try{if(this.isSupported(t,o,r,n))return this._patch(e)}catch(e){c.instrument_logger.error("Unhandeled error during patching framework",{framework:o,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return e}isSupported(e,t,r,n){const o=g(e);return!!f(o,r)||(c.instrument_logger.warn("Unsupported version",{framework:t,version:o,supportedVersion:r,basedir:e}),c.customer_logger.log(a.UserErrorLogs.UnsupportedFrameworkVersion(t)),!1)}}},828:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KafkaJSMetric=void 0;const n=r(523),o=r(7131),s=r(9873);class i extends s.FlowMetric{partition;error;producedTimestamp;totalConsumeDuration;constructor(e){super(e)}_createUsableMetric(e){return this}end(){this.producedTimestamp&&(this.totalConsumeDuration=Number(Date.now()-this.producedTimestamp)*Number(1e6)),super.end()}addProducedTimestamp(e){void 0!==e&&(this.producedTimestamp=Number(e))}addPartition(e){this.partition=e}setError(e){this.error=(0,o.extractName)(e)}toRaw(){if(void 0!==this.partition)return{flow_id:this.flowId,type:"KafkaJSMetric",duration:this.duration,partition:this.partition,error:this.error,total_consume_duration:this.totalConsumeDuration};n.instrument_logger.warn("No partition found for message",{flowId:this.flowId})}}t.KafkaJSMetric=i},857:e=>{"use strict";e.exports=require("os")},932:e=>{"use strict";e.exports=require("process")},1326:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(2546),s=r(523),i=r(8949),a=r(714),c=n(r(9589));class u extends a.FrameworkPatcher{static nextJSHudMarked=Symbol.for("hudNextJSMarked");_patch(e){return(0,o.setIsNextJsApp)(!0),this._pathLoad(e),s.instrument_logger.info("Patched Next.js successfully"),e}_pathLoad(e){try{const t=e.RouteModuleLoader;if(t[u.nextJSHudMarked])return e;const r=t.load;t.load=async function(...e){const t=await r.apply(this,e);try{if(t){const e=t.definition?.pathname;e&&!t[u.nextJSHudMarked]&&(c.default._detectAndPatchSupportedMethods(t,e),t[u.nextJSHudMarked]=!0)}}catch(e){s.instrument_logger.error("Failed to patch Next.js route module",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t},t[u.nextJSHudMarked]=!0,(0,i.copyPropertiesToTarget)(r,t.load)}catch(e){s.instrument_logger.error("Failed to patch Next.js base server",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return e}}t.default=u},1427:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getSystemInfo=function(){return{pod_name:u(),node_name:d()}};const o=n(r(9896)),s=n(r(857)),i=Symbol("not found");let a,c;function u(){if(a!==i){if(a)return a;try{return a=s.default.hostname(),a}catch{return void(a=i)}}}function d(){if(c!==i){if(c)return c;try{const e=o.default.readFileSync("/etc/machine-id","utf8").trim();return c=e,c}catch{return void(c=i)}}}},1502:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5809),o=r(8528),s=r(8269),i=r(2546),a=r(523),c=r(8949),u=r(714);class d extends u.FrameworkPatcher{static koaModuleName="koa";static koaPatchedSymbol=Symbol.for(n.hudConfig.hudPatchedName);_patch(e){return this._patchAppUse(e),a.instrument_logger.info("Patched koa successfully"),e}_patchAppUse(e){const t=e.prototype.use;e.prototype.use=function(e){const r=t.apply(this,arguments);try{if(!arguments[0].router)return r;const e=arguments[0].router.stack;for(let t=0;t<e.length;t++)d._wrapRoute(e[t])}catch(e){a.instrument_logger.error("Failed to patch koa.use function",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return r},(0,c.copyPropertiesToTarget)(t,e.prototype.use)}static _wrapRoute(e){if(e.methods&&0===e.methods.length)return;if(!e.stack[0][d.koaPatchedSymbol]){const t=(0,c.wrapFlow)(m,e.stack[0],!0,l);e.stack[0]=t,e.stack[0][d.koaPatchedSymbol]=!0}const t=(0,i.generateEndpointFlowId)(e.path,e.methods);(0,s.storeEndpointDeclaration)(new o.EndpointDeclaration(t,e.methods,"koa",void 0,e.path));for(const r of e.methods)p(t,e.path,r)}}function l(e,t,r){if(!r[0])return void a.instrument_logger.error("No ctx object found in koa");const o=r[0].req;if(!o)return void a.instrument_logger.error("No req found in koa ctx");const s=o[n.hudConfig.metricSymbol];s?s.setFlowId(e):a.instrument_logger.error("No endpoint metric found in koa req")}function f(e,t){return e+"|"+t}t.default=d;const g=new Map;function p(e,t,r){g.set(f(t,r),e)}function m(e){if(0===e.length)return;const t=e[0]._matchedRoute,r=e[0].req?.method;return function(e,t){return g.get(f(e,t))}(t,r)}},2080:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqsMetric=void 0;const n=r(9873);class o extends n.FlowMetric{errors;msgCount;e2eEpocStartTimeMS;e2eDurationNS;_finishedMessageCount;constructor(e){super(e),this._finishedMessageCount=0,this.errors=new Map}addError(e,t=1){this.errors.set(e,(this.errors.get(e)??0)+t)}increaseAndShouldEnd(e=1){return this._finishedMessageCount+=e,!(this.msgCount&&this._finishedMessageCount<this.msgCount)}end(){this.e2eEpocStartTimeMS&&(this.e2eDurationNS=Number(Date.now()-this.e2eEpocStartTimeMS)*Number(1e6)),super.end()}_createUsableMetric(e){return this}toRaw(){return{flow_id:this.flowId,type:"SqsMetric",duration:this.duration,e2e_duration:this.e2eDurationNS,msg_count:this.msgCount,errors:this.errors}}}t.SqsMetric=o},2197:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||o(t,e,r)},a=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.koa=t.express=t.safeLog=t.registerHook=t.hudRITM=void 0;var c=r(5688);Object.defineProperty(t,"hudRITM",{enumerable:!0,get:function(){return c.hudRITM}}),Object.defineProperty(t,"registerHook",{enumerable:!0,get:function(){return c.registerHook}}),Object.defineProperty(t,"safeLog",{enumerable:!0,get:function(){return c.safeLog}}),i(r(3901),t),t.express=a(r(7127)),i(r(714),t),t.koa=a(r(1502)),i(r(7166),t)},2546:e=>{"use strict";e.exports=require("./lib")},2729:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5809),o=r(523),s=r(2822),i=r(8949),a=r(8901),c=r(714);class u extends c.FrameworkPatcher{_patch(e){const t=this._patchGetFramework(e);return o.instrument_logger.info("Patched serverless-http/lib/framework/get-framework.js successfully"),t}_patchGetFramework(e){const t=e;return e=function(...e){const r=t.apply(t.this,e);async function c(e,...t){const i=a.HttpEndpointMetric.createUsableMetric();try{i.start(),i.setRequestAttributes(e),e[n.hudConfig.metricSymbol]=i}catch(e){o.instrument_logger.error("Failed to start flowMetric during framework serverless request handler patching",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}const c=await(0,s.runWithInvestigation)(()=>r.apply(r.this,[e,...t]));return c.once("finish",function(){try{(0,s.finishHttpInvestigation)(e,c,i),i.setResponseAttributes(c),i.end()}catch(e){o.instrument_logger.error("Failed to end flowMetric during framework serverless request handler patching",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}),c}return(0,i.copyPropertiesToTarget)(r,c),c},(0,i.copyPropertiesToTarget)(t,e),e}}t.default=u},2741:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(523),o=r(6730),s=r(4815),i=r(7225),a=r(714);class c extends a.FrameworkPatcher{_patch(e){return i.isVerboseLoggingEnabled?((0,o.patchMethods)(e,"application_export"),(0,s.patchUse)(e,"application",!1),(0,i.logLazyRouter)(e),n.instrument_logger.info("Patched express.Application successfully"),e):(n.instrument_logger.info("Skipping express.Application patching, verbose logging is not enabled"),e)}}t.default=c},2784:e=>{"use strict";e.exports=require("../native/_index")},2822:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStackTrace=l,t.serializableInvestigation=p,t.getBaseInvestigationStorage=m,t.createNewInvestigation=function(){if(!globalThis.hudEnableInvestigation)return;const e=(0,a.getInvestigationStorage)();void 0!==e&&e.enterWith(m())},t.runWithInvestigation=function(e){if(!globalThis.hudEnableInvestigation)return e();const t=(0,a.getInvestigationStorage)();return void 0===t?e():t.run(m(),e)},t.closeInvestigation=h,t.storeInvestigation=_,t.getStacktraceUniqString=b,t.finishHttpInvestigation=function(e,t,r){if(t.statusCode<500)return;try{g("http requests headers",{headers:Object.keys(e.headers)})}catch{g("failed to log http requests headers")}const n=k(r);if(void 0===n)return void g("finishHttpInvestigation: base investigation return undefined");const o=r.getFlowId(),s=r.getMsStartTime();void 0!==o&&void 0!==r.route&&void 0!==r.method&&void 0!==s?_(n,{type:"http",endpoint_uuid:o,route:r.route,method:r.method,timestamp:s,params:e.params,query:e.query,request_body:w(e.body),status_code:t.statusCode,machine_metrics:(0,c.getMachineMetrics)(),observability_identifiers:(0,u.getObservabilityIdentifiers)(e),extra_headers:(0,u.getExtraHeaders)(e),system_info:(0,d.getSystemInfo)()}):g("route, method, or reqTimestamp is undefined even though they shouldn't",{flowId:o,route:r.route,method:r.method,reqTimestamp:s})},t.finishSqsInvestigation=function(e,t){if(0===t.errors.size)return;const r=k(t);if(void 0===r)return void g("finishSqsInvestigation: investigation is undefined");const n=t.getFlowId(),o=t.getMsStartTime();void 0!==o&&void 0!==n?_(r,{type:"sqs",timestamp:o,flow_id:n,messages:w(e),machine_metrics:(0,c.getMachineMetrics)(),system_info:(0,d.getSystemInfo)()}):g("reqTimestamp is undefined even though it shouldn't",{flowId:n})};const n=r(5809),o=r(8528),s=r(8269),i=r(523),a=r(7131),c=r(7808),u=r(7603),d=r(1427);function l(e,t){if(void 0===t)return;const r=function(e){let t=0;for(let r=0;r<e.length;r++)"\n"===e[r]&&t++;return t}(e)+1;let n=-1;for(let e=0;e<r;e++)if(n=t.indexOf("\n",n+1)??-1,-1===n)return;return-1!==n?t.slice(n+1):void 0}const f={};function g(e,...t){let r="debug";(void 0===f[e]||f[e]<n.hudConfig.dynamicConfig.investigationRateLimits.maxUniqLogs)&&(r="warn",f[e]=f[e]+1||1),i.app_logger.logLevel(r,e,...t)}function p(e){return{status:e.status,context:e.context,exceptions:Array.from(Array.from(e.exceptions?.values()??[]).map(({exception:e,executionFlow:t})=>({name:(0,a.extractNameOptional)(e),message:(0,a.extractMessage)(e),stackTrace:l(e.message,e.stack),executionFlow:t}))??[]),userContext:e.userContext}}function m(){return{status:o.InvestigationStatus.Open}}function h(){if(!globalThis.hudEnableInvestigation)return;const e=(0,a.getInvestigationStorage)();if(void 0===e)return;const t=e.getStore();return void 0!==t&&t.status===o.InvestigationStatus.Open?(t.status=o.InvestigationStatus.Closed,t):void 0}function _(e,t){e.context=t,(0,s.storeClosedInvestigation)(p(e))}const y=/.*\((.*):(\d+):(\d+)\)/,v=/.*?(\S*):(\d+):(\d+)/;function b(e){const t=Error.prepareStackTrace;if(void 0===t||"function"!=typeof t)return void g("getStacktraceUniqString: prepareStackTrace is undefined or not a function");let r,n;try{Error.prepareStackTrace=(e,t)=>{r=t[0],n=t};const o=e.stack;if(void 0!==o&&void 0===r){const t=function(e,t){const r=l(t,e);if(void 0===r)return;const n=r.indexOf("\n");return r.slice(0,-1===n?void 0:n)}(o,e.message);if(!t)return void g("getStacktraceUniqString: firstStackTraceLine is undefined",{stack:o,message:e.message});const r=t.match(y);if(r&&r[1]&&r[2]&&r[3])return`${e.name}@${r[1]}:${r[2]}:${r[3]}`;const n=t.match(v);return n&&n[1]&&n[2]&&n[3]?`${e.name}@${n[1]}:${n[2]}:${n[3]}`:void g("getStacktraceUniqString: no match found in regex",{stack:o,message:e.message})}if(void 0===r||void 0===n)return void g("getStacktraceUniqString: result or globCallSites is undefined",{result:void 0===r,globCallSites:void 0===n});Object.defineProperty(e,"stack",{configurable:!0,enumerable:!1,get:()=>t(e,n)})}finally{Error.prepareStackTrace=t}try{return`${e.name}@${r.getFileName()}:${r.getLineNumber()}:${r.getColumnNumber()}`}catch{}}function w(e,t=n.hudConfig.investigation.maxObjectDepth){try{if("string"==typeof e)return e.length>n.hudConfig.investigation.maxStringLength?e.slice(0,n.hudConfig.investigation.maxStringLength)+"...":e;if(Array.isArray(e))return e.slice(0,n.hudConfig.investigation.maxArrayLength).map(e=>w(e,t-1));if(null===e||["number","boolean"].includes(typeof e))return e;if("bigint"==typeof e)return e.toString();if("object"==typeof e){const r={...e};for(const n in e)r[n]=w(e[n],t-1);return r}}catch{}}function k(e){const t=h();if(void 0===t)return void g("finishBaseInvestigation: investigation is undefined");if(void 0===t.firstException)return void g("finishBaseInvestigation: firstException is undefined");if(s.globalInvestigationTracking>=n.hudConfig.dynamicConfig.investigationRateLimits.maxTotalInvestigations)return void g("finishBaseInvestigation: globalInvestigationTracking is greater than maxTotalInvestigations",{globalInvestigationTracking:s.globalInvestigationTracking,maxTotalInvestigations:n.hudConfig.dynamicConfig.investigationRateLimits.maxTotalInvestigations});const r=e.getFlowId();if(void 0===r)return void g("finishBaseInvestigation: flowId is undefined");const o=b(t.firstException);if(void 0===o)return void g("finishBaseInvestigation: exceptionUniqString is undefined");const i=((0,s.getInvestigationDedupingCache)(r).get(o)??0)+1;if(!(i>n.hudConfig.dynamicConfig.investigationRateLimits.maxSameInvestigations))return(0,s.increaseGlobalInvestigationTracking)(),(0,s.increaseInvestigationDedupingCache)(r,o),t;g("finishBaseInvestigation: investigationCount is greater than maxSameInvestigations",{investigationCount:i,maxSameInvestigations:n.hudConfig.dynamicConfig.investigationRateLimits.maxSameInvestigations})}},2828:(e,t,r)=>{var n={"./codeGenieServerlessExpress":336,"./codeGenieServerlessExpress.ts":336,"./express":7127,"./express.ts":7127,"./express/methods":6730,"./express/methods.ts":6730,"./express/route":2977,"./express/route.ts":2977,"./express/router":4815,"./express/router.ts":4815,"./express/verbosity":7225,"./express/verbosity.ts":7225,"./expressApplication":2741,"./expressApplication.ts":2741,"./flows/endpoints/metrics":8901,"./flows/endpoints/metrics.ts":8901,"./flows/flow":9873,"./flows/flow.ts":9873,"./flows/graphql":6504,"./flows/graphql.ts":6504,"./flows/kafkajs":828,"./flows/kafkajs.ts":828,"./flows/sqs":2080,"./flows/sqs.ts":2080,"./frameworkPatcher":714,"./frameworkPatcher.ts":714,"./graphql":7214,"./graphql.ts":7214,"./http":5459,"./http.ts":5459,"./kafkajs":486,"./kafkajs.ts":486,"./koa":1502,"./koa.ts":1502,"./nestjsRouterExecutionContext":646,"./nestjsRouterExecutionContext.ts":646,"./nestjsRpcContextCreator":4290,"./nestjsRpcContextCreator.ts":4290,"./nextJsConfig":9723,"./nextJsConfig.ts":9723,"./nextJsModuleLoader":1326,"./nextJsModuleLoader.ts":1326,"./nextRequestAdapter":7246,"./nextRequestAdapter.ts":7246,"./nextjs":9589,"./nextjs.ts":9589,"./router":5946,"./router.ts":5946,"./serverlessHttp":2729,"./serverlessHttp.ts":2729,"./sqsConsumer":5150,"./sqsConsumer.ts":5150};function o(e){var t=s(e);return r(t)}function s(e){if(!r.o(n,e)){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}return n[e]}o.keys=function(){return Object.keys(n)},o.resolve=s,e.exports=o,o.id=2828},2977:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.patchRoute=function(e){const t=(0,g.getMethods)();t.concat("all").forEach(function(r){const n=e.prototype[r];e.prototype[r]=function(){let e;try{e=p(Array.prototype.slice.call(arguments));let n=function(e){const t=e[0][a.hudConfig.express.layerStateSymbol];if(t)return t.flowId}(e);const o=function(e){const t=e[0][a.hudConfig.express.layerStateSymbol];if(t)return t.kind}(e),s=function(e){const t=e[0][a.hudConfig.express.layerStateSymbol];return!!t&&t.allMethod}(e);if(n||(n=[l.randomUUID()]),"application"===o)if(Array.isArray(this.path)){_(e,void 0);for(let e=0;e<this.path.length;e++)h(n[e],s?t:[r],this.path[e])}else _(e,n[0]),h(n[0],s?t:[r],this.path);else if("router"===o)if(Array.isArray(this.path)){_(e,void 0);for(let e=0;e<this.path.length;e++)m(this,n[e],r,this.path[e])}else _(e,n[0]),m(this,n[0],r,this.path);else _(e,n[0]),m(this,n[0],r,this.path)}catch(e){d.instrument_logger.error("Failed to patch express.Route.route",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return n.apply(this,e||arguments)}})};const a=r(5809),c=r(8528),u=r(8269),d=r(523),l=i(r(6982)),f=r(8949),g=r(6730),p=r(5673);function m(e,t,r,n){!function(e,t,r,n){e[a.hudConfig.express.layerStateSymbol]||(e[a.hudConfig.express.layerStateSymbol]={}),e[a.hudConfig.express.layerStateSymbol][t]?e[a.hudConfig.express.layerStateSymbol][t].methods.push(r):e[a.hudConfig.express.layerStateSymbol][t]={layerPath:n,methods:[r]}}(e,t,r,n),function(e,t,r){const n=new c.EndpointDeclaration(e,[t],"express",void 0,void 0,r);(0,u.storePartialEndpointDeclaration)(n),(0,u.storeExpressEndpointDeclaration)(n)}(t,r,n)}function h(e,t,r){const n=new c.EndpointDeclaration(e,t,"express",void 0,r,void 0);(0,u.storeExpressEndpointDeclaration)(n)}function _(e,t){if(e&&!(e.length<1)){if(a.hudConfig.express.wrapAllCallbacks)for(let r=0;r<e.length;r++){const n=(0,f.wrapFlow)(v(t),e[r],!0,b);e[r]=n}else{const r=(0,f.wrapFlow)(v(t),e[e.length-1],!0,b);e[e.length-1]=r}return t}}function y(e){return(0,u.getLinkedConsistentFlowId)(e,!1)||(d.instrument_logger.warn("No consistent flowId found, returning temporary flow id",{flowId:e}),e)}function v(e){return e?function(){return y(e)}:function(e){const t=e[0]?.route[a.hudConfig.express.layerStateSymbol],r=e[0]?.url;if(t)for(const[e,n]of Object.entries(t)){if(n.layerPath instanceof RegExp&&n.layerPath.test(r))return y(e);if(r.includes(n.layerPath))return y(e)}d.instrument_logger.warn("No flowId found for path",{states:t,url:r.split("?")[0]})}}function b(e,t,r){let n=0;if(4===r.length)n=1;else if(3!==r.length)return void d.instrument_logger.error("Invalid number of arguments in express request",{length:r.length});if(!r[n])return void d.instrument_logger.error("No request object in express request");const o=r[n][a.hudConfig.metricSymbol];o?o.setFlowId(e):d.instrument_logger.error("No endpoint metric found in express request")}},2987:e=>{"use strict";e.exports=require("perf_hooks")},3176:e=>{"use strict";e.exports=require("buffer-crc32")},3339:e=>{"use strict";e.exports=require("module")},3868:e=>{"use strict";e.exports=require("@jridgewell/sourcemap-codec")},3901:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getFunctionWrapperTemplate=b,t.splitCode=E,t.editInSplits=I,t.editWithCliBuildId=function(e,t,r,n){let{transformedCode:o,metadatas:s}=F(e,t,r,[],!0);return o+=`\n//# sourceMappingURL=${y.default.basename(t)}.map`,o+=`\n//"${n}";${d.hudConfig.cliSdkVersionVarName}="${d.SDK_VERSION}";${d.hudConfig.cliBuildIdVarName}`,{transformedCode:o,metadatas:s}},t.edit=F,t.incrementInstrumentedFunctionsCount=T;const c=a(r(3176)),u=r(3903),d=r(5809),l=r(2546),f=r(523),g=r(8528),p=r(8269),m=r(2546),h=r(3868),_=i(r(2784)),y=a(r(6928)),v=/([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})/;function b(e,t,r=!1){const n=`${e}_hudTemp`,o="BODY_PLACEHOLDER",s="FUNCTION_ID_PLACEHOLDER",i="AWAITABLE_PLACEHOLDER",a="EXCEPTION_VARIABLE_PLACEHOLDER",c=function(e,t,r=!1){const n=[];if(r)return n;let o;t===g.Format.cjs?o="require":t===g.Format.esm&&(n.push(`import { createRequire as ${e}_createRequire } from "module";`,`const ${e}_require = ${e}_createRequire(import.meta.url);`),o=`${e}_require`);const s=m.myRequire.resolve(d.SDK_MODULE_NAME+"/wrap");return n.push(`let ${e}_temp;`,`try { ${e}_temp = ${o}(String.raw\`${s}\`); } catch (e) { ${e}_temp = { wrapperInitial: () => {}, wrapperCatch: () => {}, wrapperFinally: () => {}, fixStack: () => {}, wrapperUserCatch: () => {} }; }`,`const { wrapperInitial: ${e}_wi, wrapperCatch: ${e}_wc, wrapperFinally: ${e}_wf, fixStack: ${e}_fs, asyncIteratorWrapper: ${e}_aiw, wrapperUserCatch: ${e}_wuc } = ${e}_temp;`),n}(e,t,r);return{functionWrapper:`{\n let ${n};\n const ${d.hudConfig.functionIdVarName} = ${s};\n const ${e}_cc = {};\n try {\n ${e}_wi(${d.hudConfig.functionIdVarName}, ${e}_cc);\n } catch (e) {\n globalThis._hud_SI = { value: 0 };\n globalThis._hud_S = [];\n }\n try {\n ${o}\n } catch (e) {\n try {\n ${e}_wc(${d.hudConfig.functionIdVarName}, ${e}_cc, e);\n } catch (e) {}\n throw e;\n } finally {\n try {\n ${e}_wf(${d.hudConfig.functionIdVarName}, ${e}_cc);\n } catch (e) {}\n }\n }`,awaitWrapper:`(${n} = ${i}, _hud_SI.value--, ${e}_cc.ff = true, ${n} = await ${n}, _hud_S[++_hud_SI.value] = ${d.hudConfig.functionIdVarName}, ${e}_cc.ff= false, ${n})`,yieldWrapper:`\n function* ${e}_generatorWrapper() {\n return (${n} = ${i}, _hud_SI.value--, ${e}_cc.ff = true, ${n} = yield ${n}, _hud_S[++_hud_SI.value] = ${d.hudConfig.functionIdVarName}, ${e}_cc.ff= false, ${n})\n }`,yieldStarWrapper:`\n function* ${e}_generatorWrapper() {\n return (${n} = ${i}, _hud_SI.value--, ${e}_cc.ff = true, ${n} = yield* ${n}, _hud_S[++_hud_SI.value] = ${d.hudConfig.functionIdVarName}, ${e}_cc.ff= false, ${n})\n }`,initialStatements:c,bodyPlaceholder:o,functionIdPlaceholder:s,awaitablePlaceholder:i,fixStackFunction:`\n try{\n ${e}_fs(${d.hudConfig.functionIdVarName}, ${e}_cc)\n }catch(e){};`,exceptionVariablePlaceholder:a,wrapperUserCatch:`\n try {\n ${e}_wuc(${d.hudConfig.functionIdVarName}, ${e}_cc, ${a});\n } catch(e){};`,asyncIteratorWrapper:`${e}_aiw`,awaitableVariable:n}}function w(e,t,r,n=!0,o=!1,s){const i=Error.prepareStackTrace;let a=!1,l=function(e){const t=e.match(`${d.hudConfig.bundlerBuildIdVarName}="${v.source}"`);if(t&&t.length>0)return t[1]}(e);l||(l=function(e){return(0,u.v5)(e,d.hudConfig.bundlerBuildUuidNamespace)}(e),a=!0);const g=(0,u.v5)(e,d.hudConfig.functionUuidNamespace),p=(0,c.default)(t.filename).readUInt32BE(),h=(0,c.default)(e).readUInt32BE(),y=(0,m.isNextJsApp)(),w={data:t,bundlerBuildId:l,prefix:d.hudConfig.wrapVarPrefix,...b(d.hudConfig.wrapVarPrefix,t.format,o),uuidNamespace:d.hudConfig.functionUuidNamespace,fileHash:g,functionsToInstrument:r,useInputSourcemap:n,isNextJsFile:y,markCode:d.hudConfig.nextJsMarkVarName,enableForAwaitInstrumentation:!s},k=_.transform(e,w);return T(k.functionsIds.length,s),y&&k.marksCount!==k.functionsIds.length&&f.instrument_logger.warn("Marks count mismatch while instrumenting functions",{marksCount:k.marksCount,functionsIdsLength:k.functionsIds.length,filename:t.filename}),Error.prepareStackTrace=i,f.instrument_logger.debug(`Successfully transformed ${t.filename}`),{code:k.code,map:k.map,functionIds:k.functionsIds,filename:t.filename,hasInputMap:k.isInputSourcemap,bundlerBuildId:l,bundlerBuildIdGenerated:a,file_path_checksum:p,file_checksum:h,sourceCodeHash:g,moduleBase:k.moduleBase,isNextJsApp:y,marksCount:k.marksCount,detectedForAwaitLoops:k.detectedForAwaitLoops}}class k extends Error{}function S(e,t){if(e&&t)throw new k("Start mark found inside mark");if(!e&&!t)throw new k("End mark found outside mark")}function x(e,t,r,n){const o=e.split("\n");let s=r,i=n;return s+=o.length-1,s+=t.split("\n").length-1,s===r?i+=o.pop()?.length||0:i=o.pop()?.length||0,{lineOffset:s,columnOffset:i}}function*E(e){let t=!1,r=0,n=0,o=!1,s=0,i=0;const a=new RegExp(`globalThis\\s*?&&\\s*?\\(globalThis\\.${d.hudConfig.esbuildGlobalVar}\\s*?=\\s*?"(Start|End):(?<fileName>.*?)"\\);?`,"g");for(const c of e.matchAll(a)){if(o=!0,!c.groups)throw new k("No groups found in match");const{fileName:a}=c.groups,[u,d]=c,l="Start"===d;S(l,t);let f="";if(t){const t=c.index+u.length;f=e.slice(r,t);const o=n+Buffer.byteLength(f,"utf8");yield{edit:!0,code:f,fileName:a,lineOffset:s,columnOffset:i,indexOffset:n,indexOffsetEnd:o},r=t,n=o}else{const t=c.index;f=e.slice(r,t),n+=Buffer.byteLength(f,"utf8"),r=t,yield{edit:!1,code:f}}t=!!l,({lineOffset:s,columnOffset:i}=x(f,u,s,i))}if(t)throw new k("End mark found outside mark");o?r<e.length&&(yield{edit:!1,code:e.slice(r)}):yield{edit:!1,code:e}}function M(e,t,r){f.instrument_logger.debug("Edit chunk",{fileName:e.fileName,size:e.code.length,edit:t}),r?.push({fileName:e.fileName,size:e.code.length,edit:t})}function C(e,t,r){const n=w(e.code,{filename:t,format:r},[],!1,!0,!1),o=n.code;return n.mapRelativeToChunk=n.map,n.map=function(e,t,r){"string"==typeof e&&(e=JSON.parse(e));const n=(0,h.decode)(e.mappings);return n.forEach(e=>{e.forEach(e=>{e.length>=4&&"number"==typeof e[2]&&("number"==typeof e[3]&&0===e[2]&&(e[3]+=r),e[2]+=t)})}),JSON.stringify({...e,mappings:(0,h.encode)(n),sourcesContent:void 0})}(n.map,e.lineOffset,e.columnOffset),{codeToAppend:o,metadata:{...n,filename:t,lineOffset:e.lineOffset,columnOffset:e.columnOffset}}}function I(e,t,r,n=!1,o=!1,s=()=>!0){const i=e.slice(-1e3);if(!o&&null!==_.getSourceMap(t,i))return f.instrument_logger.error("Source map found for esbuild split",{filename:t}),f.customer_logger.log(l.UserErrorLogs.EsbuildSourceMapFound()),(0,p.detachHud)(!1,!1),{transformedCode:e,metadatas:[],editedChunksSizes:void 0};let a="",c=0,u=0;const g=[];let m=0;const h=n?[]:void 0,y=b(d.hudConfig.wrapVarPrefix,r).initialStatements.join("\n"),v=function(e){return e.slice(d.hudConfig.esbuildMark.length,d.hudConfig.esbuildMark.length+36)}(e);for(const n of E(e)){m++;try{let e="",o=!1;if(n.edit&&(o=s(n.fileName),h&&M(n,o,h)),n.edit&&o){const o=C(n,t,r);e=o.codeToAppend,g.push({...o.metadata,bundlerBuildId:v,transformedLineOffset:c,transformedColumnOffset:u,indexOffset:n.indexOffset,indexOffsetEnd:n.indexOffsetEnd})}else e=0===a.length?P(n.code,y):n.code;({transformedCodeLineOffset:c,transformedCodeColumnOffset:u}=O(e,c,u)),a+=e}catch(r){return f.instrument_logger.error("Failed to patch index",{index:m,filename:t,msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0}),{transformedCode:e,metadatas:[],editedChunksSizes:h}}}return{transformedCode:a,metadatas:g,editedChunksSizes:h}}function P(e,t){let r="";return e.startsWith('"use strict";')?(r+='"use strict";',r+=t,r+=e.slice(13),r):(r+=t,r+=e,r)}function O(e,t,r){const n=e.split("\n");return n.length>1?(t+=n.length-1,r=n.pop()?.length||0):r+=e.length,{transformedCodeLineOffset:t,transformedCodeColumnOffset:r}}function F(e,t,r,n,o){if(e.startsWith(d.hudConfig.esbuildMark))return f.instrument_logger.info("Editing in splits"),I(e,t,r,!1);{const s=w(e,{filename:t,format:r},n,d.hudConfig.userConfig.disableSourceMapsResolution?.value??!0,!1,o);return{transformedCode:s.code,metadatas:[s]}}}let N=0;function T(e,t){N+=e;const r=d.hudConfig.userConfig?.maxMappedFunctions?.value??0;N>=r&&(t||f.customer_logger.log(l.UserErrorLogs.InstrumentedFunctionCountExceeded(r)),f.app_logger.error("Instrumented function count exceeded",{instrumentedFunctionsCount:N,maxMappedFunctions:r}),(0,p.detachHud)(!1,!1))}},3903:e=>{"use strict";e.exports=require("uuid")},4290:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(523),o=r(8949),s=r(5128),i=r(714);class a extends i.FrameworkPatcher{_patch(e){return this._patchCreate(e),n.instrument_logger.info("Patched NestJS RpcContextCreator successfully"),e}_patchCreate(e){const t=e.RpcContextCreator.prototype.create;e.RpcContextCreator.prototype.create=function(...e){try{const t=e[0],r=e[1];"function"==typeof t.constructor&&"function"==typeof r?e[1]=(0,s.wrapLinkedFunction)(r):n.instrument_logger.error("Invalid args in NestJS RpcContextCreator.create",{args:e})}catch(e){n.instrument_logger.error("Error in NestJS RpcContextCreator patcher",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t.apply(this,e)},(0,o.copyPropertiesToTarget)(t,e.RpcContextCreator.prototype.create)}}t.default=a},4815:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.patchUse=function(e,t,r=!0){const n=e.use;e.use=function(e){const o=n.apply(this,arguments);try{let n=this[f.uuidSymbol];!n&&f.isVerboseLoggingEnabled&&(n=d.randomUUID(),this[f.uuidSymbol]=n,u.instrument_logger.info("Express use setting uuid",{kind:t,uuid:n})),"application"===t?function(e,t,r,n){try{r&&(e._router?p(e._router):e.router?p(e.router):u.instrument_logger.warn("Express application doesn't have router or _router")),n&&f.isVerboseLoggingEnabled&&u.instrument_logger.info("Express use app",{parent:n,child:t[1]?.[f.uuidSymbol]||"no uuid",path:t[0]})}catch(e){u.instrument_logger.error("Failed to save express app router",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}(this,arguments,r,n):"router"===t&&function(e,t,r,n,o){try{if(!e.stack)return void u.instrument_logger.error("Express router without stack");if(0===e.stack.length)return void u.instrument_logger.warn("Express router with an empty stack");"query"===e.stack[0].name?p(e):f.isVerboseLoggingEnabled&&!f.skipLayerNamesLogs.has(e.stack[0].name)&&(f.skipLayerNamesLogs.add(e.stack[0].name),u.instrument_logger.warn("Found unknown stack name",{stack:e.stack[0].name}));const{path:s,offset:i}=function(e){let t=0,r="/";if("function"!=typeof e){let n=e;for(;Array.isArray(n)&&0!==n.length;)n=n[0];"function"!=typeof n&&(t=1,r=e)}return{path:r,offset:t}}(o),c=g(Array.prototype.slice.call(t,i));for(let t=0;t<c.length&&t<e.stack.length;t++){const o=e.stack[e.stack.length-t-1],i=c[c.length-t-1];"router"===o.name?(i&&!i[f.uuidSymbol]&&f.isVerboseLoggingEnabled&&(i[f.uuidSymbol]=d.randomUUID(),u.instrument_logger.info("Express handle router setting uuid",{uuid:i[f.uuidSymbol]})),r&&(o[a.hudConfig.express.routeNamesSymbol]=s)):f.isVerboseLoggingEnabled&&!f.skipLayerNamesLogs.has(o.name)&&(f.skipLayerNamesLogs.add(o.name),u.instrument_logger.warn("Found unknown layer name",{layer:o.name,parent:n,child:i[f.uuidSymbol]||"no uuid",path:s}))}}catch(e){u.instrument_logger.error("Failed to patch router.use function",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}(this,arguments,r,n,e)}catch(e){u.instrument_logger.error("Failed to patch express.use function",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return o},(0,l.copyPropertiesToTarget)(n,e.use)},t.extractEndpointsFromRouter=function e(t,r){let n=[];if(!r.stack)return u.instrument_logger.error("Router without stack - bad OTEL version",{router:r}),n;for(const o of r.stack)if("router"===o.name){if(!o[a.hudConfig.express.routeNamesSymbol]){u.instrument_logger.error("Router layer without routes",{layer:o});continue}const r=t+o[a.hudConfig.express.routeNamesSymbol];n=n.concat(e(r,o.handle))}else o.route&&o.route[a.hudConfig.express.layerStateSymbol]?n=n.concat(m(o,t)):f.isVerboseLoggingEnabled&&!f.skipLayerNamesLogs.has(o.name)&&(f.skipLayerNamesLogs.add(o.name),u.instrument_logger.warn("Found unknown layer name when extracting endpoints",{layer:o.name}));return n};const a=r(5809),c=r(8528),u=r(523),d=i(r(6982)),l=r(8949),f=r(7225),g=r(5673);function p(e){e[a.hudConfig.express.markedSymbol]||(globalThis.hudExpressState.push(e),e[a.hudConfig.express.markedSymbol]=!0)}function m(e,t){const r=[];for(const[n,o]of Object.entries(e.route[a.hudConfig.express.layerStateSymbol]))r.push(new c.EndpointDeclaration(n,o.methods,"express",t,o.layerPath));return Array.from(r.values())}},5128:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHudLfMarked=void 0,t.wrapLinkedFunction=function(e){if(e[t.isHudLfMarked])return e;let r;e[t.isHudLfMarked]=!0;const a=(0,s.getFlowStateStorage)();return a?(r=e instanceof i.AsyncFunction?async function(...t){if(hudRunningMode!==n.HudRunningMode.enabled)return await e.apply(this,t);let r;try{r=a.getStore()}catch(r){return o.instrument_logger.error("Failed to get flowState",{msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0}),await e.apply(this,t)}return r?(r.shouldLinkFunction=!0,await e.apply(this,t)):await e.apply(this,t)}:function(...t){if(hudRunningMode!==n.HudRunningMode.enabled)return e.apply(this,t);let r;try{r=a.getStore()}catch(r){return o.instrument_logger.error("Failed to get flowState",{msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0}),e.apply(this,t)}return r?(r.shouldLinkFunction=!0,e.apply(this,t)):e.apply(this,t)},(0,i.copyPropertiesToTarget)(e,r),r):e};const n=r(8528),o=r(523),s=r(7131),i=r(8949);t.isHudLfMarked=Symbol.for("isHudLfMarked")},5150:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5809),o=r(8269),s=r(2546),i=r(523),a=r(7131),c=r(2822),u=r(8949),d=r(2080),l=r(714);class f extends l.FrameworkPatcher{isSupported(e,t,r,o){const a=n.hudConfig.userConfig.enableDapulse?.value?o.mondayVersion:o.bbcVersion,c=(0,l.extractModuleVersion)(e);return!!(0,l.isSupportedVersion)(c,a)||(i.instrument_logger.warn("Unsupported sqs-consumer version",{framework:"SqsConsumer",version:c,supportedVersion:a,basedir:e,isDapulse:n.hudConfig.userConfig.enableDapulse?.value}),i.customer_logger.log(s.UserErrorLogs.UnsupportedFrameworkVersion("sqs-consumer")),!1)}_patch(e){return function(e){const t=e.Consumer.create;e.Consumer.create=function(...e){const r=t.apply(this,e);try{!function(e){const t=e.queueUrl;if(!t)throw new s.HudNoQueueUrlInSqsConsumer;const r=m(t);if(e.handleMessageBatch&&"function"==typeof e.handleMessageBatch){const t="handleMessageBatch",n=(0,s.generateSqsFlowId)(r,t);(0,o.storeSqsQueueDeclaration)({flow_id:n,queue_name:r,handle_type:t,batch_size:e.batchSize});const i=e.handleMessageBatch,a=(0,u.wrapFlow)(()=>n,i,!0,h);return void(e.handleMessageBatch=a)}if(e.handleMessage&&"function"==typeof e.handleMessage){const t="handleMessage",n=(0,s.generateSqsFlowId)(r,t);(0,o.storeSqsQueueDeclaration)({flow_id:n,queue_name:r,handle_type:t});const i=e.handleMessage,a=(0,u.wrapFlow)(()=>n,i,!0,h);return void(e.handleMessage=a)}i.instrument_logger.warn("Unable to getFlowId - No handleMessage or handleMessageBatch found in SqsConsumer.Consumer",{queueName:r})}(r),function(e){const t=e.on;e.on=function(...r){try{const t=r[0];if(!t||"string"!=typeof t)throw new s.HudNoEventTypeInSqsConsumerOn;const n=r[1];if(!n||"function"!=typeof n)throw new s.HudNoCallbackInSqsConsumerOn;const i=m(e.queueUrl),a="event",c=(0,s.generateSqsFlowId)(i,a,t);(0,o.storeSqsQueueDeclaration)({flow_id:c,queue_name:i,handle_type:a,event_type:t}),r[1]=(0,u.wrapFlow)(()=>c,n,!0,_,y,v)}catch(e){i.instrument_logger.error("Error in SqsConsumer.Consumer.on patched logic",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t.apply(this,r)},(0,u.copyPropertiesToTarget)(t,e.on)}(r),function(e){const t=e.emit;e.emit=function(...e){return function(e){try{const t=e[0];if(!t||"string"!=typeof t)throw new s.HudNoEventTypeInSqsConsumerEmit;let r,o;if("message_processed"===t&&(r=1),["error","timeout_error","processing_error"].includes(t)&&(o=1,r=2),void 0===r)return;const u=e[r];if(!u)throw new s.HudNoMessageInSqsConsumerEmit;let d;if(void 0!==o){const t=e[o];if(!(t&&t instanceof Error))throw new s.HudNoErrorInSqsConsumerEmit;d=(0,a.extractName)(t),"StandardError"===d&&t.cause&&t.cause instanceof Error&&(d=(0,a.extractName)(t.cause))}const l=(e,t)=>{const r=e[n.hudConfig.metricSymbol];r?(d&&r.addError(d,t),r.increaseAndShouldEnd(t)&&(r.end(),(0,c.finishSqsInvestigation)(Array.isArray(u)?u:[u],r))):p||(p=!0,i.instrument_logger.warn("No metric found for message"))};Array.isArray(u)&&u.length>=1?l(u[0],u.length):l(u,1)}catch(e){g||(g=!0,i.instrument_logger.error("Error in SqsConsumer.Consumer.emit patched logic",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}))}}(e),t.apply(this,e)},(0,u.copyPropertiesToTarget)(t,e.emit)}(r)}catch(e){i.instrument_logger.error("Error in patching SqsConsumer.Consumer",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return r},(0,u.copyPropertiesToTarget)(t,e.Consumer.create)}(e),i.instrument_logger.info("Patched sqs-consumer successfully",{isDapulse:n.hudConfig.userConfig.enableDapulse?.value}),e}}t.default=f;let g=!1,p=!1;function m(e){const t=e.split("/").pop();if(!t)throw new s.HudFailExtractSqsQueueName(`Url: ${e}`);return t}function h(e,t,r){const o=d.SqsMetric.createUsableMetric(e);o.start();const s=r[0];if(!s)return i.instrument_logger.warn("No messages pass to sqs handler",{flowId:e}),void(t.flowMetric=o);if(Array.isArray(s)){if(o.msgCount=s.length,s.forEach(e=>{e[n.hudConfig.metricSymbol]=o}),s[0]?.Attributes?.SentTimestamp){const t=s.reduce((e,t)=>{const r=Number.parseInt(t?.Attributes?.SentTimestamp);return isNaN(r)?e:Math.min(e,r)},1/0);t!==1/0?o.e2eEpocStartTimeMS=t:i.instrument_logger.warn("No valid SentTimestamp found eventhough the first element had SentTimestamp",{flowId:e})}}else o.msgCount=1,s[n.hudConfig.metricSymbol]=o,s?.Attributes?.SentTimestamp&&(o.e2eEpocStartTimeMS=s.Attributes.SentTimestamp);t.flowMetric=o,(0,c.createNewInvestigation)()}function _(e,t,r){const n=d.SqsMetric.createUsableMetric(e);n.start(),t.flowMetric=n}function y(e,t){const r=t.flowMetric;r?r.end():i.instrument_logger.warn("No flowMetric found for message during catch",{flowId:e})}function v(e,t,r){const n=t.flowMetric;n?(n.addError((0,a.extractName)(r)),n.end()):i.instrument_logger.warn("No flowMetric found for message during catch",{flowId:e})}},5459:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getHttpMetricFromRequest=function(e){return e[n.hudConfig.metricSymbol]};const n=r(5809),o=r(523),s=r(2822),i=r(8949),a=r(8901),c=r(714);class u extends c.FrameworkPatcher{_patch(e){return this._patchEmit(e),o.instrument_logger.info("Patched http successfully"),e}_patchEmit(e){const t=e.Server.prototype.emit;e.Server.prototype.emit=function(e,...r){if("request"!==e)return t.apply(this,[e,...r]);try{const e=r[0],t=r[1],i=a.HttpEndpointMetric.createUsableMetric();i.start(),(0,s.createNewInvestigation)(),i.setRequestAttributes(e),t.once("finish",function(){try{(0,s.finishHttpInvestigation)(e,t,i),i.setResponseAttributes(t),i.end()}catch(e){o.instrument_logger.error("Failed to set response attributes",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}),e[n.hudConfig.metricSymbol]=i}catch(e){o.instrument_logger.error("Failed to patch http.Server.prototype.emit",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t.apply(this,[e,...r])},(0,i.copyPropertiesToTarget)(t,e.Server.prototype.emit)}}t.default=u},5673:e=>{"use strict";e.exports=require("array-flatten")},5688:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hudRITM=void 0,t.safeLog=function(e){try{i.app_logger.debug(e)}catch{return}},t.registerHook=function(){if(i.app_logger.info("HUD is required"),process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE){if(i.app_logger.info("Running in Lambda environment"),parseInt(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE)<n.hudConfig.lambdaMinimunMemory){const e=process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE;return i.app_logger.warn("Lambda function memory size is less than required, Hud will not run",{memorySize:e}),i.customer_logger.log(s.UserErrorLogs.UnsupportedLambdaMemory(n.hudConfig.lambdaMinimunMemory)),!1}globalThis.hudRuningInsideLambda=!0}return(0,o.initGlobals)(),i.app_logger.debug("InitGlobals done"),!(globalThis.hudStartFromAutoInit&&!(0,o.validateAndGetUserInput)())&&(i.instrument_logger.isValid()?globalThis.hudRanOnRequire?(i.instrument_logger.warn("Already ran onRequire!"),!1):(globalThis.hudRanOnRequire=!0,i.instrument_logger.info("Using module",{name:n.SDK_MODULE_NAME}),n.hudConfig.userConfig.enableFrameworks&&i.instrument_logger.info("User enabled frameworks",{frameworks:(0,a.getEnabledFrameworks)()}),(0,a.onRequire)(),(0,s.detectNextJsApp)(),i.instrument_logger.debug("onRequire done"),globalThis.hudInitGuard=setTimeout(c,n.hudConfig.userConfig.maxTimeUntilInitSessionMs?.value??0),globalThis.hudInitGuard.unref(),!0):((0,o.detachHud)(!1),!1))};const n=r(5809),o=r(8269),s=r(2546),i=r(523),a=r(7166);function c(){i.instrument_logger.warn("Init timeout disabling hud!"),i.customer_logger.log(s.UserErrorLogs.InitTimeout(globalThis.hudIsRunningFromSetup)),(0,o.detachHud)(!1)}t.hudRITM=a.onRequireFn},5809:e=>{"use strict";e.exports=require("./config")},5946:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(523),o=r(6730),s=r(4815),i=r(714);class a extends i.FrameworkPatcher{_patch(e){return(0,s.patchUse)(e.prototype,"router"),(0,o.patchMethods)(e.prototype,"router"),n.instrument_logger.info("Patched router successfully"),e}}t.default=a},6093:e=>{"use strict";e.exports=require("@cspotcode/source-map-support")},6504:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GraphQLMetric=void 0;const n=r(9873);class o extends n.FlowMetric{constructor(e){super(e)}_createUsableMetric(e){return this}toRaw(){return{flow_id:this.flowId,type:"GraphQLMetric",duration:this.duration}}}t.GraphQLMetric=o},6730:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.getMethods=f,t.patchMethods=function(e,t){f().concat("all").forEach(function(r){const n=e[r];if(!n)return void(l.isVerboseLoggingEnabled&&c.instrument_logger.warn("Method not found",{method:r}));const o="all"===r;e[r]=function(){try{if(arguments.length<2)return n.apply(this,arguments);let e=this[l.uuidSymbol];l.isVerboseLoggingEnabled&&(e||(e=u.randomUUID(),this[l.uuidSymbol]=e,c.instrument_logger.info("Express method setting uuid",{uuid:e,kind:t})),c.instrument_logger.info("Express added new method",{method:r,uuid:e,path:arguments[0]}));const s=Array.prototype.slice.call(arguments);if(s[1][a.hudConfig.express.layerStateSymbol]={flowId:[],kind:t,allMethod:o},Array.isArray(s[0]))for(const e of s[0]){const e=u.randomUUID();s[1][a.hudConfig.express.layerStateSymbol].flowId.push(e)}else s[1][a.hudConfig.express.layerStateSymbol].flowId.push(u.randomUUID());const i=n.apply(this,s);try{delete s[1][a.hudConfig.express.layerStateSymbol]}catch{}return i}catch(e){c.instrument_logger.error("Failed to patch method",{kind:t,method:r,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return n.apply(this,arguments)},(0,d.copyPropertiesToTarget)(n,e[r])})};const a=r(5809),c=r(523),u=i(r(6982)),d=r(8949),l=r(7225);function f(){const e=r(8611);return e.METHODS&&e.METHODS.map(function(e){return e.toLowerCase()})||["get","post","put","head","delete","options","trace","copy","lock","mkcol","move","purge","propfind","proppatch","unlock","report","mkactivity","checkout","merge","m-search","notify","subscribe","unsubscribe","patch","search","connect"]}},6928:e=>{"use strict";e.exports=require("path")},6982:e=>{"use strict";e.exports=require("crypto")},7127:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(523),o=r(6730),s=r(2977),i=r(4815),a=r(7225),c=r(714);class u extends c.FrameworkPatcher{_patch(e){return(0,s.patchRoute)(e.Route),(0,i.patchUse)(e.application,"application"),(0,o.patchMethods)(e.application,"application"),a.isVerboseLoggingEnabled&&(0,a.logLazyRouter)(e.application),e.Router.use?((0,i.patchUse)(e.Router,"router"),(0,o.patchMethods)(e.Router,"router")):n.instrument_logger.warn("Skipping express.Router patching"),n.instrument_logger.info("Patched express successfully"),e}}t.default=u},7131:e=>{"use strict";e.exports=require("./wrap")},7166:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.parseCliInstrumentationPattern=k,t.supportSourceMapInstall=S,t.patch=x,t.patchCompile=I,t.onRequireFn=P,t.patchRequire=O,t.isFrameworkEnabled=F,t.getEnabledFrameworks=function(){const e=new Map;for(const[t,r]of g.hudConfig.frameworksToPatch)e.set(r.framework,F(r,g.hudConfig.userConfig.enableFrameworks));return Object.fromEntries(e)},t.getFunctionsToInstrument=q,t.createCheckers=R,t.updateModuleChecker=A,t.skip=D,t.onRequire=function(){try{(0,d.setInstrumentedFilesCountInterval)(),A();try{I()}catch(e){l.instrument_logger.error("Failed to patch compile",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{(0,d.shouldSupportSourceMap)()&&S()}catch(e){l.instrument_logger.error("Failed to install source map support",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{O()}catch(e){l.instrument_logger.error("Failed to patch require",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}catch(e){l.instrument_logger.error("Something went wrong in onRequire",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{(0,m.saveMachineMetric)()}catch(e){l.instrument_logger.error("Failed to add metric",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};const a=i(r(9896)),c=i(r(6928)),u=r(8528),d=r(2546),l=r(523),f=r(3901),g=r(5809),p=r(8528),m=r(8269),h=r(2546),_=r(9063),y=r(714),v=function(){const e=g.SDK_MODULE_NAME;try{return c.dirname(c.dirname(h.myRequire.resolve(e)))}catch(t){return l.instrument_logger.error("Failed to resolve own path",{moduleName:e,msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0}),null}}();function b(e){const t=globalThis.HudSourceMapCache.get(e);return t?{map:JSON.parse(t)}:null}const w=new RegExp(`//"([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})";${g.hudConfig.cliSdkVersionVarName}="([^"]+)";${g.hudConfig.cliBuildIdVarName}`);function k(e){if(e.slice(-g.hudConfig.cliBuildIdVarName.length)!==g.hudConfig.cliBuildIdVarName)return null;const t=Math.min(100,e.length),r=e.slice(-t).match(w);return r?{buildId:r[1],sdkVersion:r[2],fullPattern:r[0]}:null}function S(){r(6093).install({handleUncaughtExceptions:!1,hookRequire:!1,environment:"node",retrieveSourceMap:b})}function x(e,t,r,n){const o={code:e,map:void 0};try{if(globalThis.hudRunningMode===p.HudRunningMode.detached)return o;if(r===u.Format.esm&&!n)throw new h.HudError("MessagePort is required for patching ESM modules");const s=k(e);if(s)return s.sdkVersion!==g.SDK_VERSION?(l.instrument_logger.error("SDK version mismatch detected, disabling SDK",{filename:t,cliSdkVersion:s.sdkVersion,currentSdkVersion:g.SDK_VERSION}),(0,m.detachHud)(!1,!1),o):((0,m.addReingestValue)(s.buildId),globalThis.hudInstrumentationIndicator&&(0,m.clearInstrumentationIndicator)(),o);if(g.hudConfig.userConfig.disableRuntimeInstrumentation?.value)return o;const i=q(t);if(D(t,void 0,i))return o;if(e.length>(g.hudConfig.userConfig.maxFileSizeBytes?.value??0)&&!e.startsWith(g.hudConfig.esbuildMark))return l.instrument_logger.info("Skipping large file",{filename:t,size:e.length}),o;const _=Date.now(),y=(0,f.edit)(e,t,r,i,!1),v=y.metadatas;if(o.code=y.transformedCode,o.map=v,l.instrument_logger.debug("Patched",{filename:t,time:Date.now()-_}),n)for(const e of v)n.postMessage({key:"HudModulePatch",hudPatched:t,hudProcessedFiles:(0,d.sourceFileMetadataToTransferSourceFileMetadata)(e)});else globalThis.hudPatched.add(t),globalThis.hudProcessedFiles.push(...v.map(e=>(0,d.sourceFileMetadataToTransferSourceFileMetadata)(e)));for(const e of v)e.functionIds.length>0&&(globalThis.hudInstrumentationOccured=!0,globalThis.hudInstrumentationIndicator&&(0,m.clearInstrumentationIndicator)(),(0,d.incrementInstrumentedFilesCount)());g.hudConfig.writePatched&&function(e,t){const r=c.parse(e);let n=`${r.dir}/patched.${r.base}`;r.dir.includes("dist")&&(n=c.join(`${r.dir.replace("dist","patched")}`,r.base)),a.existsSync(c.dirname(n))||a.mkdirSync(c.dirname(n),{recursive:!0}),a.writeFileSync(n,t,"utf8"),l.instrument_logger.debug("Dumped patched file",{filename:e,patchedPath:n})}(t,y.transformedCode)}catch(e){l.instrument_logger.error("Failed to patch",{filename:t,format:r,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return o}let E="",M=!0,C=!1;function I(){if(!(0,h.isSupportedNative)())return;const e=r(3339),t=(0,d.shouldSupportSourceMap)();C&&l.instrument_logger.warn("PatchCompile ran twice"),0===Object.keys(globalThis.hudLoadedModules).length&&(globalThis.hudLoadedModules=Object.keys(h.myRequire.cache));const n=e.prototype._compile;e.prototype._compile=function(e,r){if(r===E){try{const e=M?l.instrument_logger.warn.bind(l.instrument_logger):l.instrument_logger.debug.bind(l.instrument_logger);M=!1,e("Skipping compile since already ran",{filename:r})}catch{}return n.call(this,e,r)}E=r,l.instrument_logger.verbose("Compiling requirement",{filename:r});const o=x(e,r,u.Format.cjs);try{if(t&&o.map){const e=(0,d.combineSourceMaps)(o.map,r);e&&globalThis.HudSourceMapCache.set(r,e)}}catch(e){l.instrument_logger.error("Failed to combine source maps",{filename:r,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}const s=n.call(this,o.code,r);return E="",s},C=!0,l.instrument_logger.debug("Patched _compile")}function P(e,t,r){try{const n=g.hudConfig.frameworksToPatch.get(t);return F(n,g.hudConfig.userConfig.enableFrameworks)&&n?.patcher&&n.version?(0,y.getFrameworkPatcher)(n.patcher).patch(e,r,n.version,n.extraInfo,t):e}catch(e){l.instrument_logger.error("Failed to patch framework",{name:t,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return e}function O(){const e=Array.from(g.hudConfig.frameworksToPatch.entries()).filter(([e,t])=>F(t,g.hudConfig.userConfig.enableFrameworks)).map(([e])=>e);new _.Hook(Array.from(e),{internals:!0},P)}function F(e,t){return!!e&&(t&&t.value?.has(e.framework)?t.value.get(e.framework)||!1:e.enable)}function N(e){const t=c.sep.replace(/\\/g,"\\\\"),r=c.join(e).split(".").join("\\.").split("*").join(".*?"),n=t+"node_modules"+t;return{isAllowdModule:new RegExp(n+r+`(?:${t}|$)`),isAllowdModuleSubModule:new RegExp(n+r+n)}}function T(e,t){return!!t.isAllowdModule.test(e)&&!t.isAllowdModuleSubModule.test(e)}function j(e,t){const r=t.replace(/\//g,c.sep);return e.includes(`node_modules${c.sep}${r}${c.sep}`)&&!e.includes(`node_modules${c.sep}${r}${c.sep}node_modules`)}function q(e){return(0,h.getInstrumentedThirdPartyModuleInfo)(e)?.functions||[]}function R(e){const t=[];for(const r of e){let e;if(r.includes("*")){const t=N(r);e=e=>T(e,t)}else e=e=>j(e,r);t.push(e)}return t}let L=[];function A(){L=R(g.hudConfig.userConfig.includeModules?.value??[])}function D(e,t,r=[]){if(!g.hudConfig.allowedEditExtensions.includes(c.extname(e))&&!e.endsWith(c.sep))return l.instrument_logger.warn("Skipping non-allowed extension",{filename:e}),!0;const n=t??L;return"/var/runtime/index.mjs"===e?(l.instrument_logger.debug("Skipping lambda runtime",{filename:e}),!0):e.includes("node_modules")&&!function(e,t){for(const r of t)if(r(e))return!0;return!1}(e,n)&&0===r.length||e.includes(".yarn")?(l.instrument_logger.debug("Skipping non-monitored imported module",{filename:e}),!0):!(v&&!e.includes(v)||(l.instrument_logger.debug("Skipping hud internal module",{filename:e}),0))}},7214:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5809),o=r(8528),s=r(8269),i=r(2546),a=r(523),c=r(8949),u=r(6504),d=r(714);class l extends d.FrameworkPatcher{static graphQLPatchedSymbol=Symbol.for(n.hudConfig.hudPatchedName);_patch(e){return this.patchGraphql(e),a.instrument_logger.info("Patched GraphQL successfully"),e}patchGraphql(e){const t=e.execute;e.execute=function(e){!function(e){try{e&&!e[l.graphQLPatchedSymbol]&&(f(e._queryType),f(e._mutationType),e[l.graphQLPatchedSymbol]=!0,a.instrument_logger.info("Patched GraphQL schema successfully"))}catch(e){a.instrument_logger.error("Failed to patch GraphQL schema",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}(e.schema);const r=process.hrtime.bigint();return function(e,t,r){return"function"==typeof e.then?e.then(e=>(h(t,r),e)):(h(t,r),e)}(t.apply(this,arguments),e.document,r)},(0,c.copyPropertiesToTarget)(t,e.execute)}}function f(e){if(!e)return;const t=e._fields;Object.keys(t).forEach(r=>{const n=t[r];!function(e,t,r){if(e.resolve&&!e.resolve[l.graphQLPatchedSymbol]){const n=(0,i.generateGraphqlFlowId)(r,t);(0,s.storeResolverDeclaration)({id:n,operation:t,name:r});const o=e.resolve;e.resolve=(0,c.wrapFlow)(m,o,!0,(e,t)=>{const r=u.GraphQLMetric.createUsableMetric();r.start(),r.setFlowId(e),t.flowMetric=r},(e,t)=>{const r=t.flowMetric;r?r.end():a.instrument_logger.warn("No flowMetric found for resolver",{flowId:e})},(e,t)=>{const r=t.flowMetric;r?r.end():a.instrument_logger.warn("No flowMetric found for resolver",{flowId:e})}),e.resolve[l.graphQLPatchedSymbol]=!0,(0,s.storeResolverIdBySelectionName)(n,r)}}(n,o.GraphQLSupportedOperations[e.name.toLowerCase()],r),n.type._fields&&p(n.type)})}t.default=l;const g=new WeakSet;function p(e){e&&e._fields&&!g.has(e)&&(g.add(e),Object.keys(e._fields).forEach(t=>{const r=e._fields[t];if(!r||!r.type)return;!function(e){const t=e.resolve;t&&!e.resolve[l.graphQLPatchedSymbol]&&(e.resolve=(0,c.wrapFlow)(m,t,!0),e.resolve[l.graphQLPatchedSymbol]=!0)}(r);let n=r.type;for(;n.ofType;)n=n.ofType;p(n)}))}function m(e){if(void 0===e[2]||void 0===e[3])return void a.instrument_logger.warn("GraphQL resolver arguments are unknown");const t=e[3].path;if(t&&!t.prev){const r=t.key,n=(0,s.getResolverIdBySelectionName)(r);return e[2][l.graphQLPatchedSymbol]=n,n}if(e[2][l.graphQLPatchedSymbol])return e[2][l.graphQLPatchedSymbol];a.instrument_logger.warn("GraphQL No functionId found for resolver")}function h(e,t){try{new s.GraphQLDocumentMetadata(e,Number(process.hrtime.bigint()-t)).save()}catch(e){a.instrument_logger.error("Failed to save document metadata",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}},7225:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.skipStackNamesLogs=t.skipLayerNamesLogs=t.isVerboseLoggingEnabled=t.uuidSymbol=void 0,t.logLazyRouter=function(e){const r=e.lazyrouter;e.lazyrouter=function(){let e=!1;try{this._router||(e=!0)}catch(e){a.instrument_logger.error("Failed to check this._router",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}const n=r.apply(this,arguments);try{if(e){let e=this[t.uuidSymbol];e||(e=c.randomUUID(),this[t.uuidSymbol]=e,a.instrument_logger.info("Express lazy router setting uuid",{uuid:e})),a.instrument_logger.info("Express lazy router",{parent:e,child:this._router?.[t.uuidSymbol]})}}catch(e){a.instrument_logger.error("Failed to patch express.lazyRouter function",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return n},(0,d.copyPropertiesToTarget)(r,e.lazyrouter)};const a=r(523),c=i(r(6982)),u=r(932),d=r(8949);t.uuidSymbol=Symbol.for("__hud_uuid__"),t.isVerboseLoggingEnabled="true"===u.env.HUD_LOG_EXPRESS,t.skipLayerNamesLogs=new Set(["query","expressInit","mounted_app"]),t.skipStackNamesLogs=new Set(["router"])},7246:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(2546),o=r(523),s=r(8949),i=r(714);class a extends i.FrameworkPatcher{static originalRequestSymbol=Symbol.for("hudOriginalRequest");static hudPatched=Symbol.for("hudPatched");_patch(e){try{if((0,n.setIsNextJsApp)(!0),!e.NextRequestAdapter)return o.instrument_logger.error("Could not find NextRequestAdapter in exports"),e;const t=e.NextRequestAdapter;if(t[a.hudPatched])return o.instrument_logger.debug("NextRequestAdapter already patched"),e;const r=t.fromNodeNextRequest;if(!r)return o.instrument_logger.error("Could not find NextRequestAdapter.fromNodeNextRequest"),e;t.fromNodeNextRequest=function(...e){const t=r.apply(this,e);try{t[a.originalRequestSymbol]=e[0]._req}catch(e){o.instrument_logger.error("Failed to patch NextRequestAdapter",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t},(0,s.copyPropertiesToTarget)(r,t.fromNodeNextRequest),t[a.hudPatched]=!0,o.instrument_logger.info("Successfully patched NextRequestAdapter.fromNodeNextRequest")}catch(e){o.instrument_logger.error("Failed to patch NextRequestAdapter",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return e}}t.default=a},7603:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getObservabilityIdentifiers=function(e){const t=l();return{datadog_trace_id:t?.trace_id,datadog_span_id:t?.span_id,otel_trace_id:g(),w3c_trace_context:i(e),w3c_baggage:c(e,"baggage"),amazon_trace_id:c(e,"x-amzn-trace-id"),b3_propagation:a(e),jaeger_trace_id:c(e,"uber-trace-id")}},t.getExtraHeaders=function(e){const t={};for(const r of n.hudConfig.dynamicConfig.extraHeaders){const n=c(e,r);void 0!==n&&(t[r]=n)}return t},t.getDatadogIds=l,t.getOtelTraceId=g;const n=r(5809),o=r(2546),s=r(523);function i(e){try{return{traceparent:c(e,"traceparent"),tracestate:c(e,"tracestate")}}catch{return}}function a(e){try{return{full:c(e,"b3"),trace_id:c(e,"x-b3-traceid"),span_id:c(e,"x-b3-spanid"),parent_span_id:c(e,"x-b3-parentspanid")}}catch{return}}function c(e,t){try{return e.headers[t]}catch{return}}function u(e){let t;return()=>(void 0===t&&(t=function(e){try{const t=o.myRequire.resolve(e),r=o.myRequire.cache[t];return void 0===r?(s.instrument_logger.info("requireFromCache: codeModule is undefined",{path:e,fullPath:t}),null):"object"!=typeof r.exports?(s.instrument_logger.warn("requireFromCache: codeModule.exports is not an object",{path:e}),null):r.exports}catch(t){return s.instrument_logger.warn("requireFromCache: error",{path:e,error:t}),null}}(e)),t)}const d=u("dd-trace/packages/datadog-core");function l(){try{const e=d();if(null===e)return;const{storage:t}=e,r=t("legacy").getStore();return{trace_id:r.span._spanContext.toTraceId(),span_id:r.span._spanContext.toSpanId()}}catch{return}}const f=u("@opentelemetry/api");function g(){try{const e=f();if(null===e)return;const{trace:t}=e;return t.getActiveSpan()?.spanContext().traceId}catch{return}}},7808:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getMachineMetrics=function(){try{const e=(0,o.getLastMetrics)();return{cpu_usage:e.cpuUsage?l(e.cpuUsage,e.timestamp):void 0,memory_usage:d(),event_loop_utilization:e.elu?u(e.elu):void 0}}catch(e){return void i.app_logger.error("Error getting machine metrics",e)}},t.getCpuUsage=l;const o=r(8269),s=r(2546),i=r(523),a=n(r(857)),c=r(2987);function u(e){try{return c.performance.eventLoopUtilization(e).utilization}catch(e){return void i.app_logger.error("Error getting event loop utilization",e)}}function d(){try{const e=process.memoryUsage(),t=a.default.totalmem();return{rss:e.rss,heap_total:e.heapTotal,heap_used:e.heapUsed,external:e.external,system_memory:t,rss_percentage:e.rss/t*100}}catch(e){return void i.app_logger.error("Error getting memory usage",e)}}function l(e,t){try{const r=process.cpuUsage(),n=1e3*(Date.now()-t),o=(0,s.getCpuLimit)(i.app_logger),a=(r.user-e.user)/n,c=(r.system-e.system)/n;return{user_time:a,system_time:c,limit:o,user_percent_of_limit:"number"==typeof o?a/o*100:void 0,system_percent_of_limit:"number"==typeof o?c/o*100:void 0}}catch(e){return void i.app_logger.error("Error getting cpu usage",e)}}},8064:e=>{"use strict";e.exports=require("semver")},8269:e=>{"use strict";e.exports=require("./globalstate")},8528:e=>{"use strict";e.exports=require("./dto")},8611:e=>{"use strict";e.exports=require("http")},8901:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpEndpointMetric=void 0;const n=r(9873);class o extends n.FlowMetric{statusCode;route;method;constructor(e){super(e)}_createUsableMetric(e){return this}setRequestAttributes(e){const t=e.url||e.path;this.route=t?.split("?")[0],this.method=e.method}setResponseAttributes(e){this.statusCode=e.statusCode}toRaw(){if(this.statusCode&&this.route&&this.method)return{flow_id:this.flowId,type:"EndpointMetric",duration:this.duration,status_code:this.statusCode,route:this.route,method:this.method}}}t.HttpEndpointMetric=o},8949:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AsyncFunction=void 0,t.wrapFlow=function(e,r,c=!0,u,d,l){let f;if(r[i])return r;const g=(0,s.getFlowStateStorage)();return g?(r[i]=!0,f=r instanceof t.AsyncFunction?async function(...t){let s;try{s=e(t)}catch(e){o.instrument_logger.error("Failed to get flowId",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}if(!s||hudRunningMode!==n.HudRunningMode.enabled)return await r.apply(this,t);const i={};if(u)try{u(s,i,t)}catch(e){o.instrument_logger.error("Failed to execute beforeCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const e=g.run({flowId:s,shouldLinkFunction:c},Reflect.apply,r,this,t),n=await e;if(d)try{d(s,i)}catch(e){o.instrument_logger.error("Failed to execute afterCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return n}catch(e){if(l)try{l(s,i,e)}catch(e){o.instrument_logger.error("Failed to execute catchCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}throw e}}:function(...t){let s;try{s=e(t)}catch(e){o.instrument_logger.error("Failed to get flowId",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}if(!s||hudRunningMode!==n.HudRunningMode.enabled)return r.apply(this,t);const i={};if(u)try{u(s,i,t)}catch(e){o.instrument_logger.error("Failed to execute beforeCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const e=g.run({flowId:s,shouldLinkFunction:c},Reflect.apply,r,this,t);if(d)if(e instanceof Promise)e.then(()=>{try{d(s,i)}catch(e){o.instrument_logger.error("Failed to execute afterCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}});else try{d(s,i)}catch(e){o.instrument_logger.error("Failed to execute afterCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return e}catch(e){if(l)try{l(s,i,e)}catch(e){o.instrument_logger.error("Failed to execute catchCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}throw e}},a(r,f),f):r},t.copyPropertiesToTarget=a;const n=r(8528),o=r(523),s=r(7131);t.AsyncFunction=(async()=>{}).constructor;const i=Symbol.for("hudMarked");function a(e,t){const r=Object.getOwnPropertyDescriptors(e),n=Reflect.ownKeys(r);Object.setPrototypeOf(t,e),n.forEach(e=>{try{Object.defineProperty(t,e,r[e])}catch{}})}},9063:e=>{"use strict";e.exports=require("require-in-the-middle")},9589:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(8528),s=r(8269),i=r(2546),a=r(523),c=r(8949),u=r(714),d=r(5459),l=n(r(7246));class f extends u.FrameworkPatcher{static nextJSHudMarked=Symbol.for("hudNextJSMarked");static routeInfoSymbol=Symbol.for("hudNextJSRouteInfo");static standardMethods=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];_patch(e){return(0,i.setIsNextJsApp)(!0),this._patchBaseServer(e),a.instrument_logger.info("Patched Next.js successfully"),e}_patchBaseServer(e){try{const t=e.default;if(t[f.nextJSHudMarked])return e;const r=t.prototype.renderToResponseWithComponentsImpl;if(!r)return a.instrument_logger.error("Could not find renderToResponseWithComponentsImpl on BaseServer.prototype"),e;t.prototype.renderToResponseWithComponentsImpl=async function(e,t,...n){try{const r=t.components;if(r&&r.routeModule&&!r.routeModule[f.nextJSHudMarked]){const t=r.routeModule,n=t.definition?.pathname||e.pathname;f._detectAndPatchSupportedMethods(t,n),t[f.nextJSHudMarked]=!0}}catch(e){a.instrument_logger.error("Failed to patch Next.js route module",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return await r.apply(this,[e,t,...n])},t[f.nextJSHudMarked]=!0,(0,c.copyPropertiesToTarget)(r,t.prototype.renderToResponseWithComponentsImpl)}catch(e){a.instrument_logger.error("Failed to patch Next.js base server",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return e}static _detectAndPatchSupportedMethods(e,t){try{switch(a.instrument_logger.debug("Patching Next.js route module",{pathname:t,kind:e.definition?.kind||"unknown"}),e.definition.kind){case"APP_ROUTE":case"PAGES_API":f._patchApiModule(e,t);break;case"PAGES":case"APP_PAGE":f._patchPageModule(e,t);break;default:a.instrument_logger.warn("Unknown Next.js route module kind",{pathname:t,kind:e.definition?.kind||"unknown"})}}catch(e){a.instrument_logger.error("Error detecting and patching supported methods",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}static _patchApiModule(e,t){if(e.methods)for(const r of f.standardMethods)if("function"==typeof e.methods[r]&&"function"==typeof e.userland?.[r]){const n=(0,i.generateEndpointFlowId)(t,[r]);(0,s.storeEndpointDeclaration)(new o.EndpointDeclaration(n,[r],"nextjs","",t));try{const t=e.methods[r];e.methods[r]=(0,c.wrapFlow)(()=>n,t,!0,(e,t,r)=>{m(r[0],e)})}catch(e){a.instrument_logger.error("Failed to patch Next.js App Route method",{method:r,pathname:t,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}if(e.userland?.default){const r=f.standardMethods.filter(t=>!e.methods?.[t]),n=(0,i.generateEndpointFlowId)(t,r);(0,s.storeEndpointDeclaration)(new o.EndpointDeclaration(n,r,"nextjs","",t));const a=e.userland.default;e.userland={...e.userland,default:(0,c.wrapFlow)(()=>n,a,!0)}}}static _patchPageModule(e,t){const r=(0,i.generateEndpointFlowId)(t,["GET"]);if((0,s.storeEndpointDeclaration)(new o.EndpointDeclaration(r,["GET"],"nextjs","",t)),e.render&&"function"==typeof e.render&&!e.render[this.nextJSHudMarked])try{const t=e.render;e.render=function(...e){try{m(e[0],r)}catch{}return t.apply(this,e)},(0,c.copyPropertiesToTarget)(t,e.render),e.render[this.nextJSHudMarked]=!0}catch(e){a.instrument_logger.error("Failed to patch Next.js Page render method",{pathname:t,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}if(e.userland?.loaderTree)try{p(e.userland.loaderTree,r)}catch(e){a.instrument_logger.error("Failed to patch App Router page component",{pathname:t,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}else a.instrument_logger.warn("No loader tree found on Next.js page component",{pathname:t})}}function g(e,t,r){return(...n)=>{const o=e(...n),s=e=>{if(e&&"function"==typeof e.default&&!e.default[f.nextJSHudMarked]){const n=(0,c.wrapFlow)(()=>r,e.default,t);(e={...e,default:n})[f.nextJSHudMarked]=!0}return e};return o&&"function"==typeof o.then?o.then(s):s(o)}}function p(e,t){const[,r,n]=e;for(const e of Object.keys(n))try{const r=n[e];if(Array.isArray(r)&&"function"==typeof r[0]){const n="page"===e,o=r[0];r[0]=g(o,n,t),(0,c.copyPropertiesToTarget)(o,r[0])}}catch(e){a.instrument_logger.error("Failed to iterate on Next.js components",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}for(const e of Object.values(r))try{p(e,t)}catch(e){a.instrument_logger.error("Failed to walk on Next.js parallel routes",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}function m(e,t){try{let r;if(e&&l.default.originalRequestSymbol in e){const t=e[l.default.originalRequestSymbol];r=(0,d.getHttpMetricFromRequest)(t)}else e&&e.originalRequest&&(r=(0,d.getHttpMetricFromRequest)(e.originalRequest));if(r||(r=(0,d.getHttpMetricFromRequest)(e)),!r)return void a.instrument_logger.error("No endpoint metric found on Next.js request or its original request");r.setFlowId(t)}catch(e){a.instrument_logger.error("Failed to link metric to flow",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}t.default=f},9723:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=r(8269),c=r(2546),u=r(523),d=r(9896),l=i(r(6928)),f=r(8949),g=r(714);class p extends g.FrameworkPatcher{_patch(e){(0,c.setIsNextJsApp)(!0);const t=this._patchLoadConfig(e);return u.instrument_logger.info("Patched next.js config successfully"),t}_patchLoadConfig(e){const t=e.default,r=async function(...e){const r=await t.call(this,...e);if(!r)return r;try{const t=e[1],n=l.join(t,r.distDir||".next"),o=l.join(n,a.apiManifest),s=l.join(n,a.pageManifest),i=await d.promises.access(o).then(()=>!0).catch(()=>!1),c=await d.promises.access(s).then(()=>!0).catch(()=>!1);(0,a.isNextConfigExtracted)()||!i&&!c||(u.instrument_logger.info("Extracted next.js config successfully"),(0,a.setNextConfig)(r))}catch(e){u.instrument_logger.error("Failed to patch next.js loadConfig",{msg:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0})}return r};(0,f.copyPropertiesToTarget)(t,r);const n=Object.create(Object.getPrototypeOf(e));return Object.defineProperty(n,"default",{enumerable:!0,get:function(){return r}}),(0,f.copyPropertiesToTarget)(e,n),n}}t.default=p},9873:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FlowMetric=void 0;const o=r(8528),s=r(8269),i=n(r(932));t.FlowMetric=class{_state;flowId;duration;_startTime;_msStartTime;constructor(e){this.flowId=e,this.duration=0,this._state="usable"}static createUsableMetric(e){return new this(e)._createUsableMetric(e)}setFlowId(e){this.flowId=e}getFlowId(){return this.flowId}getMsStartTime(){return this._msStartTime}start(){this._startTime=i.default.hrtime.bigint(),this._msStartTime=Date.now()}end(){this._startTime&&(this.duration=Number(i.default.hrtime.bigint()-this._startTime)),this.#e(),this._state="unusable"}#e(){if(hudRunningMode===o.HudRunningMode.enabled){const e=this.toRaw();e&&(0,s.storeFlowMetric)(e)}}}},9896:e=>{"use strict";e.exports=require("fs")}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,r),s.exports}return r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r(2197)})());
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 n in r)("object"==typeof exports?exports:e)[n]=r[n]}}(global,()=>(()=>{var e={336:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5809),o=r(523),s=r(2822),i=r(8949),a=r(8901),c=r(714);class u extends c.FrameworkPatcher{_patch(e){return this._patchSendRequest(e),o.instrument_logger.info("Patched @codegenie/serverless-express/src/frameworks/express.js successfully"),e}_patchSendRequest(e){const t=e.sendRequest;e.sendRequest=function(e){let r,i;const c=a.HttpEndpointMetric.createUsableMetric();try{if(r=e.request,i=e.response,!r||!i)return t.call(this,e);c.start(),c.setRequestAttributes(r),r[n.hudConfig.metricSymbol]=c}catch(e){o.instrument_logger.error("Failed to start flowMetric during sendRequest patching",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}const u=(0,s.runWithInvestigation)(()=>t.call(this,e));try{i.once("finish",function(){try{(0,s.finishHttpInvestigation)(r,i,c),c.setResponseAttributes(i),c.end()}catch(e){o.instrument_logger.error("Failed to end flowMetric during sendRequest patching",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})}catch(e){o.instrument_logger.error("Failed to end flowMetric during sendRequest patching",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return u},(0,i.copyPropertiesToTarget)(t,e.sendRequest)}}t.default=u},486:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5809),o=r(8269),s=r(2546),i=r(523),a=r(8949),c=r(828),u=r(714);class d extends u.FrameworkPatcher{_patch(e){return this._patchConsumer(e),i.instrument_logger.info("Patched KafkaJS successfully"),e}_patchConsumer(e){const t=e.Kafka.prototype.consumer;e.Kafka.prototype.consumer=function(...e){const r=t.apply(this,e);try{const t=new Map,o=[],s=[];!function(e,t){const r=e.subscribe;e.subscribe=async function(...e){const n=await r.apply(this,e);try{const r=e[0].topics;r?r.forEach(e=>{t.push(e)}):e[0].topic?t.push(e[0].topic):i.instrument_logger.warn("No topic found in KafkaJS.Consumer.subscribe",{args:e[0]})}catch(e){i.instrument_logger.error("Error in patching KafkaJS.Consumer.subscribe",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return n},(0,a.copyPropertiesToTarget)(r,e.subscribe)}(r,s),function(e,t,r,o,s){const u=e.run;function d(e,u){const d="eachBatch"===u;for(const e of s)p(e,o,t,r,u);const m=function(e,t,r){return n=>{const o=n[0],s=r?o.batch.topic:o.topic;return function(e,t,r,n){const o=e.get(g(r,n));if(o)return o;for(const e of t)if(e.isBatch===n&&e.pattern.test(r))return e.flowId;i.instrument_logger.warn("No flowId found for topic",{topicName:r,isBatch:n})}(e,t,s,r)}}(t,r,d),h=function(e){return(t,r,o)=>{const s=c.KafkaJSMetric.createUsableMetric();s.start(),s.setFlowId(t);const i=o[0];void 0!==i&&void 0!==i.message&&(i.message[n.hudConfig.metricSymbol]=s);const a=e?i.batch.partition:i.partition,u=e?i.batch.messages[0]?.timestamp:i.message?.timestamp;s.addPartition(a),s.addProducedTimestamp(u),r.flowMetric=s}}(d),_=(0,a.wrapFlow)(m,e[u],!0,h,l,f);e[u]=_}e.run=async function(...e){try{const t=e[0];t.eachMessage&&d(t,"eachMessage"),t.eachBatch&&d(t,"eachBatch")}catch(e){i.instrument_logger.error("Error in patching KafkaJS.Consumer.run",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return await u.apply(this,e)},(0,a.copyPropertiesToTarget)(u,e.run)}(r,t,o,e[0].groupId,s)}catch(e){i.instrument_logger.error("Error in patching KafkaJS.Consumer",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return r},(0,a.copyPropertiesToTarget)(t,e.Kafka.prototype.consumer)}}function l(e,t){const r=t.flowMetric;r?r.end():i.instrument_logger.warn("No flowMetric found for message",{flowId:e})}function f(e,t,r){const n=t.flowMetric;n?(n.setError(r),n.end()):i.instrument_logger.warn("No flowMetric found for message",{flowId:e})}function g(e,t){return e+"|"+t}function p(e,t,r,n,i){const a=(0,s.generateKafkaFlowId)(e,t,i),c={flow_id:a,topic_name:e.toString(),group_id:t,pulling_type:i};(0,o.storeKafkaJSTopicDeclaration)(c),function(e,t,r,n,o){"string"==typeof r?e.set(g(r,n),o):t.push({pattern:r,isBatch:n,flowId:o})}(r,n,e,"eachBatch"===i,a)}t.default=d},523:e=>{"use strict";e.exports=require("./logger")},646:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(523),o=r(8949),s=r(5128),i=r(714);class a extends i.FrameworkPatcher{_patch(e){return this._patchCreate(e),n.instrument_logger.info("Patched NestJS RouterExecutionContext successfully"),e}_patchCreate(e){const t=e.RouterExecutionContext.prototype.create;e.RouterExecutionContext.prototype.create=function(...e){try{const t=e[0],r=e[1];"function"==typeof t.constructor&&"function"==typeof r?e[1]=(0,s.wrapLinkedFunction)(r):n.instrument_logger.error("Invalid args in NestJS RouterExecutionContext.create",{args:e})}catch(e){n.instrument_logger.error("Error in NestJS RouterExecutionContext patcher",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t.apply(this,e)},(0,o.copyPropertiesToTarget)(t,e.RouterExecutionContext.prototype.create)}}t.default=a},714:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.FrameworkPatcher=void 0,t.isSupportedVersion=f,t.extractModuleVersion=g,t.getFrameworkPatcher=function(e){return new(r(2828)(`./${e}`).default)};const a=r(2546),c=r(523),u=r(9896),d=i(r(6928)),l=r(8064);function f(e,t){return""===e||l.satisfies(l.coerce(e),t)}function g(e){try{const t=(0,u.readFileSync)(d.join(e,"package.json"),{encoding:"utf8"}),r=JSON.parse(t).version;return"string"==typeof r?r:""}catch{c.instrument_logger.info("Failed extracting version",{baseDir:e})}return""}t.FrameworkPatcher=class{patch(e,t,r,n,o=this.constructor.name){try{if(this.isSupported(t,o,r,n))return this._patch(e)}catch(e){c.instrument_logger.error("Unhandeled error during patching framework",{framework:o,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return e}isSupported(e,t,r,n){const o=g(e);return!!f(o,r)||(c.instrument_logger.warn("Unsupported version",{framework:t,version:o,supportedVersion:r,basedir:e}),c.customer_logger.log(a.UserErrorLogs.UnsupportedFrameworkVersion(t)),!1)}}},828:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KafkaJSMetric=void 0;const n=r(523),o=r(7131),s=r(9873);class i extends s.FlowMetric{partition;error;producedTimestamp;totalConsumeDuration;constructor(e){super(e)}_createUsableMetric(e){return this}end(){this.producedTimestamp&&(this.totalConsumeDuration=Number(Date.now()-this.producedTimestamp)*Number(1e6)),super.end()}addProducedTimestamp(e){void 0!==e&&(this.producedTimestamp=Number(e))}addPartition(e){this.partition=e}setError(e){this.error=(0,o.extractName)(e)}toRaw(){if(void 0!==this.partition)return{flow_id:this.flowId,type:"KafkaJSMetric",duration:this.duration,partition:this.partition,error:this.error,total_consume_duration:this.totalConsumeDuration};n.instrument_logger.warn("No partition found for message",{flowId:this.flowId})}}t.KafkaJSMetric=i},857:e=>{"use strict";e.exports=require("os")},932:e=>{"use strict";e.exports=require("process")},1326:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(2546),s=r(523),i=r(8949),a=r(714),c=n(r(9589));class u extends a.FrameworkPatcher{static nextJSHudMarked=Symbol.for("hudNextJSMarked");_patch(e){return(0,o.setIsNextJsApp)(!0),this._pathLoad(e),s.instrument_logger.info("Patched Next.js successfully"),e}_pathLoad(e){try{const t=e.RouteModuleLoader;if(t[u.nextJSHudMarked])return e;const r=t.load;t.load=async function(...e){const t=await r.apply(this,e);try{if(t){const e=t.definition?.pathname;e&&!t[u.nextJSHudMarked]&&(c.default._detectAndPatchSupportedMethods(t,e),t[u.nextJSHudMarked]=!0)}}catch(e){s.instrument_logger.error("Failed to patch Next.js route module",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t},t[u.nextJSHudMarked]=!0,(0,i.copyPropertiesToTarget)(r,t.load)}catch(e){s.instrument_logger.error("Failed to patch Next.js base server",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return e}}t.default=u},1427:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getSystemInfo=function(){return{pod_name:u(),node_name:d()}};const o=n(r(9896)),s=n(r(857)),i=Symbol("not found");let a,c;function u(){if(a!==i){if(a)return a;try{return a=s.default.hostname(),a}catch{return void(a=i)}}}function d(){if(c!==i){if(c)return c;try{const e=o.default.readFileSync("/etc/machine-id","utf8").trim();return c=e,c}catch{return void(c=i)}}}},1502:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5809),o=r(8528),s=r(8269),i=r(2546),a=r(523),c=r(8949),u=r(714);class d extends u.FrameworkPatcher{static koaModuleName="koa";static koaPatchedSymbol=Symbol.for(n.hudConfig.hudPatchedName);_patch(e){return this._patchAppUse(e),a.instrument_logger.info("Patched koa successfully"),e}_patchAppUse(e){const t=e.prototype.use;e.prototype.use=function(e){const r=t.apply(this,arguments);try{if(!arguments[0].router)return r;const e=arguments[0].router.stack;for(let t=0;t<e.length;t++)d._wrapRoute(e[t])}catch(e){a.instrument_logger.error("Failed to patch koa.use function",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return r},(0,c.copyPropertiesToTarget)(t,e.prototype.use)}static _wrapRoute(e){if(e.methods&&0===e.methods.length)return;if(!e.stack[0][d.koaPatchedSymbol]){const t=(0,c.wrapFlow)(m,e.stack[0],!0,l);e.stack[0]=t,e.stack[0][d.koaPatchedSymbol]=!0}const t=(0,i.generateEndpointFlowId)(e.path,e.methods);(0,s.storeEndpointDeclaration)(new o.EndpointDeclaration(t,e.methods,"koa",void 0,e.path));for(const r of e.methods)p(t,e.path,r)}}function l(e,t,r){if(!r[0])return void a.instrument_logger.error("No ctx object found in koa");const o=r[0].req;if(!o)return void a.instrument_logger.error("No req found in koa ctx");const s=o[n.hudConfig.metricSymbol];s?s.setFlowId(e):a.instrument_logger.error("No endpoint metric found in koa req")}function f(e,t){return e+"|"+t}t.default=d;const g=new Map;function p(e,t,r){g.set(f(t,r),e)}function m(e){if(0===e.length)return;const t=e[0]._matchedRoute,r=e[0].req?.method;return function(e,t){return g.get(f(e,t))}(t,r)}},2080:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SqsMetric=void 0;const n=r(9873);class o extends n.FlowMetric{errors;msgCount;e2eEpocStartTimeMS;e2eDurationNS;_finishedMessageCount;constructor(e){super(e),this._finishedMessageCount=0,this.errors=new Map}addError(e,t=1){this.errors.set(e,(this.errors.get(e)??0)+t)}increaseAndShouldEnd(e=1){return this._finishedMessageCount+=e,!(this.msgCount&&this._finishedMessageCount<this.msgCount)}end(){this.e2eEpocStartTimeMS&&(this.e2eDurationNS=Number(Date.now()-this.e2eEpocStartTimeMS)*Number(1e6)),super.end()}_createUsableMetric(e){return this}toRaw(){return{flow_id:this.flowId,type:"SqsMetric",duration:this.duration,e2e_duration:this.e2eDurationNS,msg_count:this.msgCount,errors:this.errors}}}t.SqsMetric=o},2197:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||o(t,e,r)},a=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.koa=t.express=t.safeLog=t.registerHook=t.hudRITM=void 0;var c=r(5688);Object.defineProperty(t,"hudRITM",{enumerable:!0,get:function(){return c.hudRITM}}),Object.defineProperty(t,"registerHook",{enumerable:!0,get:function(){return c.registerHook}}),Object.defineProperty(t,"safeLog",{enumerable:!0,get:function(){return c.safeLog}}),i(r(3901),t),t.express=a(r(7127)),i(r(714),t),t.koa=a(r(1502)),i(r(7166),t)},2546:e=>{"use strict";e.exports=require("./lib")},2729:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5809),o=r(523),s=r(2822),i=r(8949),a=r(8901),c=r(714);class u extends c.FrameworkPatcher{_patch(e){const t=this._patchGetFramework(e);return o.instrument_logger.info("Patched serverless-http/lib/framework/get-framework.js successfully"),t}_patchGetFramework(e){const t=e;return e=function(...e){const r=t.apply(t.this,e);async function c(e,...t){const i=a.HttpEndpointMetric.createUsableMetric();try{i.start(),i.setRequestAttributes(e),e[n.hudConfig.metricSymbol]=i}catch(e){o.instrument_logger.error("Failed to start flowMetric during framework serverless request handler patching",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}const c=await(0,s.runWithInvestigation)(()=>r.apply(r.this,[e,...t]));return c.once("finish",function(){try{(0,s.finishHttpInvestigation)(e,c,i),i.setResponseAttributes(c),i.end()}catch(e){o.instrument_logger.error("Failed to end flowMetric during framework serverless request handler patching",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}),c}return(0,i.copyPropertiesToTarget)(r,c),c},(0,i.copyPropertiesToTarget)(t,e),e}}t.default=u},2741:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(523),o=r(6730),s=r(4815),i=r(7225),a=r(714);class c extends a.FrameworkPatcher{_patch(e){return i.isVerboseLoggingEnabled?((0,o.patchMethods)(e,"application_export"),(0,s.patchUse)(e,"application",!1),(0,i.logLazyRouter)(e),n.instrument_logger.info("Patched express.Application successfully"),e):(n.instrument_logger.info("Skipping express.Application patching, verbose logging is not enabled"),e)}}t.default=c},2784:e=>{"use strict";e.exports=require("../native/_index")},2822:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getStackTraceWithoutMessage=l,t.serializableInvestigation=p,t.getBaseInvestigationStorage=m,t.createNewInvestigation=function(){if(!globalThis.hudEnableInvestigation)return;const e=(0,a.getInvestigationStorage)();void 0!==e&&e.enterWith(m())},t.runWithInvestigation=function(e){if(!globalThis.hudEnableInvestigation)return e();const t=(0,a.getInvestigationStorage)();return void 0===t?e():t.run(m(),e)},t.closeInvestigation=h,t.storeInvestigation=_,t.getStacktraceUniqString=b,t.finishHttpInvestigation=function(e,t,r){if(t.statusCode<500)return;try{g("http requests headers",{headers:Object.keys(e.headers)})}catch{g("failed to log http requests headers")}const n=k(r);if(void 0===n)return void g("finishHttpInvestigation: base investigation return undefined");const o=r.getFlowId(),s=r.getMsStartTime();void 0!==o&&void 0!==r.route&&void 0!==r.method&&void 0!==s?_(n,{type:"http",endpoint_uuid:o,route:r.route,method:r.method,timestamp:s,params:e.params,query:e.query,request_body:w(e.body),status_code:t.statusCode,machine_metrics:(0,c.getMachineMetrics)(),observability_identifiers:(0,u.getObservabilityIdentifiers)(e),extra_headers:(0,u.getExtraHeaders)(e),system_info:(0,d.getSystemInfo)()}):g("route, method, or reqTimestamp is undefined even though they shouldn't",{flowId:o,route:r.route,method:r.method,reqTimestamp:s})},t.finishSqsInvestigation=function(e,t){if(0===t.errors.size)return;const r=k(t);if(void 0===r)return void g("finishSqsInvestigation: investigation is undefined");const n=t.getFlowId(),o=t.getMsStartTime();void 0!==o&&void 0!==n?_(r,{type:"sqs",timestamp:o,flow_id:n,messages:w(e),machine_metrics:(0,c.getMachineMetrics)(),system_info:(0,d.getSystemInfo)()}):g("reqTimestamp is undefined even though it shouldn't",{flowId:n})};const n=r(5809),o=r(8528),s=r(8269),i=r(523),a=r(7131),c=r(7808),u=r(7603),d=r(1427);function l(e,t){if(void 0===t)return;const r=function(e){let t=0;for(let r=0;r<e.length;r++)"\n"===e[r]&&t++;return t}(e)+1;let n=-1;for(let e=0;e<r;e++)if(n=t.indexOf("\n",n+1)??-1,-1===n)return;return-1!==n?t.slice(n+1):void 0}const f={};function g(e,...t){let r="debug";(void 0===f[e]||f[e]<n.hudConfig.dynamicConfig.investigationRateLimits.maxUniqLogs)&&(r="warn",f[e]=f[e]+1||1),i.app_logger.logLevel(r,e,...t)}function p(e){return{status:e.status,context:e.context,exceptions:Array.from(Array.from(e.exceptions?.values()??[]).map(({exception:e,executionFlow:t})=>({name:(0,a.extractNameOptional)(e),message:(0,a.extractMessage)(e),stackTrace:l(e.message,e.stack),executionFlow:t}))??[]),userContext:e.userContext}}function m(){return{status:o.InvestigationStatus.Open}}function h(){if(!globalThis.hudEnableInvestigation)return;const e=(0,a.getInvestigationStorage)();if(void 0===e)return;const t=e.getStore();return void 0!==t&&t.status===o.InvestigationStatus.Open?(t.status=o.InvestigationStatus.Closed,t):void 0}function _(e,t){e.context=t,(0,s.storeClosedInvestigation)(p(e))}const y=/.*\((.*):(\d+):(\d+)\)/,v=/.*?(\S*):(\d+):(\d+)/;function b(e){const t=Error.prepareStackTrace;if(void 0===t||"function"!=typeof t)return void g("getStacktraceUniqString: prepareStackTrace is undefined or not a function");let r,n;try{Error.prepareStackTrace=(e,t)=>{r=t};const o=e.stack;if(void 0!==r&&(n=r.find(e=>{const t=e.getFileName();return t&&e.getLineNumber()&&e.getColumnNumber()&&!t.startsWith("node:")}),void 0===n&&(g("getStacktraceUniqString: result is undefined, fallbacking to callsites[0]",{globCallSites:r}),n=r[0])),void 0!==o&&void 0===n){const t=l(e.message,o);if(void 0===t)return;const r=t;for(const t of r.split("\n")){const r=t.match(y);if(r&&r[1]&&r[2]&&r[3]&&!r[1].startsWith("node:"))return`${e.name}@${r[1]}:${r[2]}:${r[3]}`;const n=t.match(v);if(n&&n[1]&&n[2]&&n[3]&&!n[1].startsWith("(node:"))return`${e.name}@${n[1]}:${n[2]}:${n[3]}`}return void g("getStacktraceUniqString: no match found in regex",{stack:o,message:e.message})}if(void 0===n||void 0===r)return void g("getStacktraceUniqString: result or globCallSites is undefined",{result:void 0===n,globCallSites:void 0===r});Object.defineProperty(e,"stack",{configurable:!0,enumerable:!1,get:()=>t(e,r)})}finally{Error.prepareStackTrace=t}try{return`${e.name}@${n.getFileName()}:${n.getLineNumber()}:${n.getColumnNumber()}`}catch(e){return void g("getStacktraceUniqString: throw exception",{error:e,stack:e instanceof Error?e.stack:void 0,message:e instanceof Error?e.message:void 0})}}function w(e,t=n.hudConfig.investigation.maxObjectDepth){try{if("string"==typeof e)return e.length>n.hudConfig.investigation.maxStringLength?e.slice(0,n.hudConfig.investigation.maxStringLength)+"...":e;if(Array.isArray(e))return e.slice(0,n.hudConfig.investigation.maxArrayLength).map(e=>w(e,t-1));if(null===e||["number","boolean"].includes(typeof e))return e;if("bigint"==typeof e)return e.toString();if("object"==typeof e){const r={...e};for(const n in e)r[n]=w(e[n],t-1);return r}}catch{}}function k(e){const t=h();if(void 0===t)return void g("finishBaseInvestigation: investigation is undefined");if(void 0===t.firstException)return void g("finishBaseInvestigation: firstException is undefined");if(s.globalInvestigationTracking>=n.hudConfig.dynamicConfig.investigationRateLimits.maxTotalInvestigations)return void g("finishBaseInvestigation: globalInvestigationTracking is greater than maxTotalInvestigations",{globalInvestigationTracking:s.globalInvestigationTracking,maxTotalInvestigations:n.hudConfig.dynamicConfig.investigationRateLimits.maxTotalInvestigations});const r=e.getFlowId();if(void 0===r)return void g("finishBaseInvestigation: flowId is undefined");const o=b(t.firstException);if(void 0===o)return void g("finishBaseInvestigation: exceptionUniqString is undefined");const i=((0,s.getInvestigationDedupingCache)(r).get(o)??0)+1;if(!(i>n.hudConfig.dynamicConfig.investigationRateLimits.maxSameInvestigations))return(0,s.increaseGlobalInvestigationTracking)(),(0,s.increaseInvestigationDedupingCache)(r,o),t;g("finishBaseInvestigation: investigationCount is greater than maxSameInvestigations",{investigationCount:i,maxSameInvestigations:n.hudConfig.dynamicConfig.investigationRateLimits.maxSameInvestigations})}},2828:(e,t,r)=>{var n={"./codeGenieServerlessExpress":336,"./codeGenieServerlessExpress.ts":336,"./express":7127,"./express.ts":7127,"./express/methods":6730,"./express/methods.ts":6730,"./express/route":2977,"./express/route.ts":2977,"./express/router":4815,"./express/router.ts":4815,"./express/verbosity":7225,"./express/verbosity.ts":7225,"./expressApplication":2741,"./expressApplication.ts":2741,"./flows/endpoints/metrics":8901,"./flows/endpoints/metrics.ts":8901,"./flows/flow":9873,"./flows/flow.ts":9873,"./flows/graphql":6504,"./flows/graphql.ts":6504,"./flows/kafkajs":828,"./flows/kafkajs.ts":828,"./flows/sqs":2080,"./flows/sqs.ts":2080,"./frameworkPatcher":714,"./frameworkPatcher.ts":714,"./graphql":7214,"./graphql.ts":7214,"./http":5459,"./http.ts":5459,"./kafkajs":486,"./kafkajs.ts":486,"./koa":1502,"./koa.ts":1502,"./nestjsRouterExecutionContext":646,"./nestjsRouterExecutionContext.ts":646,"./nestjsRpcContextCreator":4290,"./nestjsRpcContextCreator.ts":4290,"./nextJsConfig":9723,"./nextJsConfig.ts":9723,"./nextJsModuleLoader":1326,"./nextJsModuleLoader.ts":1326,"./nextRequestAdapter":7246,"./nextRequestAdapter.ts":7246,"./nextjs":9589,"./nextjs.ts":9589,"./router":5946,"./router.ts":5946,"./serverlessHttp":2729,"./serverlessHttp.ts":2729,"./sqsConsumer":5150,"./sqsConsumer.ts":5150};function o(e){var t=s(e);return r(t)}function s(e){if(!r.o(n,e)){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}return n[e]}o.keys=function(){return Object.keys(n)},o.resolve=s,e.exports=o,o.id=2828},2977:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.patchRoute=function(e){const t=(0,g.getMethods)();t.concat("all").forEach(function(r){const n=e.prototype[r];e.prototype[r]=function(){let e;try{e=p(Array.prototype.slice.call(arguments));let n=function(e){const t=e[0][a.hudConfig.express.layerStateSymbol];if(t)return t.flowId}(e);const o=function(e){const t=e[0][a.hudConfig.express.layerStateSymbol];if(t)return t.kind}(e),s=function(e){const t=e[0][a.hudConfig.express.layerStateSymbol];return!!t&&t.allMethod}(e);if(n||(n=[l.randomUUID()]),"application"===o)if(Array.isArray(this.path)){_(e,void 0);for(let e=0;e<this.path.length;e++)h(n[e],s?t:[r],this.path[e])}else _(e,n[0]),h(n[0],s?t:[r],this.path);else if("router"===o)if(Array.isArray(this.path)){_(e,void 0);for(let e=0;e<this.path.length;e++)m(this,n[e],r,this.path[e])}else _(e,n[0]),m(this,n[0],r,this.path);else _(e,n[0]),m(this,n[0],r,this.path)}catch(e){d.instrument_logger.error("Failed to patch express.Route.route",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return n.apply(this,e||arguments)}})};const a=r(5809),c=r(8528),u=r(8269),d=r(523),l=i(r(6982)),f=r(8949),g=r(6730),p=r(5673);function m(e,t,r,n){!function(e,t,r,n){e[a.hudConfig.express.layerStateSymbol]||(e[a.hudConfig.express.layerStateSymbol]={}),e[a.hudConfig.express.layerStateSymbol][t]?e[a.hudConfig.express.layerStateSymbol][t].methods.push(r):e[a.hudConfig.express.layerStateSymbol][t]={layerPath:n,methods:[r]}}(e,t,r,n),function(e,t,r){const n=new c.EndpointDeclaration(e,[t],"express",void 0,void 0,r);(0,u.storePartialEndpointDeclaration)(n),(0,u.storeExpressEndpointDeclaration)(n)}(t,r,n)}function h(e,t,r){const n=new c.EndpointDeclaration(e,t,"express",void 0,r,void 0);(0,u.storeExpressEndpointDeclaration)(n)}function _(e,t){if(e&&!(e.length<1)){if(a.hudConfig.express.wrapAllCallbacks)for(let r=0;r<e.length;r++){const n=(0,f.wrapFlow)(v(t),e[r],!0,b);e[r]=n}else{const r=(0,f.wrapFlow)(v(t),e[e.length-1],!0,b);e[e.length-1]=r}return t}}function y(e){return(0,u.getLinkedConsistentFlowId)(e,!1)||(d.instrument_logger.warn("No consistent flowId found, returning temporary flow id",{flowId:e}),e)}function v(e){return e?function(){return y(e)}:function(e){const t=e[0]?.route[a.hudConfig.express.layerStateSymbol],r=e[0]?.url;if(t)for(const[e,n]of Object.entries(t)){if(n.layerPath instanceof RegExp&&n.layerPath.test(r))return y(e);if(r.includes(n.layerPath))return y(e)}d.instrument_logger.warn("No flowId found for path",{states:t,url:r.split("?")[0]})}}function b(e,t,r){let n=0;if(4===r.length)n=1;else if(3!==r.length)return void d.instrument_logger.error("Invalid number of arguments in express request",{length:r.length});if(!r[n])return void d.instrument_logger.error("No request object in express request");const o=r[n][a.hudConfig.metricSymbol];o?o.setFlowId(e):d.instrument_logger.error("No endpoint metric found in express request")}},2987:e=>{"use strict";e.exports=require("perf_hooks")},3176:e=>{"use strict";e.exports=require("buffer-crc32")},3339:e=>{"use strict";e.exports=require("module")},3868:e=>{"use strict";e.exports=require("@jridgewell/sourcemap-codec")},3901:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getFunctionWrapperTemplate=b,t.splitCode=E,t.editInSplits=I,t.editWithCliBuildId=function(e,t,r,n){let{transformedCode:o,metadatas:s}=F(e,t,r,[],!0);return o+=`\n//# sourceMappingURL=${y.default.basename(t)}.map`,o+=`\n//"${n}";${d.hudConfig.cliSdkVersionVarName}="${d.SDK_VERSION}";${d.hudConfig.cliBuildIdVarName}`,{transformedCode:o,metadatas:s}},t.edit=F,t.incrementInstrumentedFunctionsCount=T;const c=a(r(3176)),u=r(3903),d=r(5809),l=r(2546),f=r(523),g=r(8528),p=r(8269),m=r(2546),h=r(3868),_=i(r(2784)),y=a(r(6928)),v=/([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})/;function b(e,t,r=!1){const n=`${e}_hudTemp`,o="BODY_PLACEHOLDER",s="FUNCTION_ID_PLACEHOLDER",i="AWAITABLE_PLACEHOLDER",a="EXCEPTION_VARIABLE_PLACEHOLDER",c=function(e,t,r=!1){const n=[];if(r)return n;let o;t===g.Format.cjs?o="require":t===g.Format.esm&&(n.push(`import { createRequire as ${e}_createRequire } from "module";`,`const ${e}_require = ${e}_createRequire(import.meta.url);`),o=`${e}_require`);const s=m.myRequire.resolve(d.SDK_MODULE_NAME+"/wrap");return n.push(`let ${e}_temp;`,`try { ${e}_temp = ${o}(String.raw\`${s}\`); } catch (e) { ${e}_temp = { wrapperInitial: () => {}, wrapperCatch: () => {}, wrapperFinally: () => {}, fixStack: () => {}, wrapperUserCatch: () => {} }; }`,`const { wrapperInitial: ${e}_wi, wrapperCatch: ${e}_wc, wrapperFinally: ${e}_wf, fixStack: ${e}_fs, asyncIteratorWrapper: ${e}_aiw, wrapperUserCatch: ${e}_wuc } = ${e}_temp;`),n}(e,t,r);return{functionWrapper:`{\n let ${n};\n const ${d.hudConfig.functionIdVarName} = ${s};\n const ${e}_cc = {};\n try {\n ${e}_wi(${d.hudConfig.functionIdVarName}, ${e}_cc);\n } catch (e) {\n globalThis._hud_SI = { value: 0 };\n globalThis._hud_S = [];\n }\n try {\n ${o}\n } catch (e) {\n try {\n ${e}_wc(${d.hudConfig.functionIdVarName}, ${e}_cc, e);\n } catch (e) {}\n throw e;\n } finally {\n try {\n ${e}_wf(${d.hudConfig.functionIdVarName}, ${e}_cc);\n } catch (e) {}\n }\n }`,awaitWrapper:`(${n} = ${i}, _hud_SI.value--, ${e}_cc.ff = true, ${n} = await ${n}, _hud_S[++_hud_SI.value] = ${d.hudConfig.functionIdVarName}, ${e}_cc.ff= false, ${n})`,yieldWrapper:`\n function* ${e}_generatorWrapper() {\n return (${n} = ${i}, _hud_SI.value--, ${e}_cc.ff = true, ${n} = yield ${n}, _hud_S[++_hud_SI.value] = ${d.hudConfig.functionIdVarName}, ${e}_cc.ff= false, ${n})\n }`,yieldStarWrapper:`\n function* ${e}_generatorWrapper() {\n return (${n} = ${i}, _hud_SI.value--, ${e}_cc.ff = true, ${n} = yield* ${n}, _hud_S[++_hud_SI.value] = ${d.hudConfig.functionIdVarName}, ${e}_cc.ff= false, ${n})\n }`,initialStatements:c,bodyPlaceholder:o,functionIdPlaceholder:s,awaitablePlaceholder:i,fixStackFunction:`\n try{\n ${e}_fs(${d.hudConfig.functionIdVarName}, ${e}_cc)\n }catch(e){};`,exceptionVariablePlaceholder:a,wrapperUserCatch:`\n try {\n ${e}_wuc(${d.hudConfig.functionIdVarName}, ${e}_cc, ${a});\n } catch(e){};`,asyncIteratorWrapper:`${e}_aiw`,awaitableVariable:n}}function w(e,t,r,n=!0,o=!1,s){const i=Error.prepareStackTrace;let a=!1,l=function(e){const t=e.match(`${d.hudConfig.bundlerBuildIdVarName}="${v.source}"`);if(t&&t.length>0)return t[1]}(e);l||(l=function(e){return(0,u.v5)(e,d.hudConfig.bundlerBuildUuidNamespace)}(e),a=!0);const g=(0,u.v5)(e,d.hudConfig.functionUuidNamespace),p=(0,c.default)(t.filename).readUInt32BE(),h=(0,c.default)(e).readUInt32BE(),y=(0,m.isNextJsApp)(),w={data:t,bundlerBuildId:l,prefix:d.hudConfig.wrapVarPrefix,...b(d.hudConfig.wrapVarPrefix,t.format,o),uuidNamespace:d.hudConfig.functionUuidNamespace,fileHash:g,functionsToInstrument:r,useInputSourcemap:n,isNextJsFile:y,markCode:d.hudConfig.nextJsMarkVarName,enableForAwaitInstrumentation:!s},k=_.transform(e,w);return T(k.functionsIds.length,s),y&&k.marksCount!==k.functionsIds.length&&f.instrument_logger.warn("Marks count mismatch while instrumenting functions",{marksCount:k.marksCount,functionsIdsLength:k.functionsIds.length,filename:t.filename}),Error.prepareStackTrace=i,f.instrument_logger.debug(`Successfully transformed ${t.filename}`),{code:k.code,map:k.map,functionIds:k.functionsIds,filename:t.filename,hasInputMap:k.isInputSourcemap,bundlerBuildId:l,bundlerBuildIdGenerated:a,file_path_checksum:p,file_checksum:h,sourceCodeHash:g,moduleBase:k.moduleBase,isNextJsApp:y,marksCount:k.marksCount,detectedForAwaitLoops:k.detectedForAwaitLoops}}class k extends Error{}function S(e,t){if(e&&t)throw new k("Start mark found inside mark");if(!e&&!t)throw new k("End mark found outside mark")}function x(e,t,r,n){const o=e.split("\n");let s=r,i=n;return s+=o.length-1,s+=t.split("\n").length-1,s===r?i+=o.pop()?.length||0:i=o.pop()?.length||0,{lineOffset:s,columnOffset:i}}function*E(e){let t=!1,r=0,n=0,o=!1,s=0,i=0;const a=new RegExp(`globalThis\\s*?&&\\s*?\\(globalThis\\.${d.hudConfig.esbuildGlobalVar}\\s*?=\\s*?"(Start|End):(?<fileName>.*?)"\\);?`,"g");for(const c of e.matchAll(a)){if(o=!0,!c.groups)throw new k("No groups found in match");const{fileName:a}=c.groups,[u,d]=c,l="Start"===d;S(l,t);let f="";if(t){const t=c.index+u.length;f=e.slice(r,t);const o=n+Buffer.byteLength(f,"utf8");yield{edit:!0,code:f,fileName:a,lineOffset:s,columnOffset:i,indexOffset:n,indexOffsetEnd:o},r=t,n=o}else{const t=c.index;f=e.slice(r,t),n+=Buffer.byteLength(f,"utf8"),r=t,yield{edit:!1,code:f}}t=!!l,({lineOffset:s,columnOffset:i}=x(f,u,s,i))}if(t)throw new k("End mark found outside mark");o?r<e.length&&(yield{edit:!1,code:e.slice(r)}):yield{edit:!1,code:e}}function M(e,t,r){f.instrument_logger.debug("Edit chunk",{fileName:e.fileName,size:e.code.length,edit:t}),r?.push({fileName:e.fileName,size:e.code.length,edit:t})}function C(e,t,r){const n=w(e.code,{filename:t,format:r},[],!1,!0,!1),o=n.code;return n.mapRelativeToChunk=n.map,n.map=function(e,t,r){"string"==typeof e&&(e=JSON.parse(e));const n=(0,h.decode)(e.mappings);return n.forEach(e=>{e.forEach(e=>{e.length>=4&&"number"==typeof e[2]&&("number"==typeof e[3]&&0===e[2]&&(e[3]+=r),e[2]+=t)})}),JSON.stringify({...e,mappings:(0,h.encode)(n),sourcesContent:void 0})}(n.map,e.lineOffset,e.columnOffset),{codeToAppend:o,metadata:{...n,filename:t,lineOffset:e.lineOffset,columnOffset:e.columnOffset}}}function I(e,t,r,n=!1,o=!1,s=()=>!0){const i=e.slice(-1e3);if(!o&&null!==_.getSourceMap(t,i))return f.instrument_logger.error("Source map found for esbuild split",{filename:t}),f.customer_logger.log(l.UserErrorLogs.EsbuildSourceMapFound()),(0,p.detachHud)(!1,!1),{transformedCode:e,metadatas:[],editedChunksSizes:void 0};let a="",c=0,u=0;const g=[];let m=0;const h=n?[]:void 0,y=b(d.hudConfig.wrapVarPrefix,r).initialStatements.join("\n"),v=function(e){return e.slice(d.hudConfig.esbuildMark.length,d.hudConfig.esbuildMark.length+36)}(e);for(const n of E(e)){m++;try{let e="",o=!1;if(n.edit&&(o=s(n.fileName),h&&M(n,o,h)),n.edit&&o){const o=C(n,t,r);e=o.codeToAppend,g.push({...o.metadata,bundlerBuildId:v,transformedLineOffset:c,transformedColumnOffset:u,indexOffset:n.indexOffset,indexOffsetEnd:n.indexOffsetEnd})}else e=0===a.length?P(n.code,y):n.code;({transformedCodeLineOffset:c,transformedCodeColumnOffset:u}=O(e,c,u)),a+=e}catch(r){return f.instrument_logger.error("Failed to patch index",{index:m,filename:t,msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0}),{transformedCode:e,metadatas:[],editedChunksSizes:h}}}return{transformedCode:a,metadatas:g,editedChunksSizes:h}}function P(e,t){let r="";return e.startsWith('"use strict";')?(r+='"use strict";',r+=t,r+=e.slice(13),r):(r+=t,r+=e,r)}function O(e,t,r){const n=e.split("\n");return n.length>1?(t+=n.length-1,r=n.pop()?.length||0):r+=e.length,{transformedCodeLineOffset:t,transformedCodeColumnOffset:r}}function F(e,t,r,n,o){if(e.startsWith(d.hudConfig.esbuildMark))return f.instrument_logger.info("Editing in splits"),I(e,t,r,!1);{const s=w(e,{filename:t,format:r},n,d.hudConfig.userConfig.disableSourceMapsResolution?.value??!0,!1,o);return{transformedCode:s.code,metadatas:[s]}}}let N=0;function T(e,t){N+=e;const r=d.hudConfig.userConfig?.maxMappedFunctions?.value??0;N>=r&&(t||f.customer_logger.log(l.UserErrorLogs.InstrumentedFunctionCountExceeded(r)),f.app_logger.error("Instrumented function count exceeded",{instrumentedFunctionsCount:N,maxMappedFunctions:r}),(0,p.detachHud)(!1,!1))}},3903:e=>{"use strict";e.exports=require("uuid")},4290:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(523),o=r(8949),s=r(5128),i=r(714);class a extends i.FrameworkPatcher{_patch(e){return this._patchCreate(e),n.instrument_logger.info("Patched NestJS RpcContextCreator successfully"),e}_patchCreate(e){const t=e.RpcContextCreator.prototype.create;e.RpcContextCreator.prototype.create=function(...e){try{const t=e[0],r=e[1];"function"==typeof t.constructor&&"function"==typeof r?e[1]=(0,s.wrapLinkedFunction)(r):n.instrument_logger.error("Invalid args in NestJS RpcContextCreator.create",{args:e})}catch(e){n.instrument_logger.error("Error in NestJS RpcContextCreator patcher",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t.apply(this,e)},(0,o.copyPropertiesToTarget)(t,e.RpcContextCreator.prototype.create)}}t.default=a},4815:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.patchUse=function(e,t,r=!0){const n=e.use;e.use=function(e){const o=n.apply(this,arguments);try{let n=this[f.uuidSymbol];!n&&f.isVerboseLoggingEnabled&&(n=d.randomUUID(),this[f.uuidSymbol]=n,u.instrument_logger.info("Express use setting uuid",{kind:t,uuid:n})),"application"===t?function(e,t,r,n){try{r&&(e._router?p(e._router):e.router?p(e.router):u.instrument_logger.warn("Express application doesn't have router or _router")),n&&f.isVerboseLoggingEnabled&&u.instrument_logger.info("Express use app",{parent:n,child:t[1]?.[f.uuidSymbol]||"no uuid",path:t[0]})}catch(e){u.instrument_logger.error("Failed to save express app router",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}(this,arguments,r,n):"router"===t&&function(e,t,r,n,o){try{if(!e.stack)return void u.instrument_logger.error("Express router without stack");if(0===e.stack.length)return void u.instrument_logger.warn("Express router with an empty stack");"query"===e.stack[0].name?p(e):f.isVerboseLoggingEnabled&&!f.skipLayerNamesLogs.has(e.stack[0].name)&&(f.skipLayerNamesLogs.add(e.stack[0].name),u.instrument_logger.warn("Found unknown stack name",{stack:e.stack[0].name}));const{path:s,offset:i}=function(e){let t=0,r="/";if("function"!=typeof e){let n=e;for(;Array.isArray(n)&&0!==n.length;)n=n[0];"function"!=typeof n&&(t=1,r=e)}return{path:r,offset:t}}(o),c=g(Array.prototype.slice.call(t,i));for(let t=0;t<c.length&&t<e.stack.length;t++){const o=e.stack[e.stack.length-t-1],i=c[c.length-t-1];"router"===o.name?(i&&!i[f.uuidSymbol]&&f.isVerboseLoggingEnabled&&(i[f.uuidSymbol]=d.randomUUID(),u.instrument_logger.info("Express handle router setting uuid",{uuid:i[f.uuidSymbol]})),r&&(o[a.hudConfig.express.routeNamesSymbol]=s)):f.isVerboseLoggingEnabled&&!f.skipLayerNamesLogs.has(o.name)&&(f.skipLayerNamesLogs.add(o.name),u.instrument_logger.warn("Found unknown layer name",{layer:o.name,parent:n,child:i[f.uuidSymbol]||"no uuid",path:s}))}}catch(e){u.instrument_logger.error("Failed to patch router.use function",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}(this,arguments,r,n,e)}catch(e){u.instrument_logger.error("Failed to patch express.use function",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return o},(0,l.copyPropertiesToTarget)(n,e.use)},t.extractEndpointsFromRouter=function e(t,r){let n=[];if(!r.stack)return u.instrument_logger.error("Router without stack - bad OTEL version",{router:r}),n;for(const o of r.stack)if("router"===o.name){if(!o[a.hudConfig.express.routeNamesSymbol]){u.instrument_logger.error("Router layer without routes",{layer:o});continue}const r=t+o[a.hudConfig.express.routeNamesSymbol];n=n.concat(e(r,o.handle))}else o.route&&o.route[a.hudConfig.express.layerStateSymbol]?n=n.concat(m(o,t)):f.isVerboseLoggingEnabled&&!f.skipLayerNamesLogs.has(o.name)&&(f.skipLayerNamesLogs.add(o.name),u.instrument_logger.warn("Found unknown layer name when extracting endpoints",{layer:o.name}));return n};const a=r(5809),c=r(8528),u=r(523),d=i(r(6982)),l=r(8949),f=r(7225),g=r(5673);function p(e){e[a.hudConfig.express.markedSymbol]||(globalThis.hudExpressState.push(e),e[a.hudConfig.express.markedSymbol]=!0)}function m(e,t){const r=[];for(const[n,o]of Object.entries(e.route[a.hudConfig.express.layerStateSymbol]))r.push(new c.EndpointDeclaration(n,o.methods,"express",t,o.layerPath));return Array.from(r.values())}},5128:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHudLfMarked=void 0,t.wrapLinkedFunction=function(e){if(e[t.isHudLfMarked])return e;let r;e[t.isHudLfMarked]=!0;const a=(0,s.getFlowStateStorage)();return a?(r=e instanceof i.AsyncFunction?async function(...t){if(hudRunningMode!==n.HudRunningMode.enabled)return await e.apply(this,t);let r;try{r=a.getStore()}catch(r){return o.instrument_logger.error("Failed to get flowState",{msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0}),await e.apply(this,t)}return r?(r.shouldLinkFunction=!0,await e.apply(this,t)):await e.apply(this,t)}:function(...t){if(hudRunningMode!==n.HudRunningMode.enabled)return e.apply(this,t);let r;try{r=a.getStore()}catch(r){return o.instrument_logger.error("Failed to get flowState",{msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0}),e.apply(this,t)}return r?(r.shouldLinkFunction=!0,e.apply(this,t)):e.apply(this,t)},(0,i.copyPropertiesToTarget)(e,r),r):e};const n=r(8528),o=r(523),s=r(7131),i=r(8949);t.isHudLfMarked=Symbol.for("isHudLfMarked")},5150:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5809),o=r(8269),s=r(2546),i=r(523),a=r(7131),c=r(2822),u=r(8949),d=r(2080),l=r(714);class f extends l.FrameworkPatcher{isSupported(e,t,r,o){const a=n.hudConfig.userConfig.enableDapulse?.value?o.mondayVersion:o.bbcVersion,c=(0,l.extractModuleVersion)(e);return!!(0,l.isSupportedVersion)(c,a)||(i.instrument_logger.warn("Unsupported sqs-consumer version",{framework:"SqsConsumer",version:c,supportedVersion:a,basedir:e,isDapulse:n.hudConfig.userConfig.enableDapulse?.value}),i.customer_logger.log(s.UserErrorLogs.UnsupportedFrameworkVersion("sqs-consumer")),!1)}_patch(e){return function(e){const t=e.Consumer.create;e.Consumer.create=function(...e){const r=t.apply(this,e);try{!function(e){const t=e.queueUrl;if(!t)throw new s.HudNoQueueUrlInSqsConsumer;const r=m(t);if(e.handleMessageBatch&&"function"==typeof e.handleMessageBatch){const t="handleMessageBatch",n=(0,s.generateSqsFlowId)(r,t);(0,o.storeSqsQueueDeclaration)({flow_id:n,queue_name:r,handle_type:t,batch_size:e.batchSize});const i=e.handleMessageBatch,a=(0,u.wrapFlow)(()=>n,i,!0,h);return void(e.handleMessageBatch=a)}if(e.handleMessage&&"function"==typeof e.handleMessage){const t="handleMessage",n=(0,s.generateSqsFlowId)(r,t);(0,o.storeSqsQueueDeclaration)({flow_id:n,queue_name:r,handle_type:t});const i=e.handleMessage,a=(0,u.wrapFlow)(()=>n,i,!0,h);return void(e.handleMessage=a)}i.instrument_logger.warn("Unable to getFlowId - No handleMessage or handleMessageBatch found in SqsConsumer.Consumer",{queueName:r})}(r),function(e){const t=e.on;e.on=function(...r){try{const t=r[0];if(!t||"string"!=typeof t)throw new s.HudNoEventTypeInSqsConsumerOn;const n=r[1];if(!n||"function"!=typeof n)throw new s.HudNoCallbackInSqsConsumerOn;const i=m(e.queueUrl),a="event",c=(0,s.generateSqsFlowId)(i,a,t);(0,o.storeSqsQueueDeclaration)({flow_id:c,queue_name:i,handle_type:a,event_type:t}),r[1]=(0,u.wrapFlow)(()=>c,n,!0,_,y,v)}catch(e){i.instrument_logger.error("Error in SqsConsumer.Consumer.on patched logic",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t.apply(this,r)},(0,u.copyPropertiesToTarget)(t,e.on)}(r),function(e){const t=e.emit;e.emit=function(...e){return function(e){try{const t=e[0];if(!t||"string"!=typeof t)throw new s.HudNoEventTypeInSqsConsumerEmit;let r,o;if("message_processed"===t&&(r=1),["error","timeout_error","processing_error"].includes(t)&&(o=1,r=2),void 0===r)return;const u=e[r];if(!u)throw new s.HudNoMessageInSqsConsumerEmit;let d;if(void 0!==o){const t=e[o];if(!(t&&t instanceof Error))throw new s.HudNoErrorInSqsConsumerEmit;d=(0,a.extractName)(t),"StandardError"===d&&t.cause&&t.cause instanceof Error&&(d=(0,a.extractName)(t.cause))}const l=(e,t)=>{const r=e[n.hudConfig.metricSymbol];r?(d&&r.addError(d,t),r.increaseAndShouldEnd(t)&&(r.end(),(0,c.finishSqsInvestigation)(Array.isArray(u)?u:[u],r))):p||(p=!0,i.instrument_logger.warn("No metric found for message"))};Array.isArray(u)&&u.length>=1?l(u[0],u.length):l(u,1)}catch(e){g||(g=!0,i.instrument_logger.error("Error in SqsConsumer.Consumer.emit patched logic",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}))}}(e),t.apply(this,e)},(0,u.copyPropertiesToTarget)(t,e.emit)}(r)}catch(e){i.instrument_logger.error("Error in patching SqsConsumer.Consumer",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return r},(0,u.copyPropertiesToTarget)(t,e.Consumer.create)}(e),i.instrument_logger.info("Patched sqs-consumer successfully",{isDapulse:n.hudConfig.userConfig.enableDapulse?.value}),e}}t.default=f;let g=!1,p=!1;function m(e){const t=e.split("/").pop();if(!t)throw new s.HudFailExtractSqsQueueName(`Url: ${e}`);return t}function h(e,t,r){const o=d.SqsMetric.createUsableMetric(e);o.start();const s=r[0];if(!s)return i.instrument_logger.warn("No messages pass to sqs handler",{flowId:e}),void(t.flowMetric=o);if(Array.isArray(s)){if(o.msgCount=s.length,s.forEach(e=>{e[n.hudConfig.metricSymbol]=o}),s[0]?.Attributes?.SentTimestamp){const t=s.reduce((e,t)=>{const r=Number.parseInt(t?.Attributes?.SentTimestamp);return isNaN(r)?e:Math.min(e,r)},1/0);t!==1/0?o.e2eEpocStartTimeMS=t:i.instrument_logger.warn("No valid SentTimestamp found eventhough the first element had SentTimestamp",{flowId:e})}}else o.msgCount=1,s[n.hudConfig.metricSymbol]=o,s?.Attributes?.SentTimestamp&&(o.e2eEpocStartTimeMS=s.Attributes.SentTimestamp);t.flowMetric=o,(0,c.createNewInvestigation)()}function _(e,t,r){const n=d.SqsMetric.createUsableMetric(e);n.start(),t.flowMetric=n}function y(e,t){const r=t.flowMetric;r?r.end():i.instrument_logger.warn("No flowMetric found for message during catch",{flowId:e})}function v(e,t,r){const n=t.flowMetric;n?(n.addError((0,a.extractName)(r)),n.end()):i.instrument_logger.warn("No flowMetric found for message during catch",{flowId:e})}},5459:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getHttpMetricFromRequest=function(e){return e[n.hudConfig.metricSymbol]};const n=r(5809),o=r(523),s=r(2822),i=r(8949),a=r(8901),c=r(714);class u extends c.FrameworkPatcher{_patch(e){return this._patchEmit(e),o.instrument_logger.info("Patched http successfully"),e}_patchEmit(e){const t=e.Server.prototype.emit;e.Server.prototype.emit=function(e,...r){if("request"!==e)return t.apply(this,[e,...r]);try{const e=r[0],t=r[1],i=a.HttpEndpointMetric.createUsableMetric();i.start(),(0,s.createNewInvestigation)(),i.setRequestAttributes(e),t.once("finish",function(){try{(0,s.finishHttpInvestigation)(e,t,i),i.setResponseAttributes(t),i.end()}catch(e){o.instrument_logger.error("Failed to set response attributes",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}),e[n.hudConfig.metricSymbol]=i}catch(e){o.instrument_logger.error("Failed to patch http.Server.prototype.emit",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t.apply(this,[e,...r])},(0,i.copyPropertiesToTarget)(t,e.Server.prototype.emit)}}t.default=u},5673:e=>{"use strict";e.exports=require("array-flatten")},5688:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.hudRITM=void 0,t.safeLog=function(e){try{i.app_logger.debug(e)}catch{return}},t.registerHook=function(){if(i.app_logger.info("HUD is required"),process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE){if(i.app_logger.info("Running in Lambda environment"),parseInt(process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE)<n.hudConfig.lambdaMinimunMemory){const e=process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE;return i.app_logger.warn("Lambda function memory size is less than required, Hud will not run",{memorySize:e}),i.customer_logger.log(s.UserErrorLogs.UnsupportedLambdaMemory(n.hudConfig.lambdaMinimunMemory)),!1}globalThis.hudRuningInsideLambda=!0}return(0,o.initGlobals)(),i.app_logger.debug("InitGlobals done"),!(globalThis.hudStartFromAutoInit&&!(0,o.validateAndGetUserInput)())&&(i.instrument_logger.isValid()?globalThis.hudRanOnRequire?(i.instrument_logger.warn("Already ran onRequire!"),!1):(globalThis.hudRanOnRequire=!0,i.instrument_logger.info("Using module",{name:n.SDK_MODULE_NAME}),n.hudConfig.userConfig.enableFrameworks&&i.instrument_logger.info("User enabled frameworks",{frameworks:(0,a.getEnabledFrameworks)()}),(0,a.onRequire)(),(0,s.detectNextJsApp)(),i.instrument_logger.debug("onRequire done"),globalThis.hudInitGuard=setTimeout(c,n.hudConfig.userConfig.maxTimeUntilInitSessionMs?.value??0),globalThis.hudInitGuard.unref(),!0):((0,o.detachHud)(!1),!1))};const n=r(5809),o=r(8269),s=r(2546),i=r(523),a=r(7166);function c(){i.instrument_logger.warn("Init timeout disabling hud!"),i.customer_logger.log(s.UserErrorLogs.InitTimeout(globalThis.hudIsRunningFromSetup)),(0,o.detachHud)(!1)}t.hudRITM=a.onRequireFn},5809:e=>{"use strict";e.exports=require("./config")},5946:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(523),o=r(6730),s=r(4815),i=r(714);class a extends i.FrameworkPatcher{_patch(e){return(0,s.patchUse)(e.prototype,"router"),(0,o.patchMethods)(e.prototype,"router"),n.instrument_logger.info("Patched router successfully"),e}}t.default=a},6093:e=>{"use strict";e.exports=require("@cspotcode/source-map-support")},6504:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GraphQLMetric=void 0;const n=r(9873);class o extends n.FlowMetric{constructor(e){super(e)}_createUsableMetric(e){return this}toRaw(){return{flow_id:this.flowId,type:"GraphQLMetric",duration:this.duration}}}t.GraphQLMetric=o},6730:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.getMethods=f,t.patchMethods=function(e,t){f().concat("all").forEach(function(r){const n=e[r];if(!n)return void(l.isVerboseLoggingEnabled&&c.instrument_logger.warn("Method not found",{method:r}));const o="all"===r;e[r]=function(){try{if(arguments.length<2)return n.apply(this,arguments);let e=this[l.uuidSymbol];l.isVerboseLoggingEnabled&&(e||(e=u.randomUUID(),this[l.uuidSymbol]=e,c.instrument_logger.info("Express method setting uuid",{uuid:e,kind:t})),c.instrument_logger.info("Express added new method",{method:r,uuid:e,path:arguments[0]}));const s=Array.prototype.slice.call(arguments);if(s[1][a.hudConfig.express.layerStateSymbol]={flowId:[],kind:t,allMethod:o},Array.isArray(s[0]))for(const e of s[0]){const e=u.randomUUID();s[1][a.hudConfig.express.layerStateSymbol].flowId.push(e)}else s[1][a.hudConfig.express.layerStateSymbol].flowId.push(u.randomUUID());const i=n.apply(this,s);try{delete s[1][a.hudConfig.express.layerStateSymbol]}catch{}return i}catch(e){c.instrument_logger.error("Failed to patch method",{kind:t,method:r,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return n.apply(this,arguments)},(0,d.copyPropertiesToTarget)(n,e[r])})};const a=r(5809),c=r(523),u=i(r(6982)),d=r(8949),l=r(7225);function f(){const e=r(8611);return e.METHODS&&e.METHODS.map(function(e){return e.toLowerCase()})||["get","post","put","head","delete","options","trace","copy","lock","mkcol","move","purge","propfind","proppatch","unlock","report","mkactivity","checkout","merge","m-search","notify","subscribe","unsubscribe","patch","search","connect"]}},6928:e=>{"use strict";e.exports=require("path")},6982:e=>{"use strict";e.exports=require("crypto")},7127:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(523),o=r(6730),s=r(2977),i=r(4815),a=r(7225),c=r(714);class u extends c.FrameworkPatcher{_patch(e){return(0,s.patchRoute)(e.Route),(0,i.patchUse)(e.application,"application"),(0,o.patchMethods)(e.application,"application"),a.isVerboseLoggingEnabled&&(0,a.logLazyRouter)(e.application),e.Router.use?((0,i.patchUse)(e.Router,"router"),(0,o.patchMethods)(e.Router,"router")):n.instrument_logger.warn("Skipping express.Router patching"),n.instrument_logger.info("Patched express successfully"),e}}t.default=u},7131:e=>{"use strict";e.exports=require("./wrap")},7166:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.parseCliInstrumentationPattern=k,t.supportSourceMapInstall=S,t.patch=x,t.patchCompile=I,t.onRequireFn=P,t.patchRequire=O,t.isFrameworkEnabled=F,t.getEnabledFrameworks=function(){const e=new Map;for(const[t,r]of g.hudConfig.frameworksToPatch)e.set(r.framework,F(r,g.hudConfig.userConfig.enableFrameworks));return Object.fromEntries(e)},t.getFunctionsToInstrument=q,t.createCheckers=R,t.updateModuleChecker=A,t.skip=D,t.onRequire=function(){try{(0,d.setInstrumentedFilesCountInterval)(),A();try{I()}catch(e){l.instrument_logger.error("Failed to patch compile",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{(0,d.shouldSupportSourceMap)()&&S()}catch(e){l.instrument_logger.error("Failed to install source map support",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{O()}catch(e){l.instrument_logger.error("Failed to patch require",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}catch(e){l.instrument_logger.error("Something went wrong in onRequire",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{(0,m.saveMachineMetric)()}catch(e){l.instrument_logger.error("Failed to add metric",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};const a=i(r(9896)),c=i(r(6928)),u=r(8528),d=r(2546),l=r(523),f=r(3901),g=r(5809),p=r(8528),m=r(8269),h=r(2546),_=r(9063),y=r(714),v=function(){const e=g.SDK_MODULE_NAME;try{return c.dirname(c.dirname(h.myRequire.resolve(e)))}catch(t){return l.instrument_logger.error("Failed to resolve own path",{moduleName:e,msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0}),null}}();function b(e){const t=globalThis.HudSourceMapCache.get(e);return t?{map:JSON.parse(t)}:null}const w=new RegExp(`//"([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})";${g.hudConfig.cliSdkVersionVarName}="([^"]+)";${g.hudConfig.cliBuildIdVarName}`);function k(e){if(e.slice(-g.hudConfig.cliBuildIdVarName.length)!==g.hudConfig.cliBuildIdVarName)return null;const t=Math.min(100,e.length),r=e.slice(-t).match(w);return r?{buildId:r[1],sdkVersion:r[2],fullPattern:r[0]}:null}function S(){r(6093).install({handleUncaughtExceptions:!1,hookRequire:!1,environment:"node",retrieveSourceMap:b})}function x(e,t,r,n){const o={code:e,map:void 0};try{if(globalThis.hudRunningMode===p.HudRunningMode.detached)return o;if(r===u.Format.esm&&!n)throw new h.HudError("MessagePort is required for patching ESM modules");const s=k(e);if(s)return s.sdkVersion!==g.SDK_VERSION?(l.instrument_logger.error("SDK version mismatch detected, disabling SDK",{filename:t,cliSdkVersion:s.sdkVersion,currentSdkVersion:g.SDK_VERSION}),(0,m.detachHud)(!1,!1),o):((0,m.addReingestValue)(s.buildId),globalThis.hudInstrumentationIndicator&&(0,m.clearInstrumentationIndicator)(),o);if(g.hudConfig.userConfig.disableRuntimeInstrumentation?.value)return o;const i=q(t);if(D(t,void 0,i))return o;if(e.length>(g.hudConfig.userConfig.maxFileSizeBytes?.value??0)&&!e.startsWith(g.hudConfig.esbuildMark))return l.instrument_logger.info("Skipping large file",{filename:t,size:e.length}),o;const _=Date.now(),y=(0,f.edit)(e,t,r,i,!1),v=y.metadatas;if(o.code=y.transformedCode,o.map=v,l.instrument_logger.debug("Patched",{filename:t,time:Date.now()-_}),n)for(const e of v)n.postMessage({key:"HudModulePatch",hudPatched:t,hudProcessedFiles:(0,d.sourceFileMetadataToTransferSourceFileMetadata)(e)});else globalThis.hudPatched.add(t),globalThis.hudProcessedFiles.push(...v.map(e=>(0,d.sourceFileMetadataToTransferSourceFileMetadata)(e)));for(const e of v)e.functionIds.length>0&&(globalThis.hudInstrumentationOccured=!0,globalThis.hudInstrumentationIndicator&&(0,m.clearInstrumentationIndicator)(),(0,d.incrementInstrumentedFilesCount)());g.hudConfig.writePatched&&function(e,t){const r=c.parse(e);let n=`${r.dir}/patched.${r.base}`;r.dir.includes("dist")&&(n=c.join(`${r.dir.replace("dist","patched")}`,r.base)),a.existsSync(c.dirname(n))||a.mkdirSync(c.dirname(n),{recursive:!0}),a.writeFileSync(n,t,"utf8"),l.instrument_logger.debug("Dumped patched file",{filename:e,patchedPath:n})}(t,y.transformedCode)}catch(e){l.instrument_logger.error("Failed to patch",{filename:t,format:r,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return o}let E="",M=!0,C=!1;function I(){if(!(0,h.isSupportedNative)())return;const e=r(3339),t=(0,d.shouldSupportSourceMap)();C&&l.instrument_logger.warn("PatchCompile ran twice"),0===Object.keys(globalThis.hudLoadedModules).length&&(globalThis.hudLoadedModules=Object.keys(h.myRequire.cache));const n=e.prototype._compile;e.prototype._compile=function(e,r){if(r===E){try{const e=M?l.instrument_logger.warn.bind(l.instrument_logger):l.instrument_logger.debug.bind(l.instrument_logger);M=!1,e("Skipping compile since already ran",{filename:r})}catch{}return n.call(this,e,r)}E=r,l.instrument_logger.verbose("Compiling requirement",{filename:r});const o=x(e,r,u.Format.cjs);try{if(t&&o.map){const e=(0,d.combineSourceMaps)(o.map,r);e&&globalThis.HudSourceMapCache.set(r,e)}}catch(e){l.instrument_logger.error("Failed to combine source maps",{filename:r,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}const s=n.call(this,o.code,r);return E="",s},C=!0,l.instrument_logger.debug("Patched _compile")}function P(e,t,r){try{const n=g.hudConfig.frameworksToPatch.get(t);return F(n,g.hudConfig.userConfig.enableFrameworks)&&n?.patcher&&n.version?(0,y.getFrameworkPatcher)(n.patcher).patch(e,r,n.version,n.extraInfo,t):e}catch(e){l.instrument_logger.error("Failed to patch framework",{name:t,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return e}function O(){const e=Array.from(g.hudConfig.frameworksToPatch.entries()).filter(([e,t])=>F(t,g.hudConfig.userConfig.enableFrameworks)).map(([e])=>e);new _.Hook(Array.from(e),{internals:!0},P)}function F(e,t){return!!e&&(t&&t.value?.has(e.framework)?t.value.get(e.framework)||!1:e.enable)}function N(e){const t=c.sep.replace(/\\/g,"\\\\"),r=c.join(e).split(".").join("\\.").split("*").join(".*?"),n=t+"node_modules"+t;return{isAllowdModule:new RegExp(n+r+`(?:${t}|$)`),isAllowdModuleSubModule:new RegExp(n+r+n)}}function T(e,t){return!!t.isAllowdModule.test(e)&&!t.isAllowdModuleSubModule.test(e)}function j(e,t){const r=t.replace(/\//g,c.sep);return e.includes(`node_modules${c.sep}${r}${c.sep}`)&&!e.includes(`node_modules${c.sep}${r}${c.sep}node_modules`)}function q(e){return(0,h.getInstrumentedThirdPartyModuleInfo)(e)?.functions||[]}function R(e){const t=[];for(const r of e){let e;if(r.includes("*")){const t=N(r);e=e=>T(e,t)}else e=e=>j(e,r);t.push(e)}return t}let L=[];function A(){L=R(g.hudConfig.userConfig.includeModules?.value??[])}function D(e,t,r=[]){if(!g.hudConfig.allowedEditExtensions.includes(c.extname(e))&&!e.endsWith(c.sep))return l.instrument_logger.warn("Skipping non-allowed extension",{filename:e}),!0;const n=t??L;return"/var/runtime/index.mjs"===e?(l.instrument_logger.debug("Skipping lambda runtime",{filename:e}),!0):e.includes("node_modules")&&!function(e,t){for(const r of t)if(r(e))return!0;return!1}(e,n)&&0===r.length||e.includes(".yarn")?(l.instrument_logger.debug("Skipping non-monitored imported module",{filename:e}),!0):!(v&&!e.includes(v)||(l.instrument_logger.debug("Skipping hud internal module",{filename:e}),0))}},7214:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(5809),o=r(8528),s=r(8269),i=r(2546),a=r(523),c=r(8949),u=r(6504),d=r(714);class l extends d.FrameworkPatcher{static graphQLPatchedSymbol=Symbol.for(n.hudConfig.hudPatchedName);_patch(e){return this.patchGraphql(e),a.instrument_logger.info("Patched GraphQL successfully"),e}patchGraphql(e){const t=e.execute;e.execute=function(e){!function(e){try{e&&!e[l.graphQLPatchedSymbol]&&(f(e._queryType),f(e._mutationType),e[l.graphQLPatchedSymbol]=!0,a.instrument_logger.info("Patched GraphQL schema successfully"))}catch(e){a.instrument_logger.error("Failed to patch GraphQL schema",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}(e.schema);const r=process.hrtime.bigint();return function(e,t,r){return"function"==typeof e.then?e.then(e=>(h(t,r),e)):(h(t,r),e)}(t.apply(this,arguments),e.document,r)},(0,c.copyPropertiesToTarget)(t,e.execute)}}function f(e){if(!e)return;const t=e._fields;Object.keys(t).forEach(r=>{const n=t[r];!function(e,t,r){if(e.resolve&&!e.resolve[l.graphQLPatchedSymbol]){const n=(0,i.generateGraphqlFlowId)(r,t);(0,s.storeResolverDeclaration)({id:n,operation:t,name:r});const o=e.resolve;e.resolve=(0,c.wrapFlow)(m,o,!0,(e,t)=>{const r=u.GraphQLMetric.createUsableMetric();r.start(),r.setFlowId(e),t.flowMetric=r},(e,t)=>{const r=t.flowMetric;r?r.end():a.instrument_logger.warn("No flowMetric found for resolver",{flowId:e})},(e,t)=>{const r=t.flowMetric;r?r.end():a.instrument_logger.warn("No flowMetric found for resolver",{flowId:e})}),e.resolve[l.graphQLPatchedSymbol]=!0,(0,s.storeResolverIdBySelectionName)(n,r)}}(n,o.GraphQLSupportedOperations[e.name.toLowerCase()],r),n.type._fields&&p(n.type)})}t.default=l;const g=new WeakSet;function p(e){e&&e._fields&&!g.has(e)&&(g.add(e),Object.keys(e._fields).forEach(t=>{const r=e._fields[t];if(!r||!r.type)return;!function(e){const t=e.resolve;t&&!e.resolve[l.graphQLPatchedSymbol]&&(e.resolve=(0,c.wrapFlow)(m,t,!0),e.resolve[l.graphQLPatchedSymbol]=!0)}(r);let n=r.type;for(;n.ofType;)n=n.ofType;p(n)}))}function m(e){if(void 0===e[2]||void 0===e[3])return void a.instrument_logger.warn("GraphQL resolver arguments are unknown");const t=e[3].path;if(t&&!t.prev){const r=t.key,n=(0,s.getResolverIdBySelectionName)(r);return e[2][l.graphQLPatchedSymbol]=n,n}if(e[2][l.graphQLPatchedSymbol])return e[2][l.graphQLPatchedSymbol];a.instrument_logger.warn("GraphQL No functionId found for resolver")}function h(e,t){try{new s.GraphQLDocumentMetadata(e,Number(process.hrtime.bigint()-t)).save()}catch(e){a.instrument_logger.error("Failed to save document metadata",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}},7225:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.skipStackNamesLogs=t.skipLayerNamesLogs=t.isVerboseLoggingEnabled=t.uuidSymbol=void 0,t.logLazyRouter=function(e){const r=e.lazyrouter;e.lazyrouter=function(){let e=!1;try{this._router||(e=!0)}catch(e){a.instrument_logger.error("Failed to check this._router",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}const n=r.apply(this,arguments);try{if(e){let e=this[t.uuidSymbol];e||(e=c.randomUUID(),this[t.uuidSymbol]=e,a.instrument_logger.info("Express lazy router setting uuid",{uuid:e})),a.instrument_logger.info("Express lazy router",{parent:e,child:this._router?.[t.uuidSymbol]})}}catch(e){a.instrument_logger.error("Failed to patch express.lazyRouter function",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return n},(0,d.copyPropertiesToTarget)(r,e.lazyrouter)};const a=r(523),c=i(r(6982)),u=r(932),d=r(8949);t.uuidSymbol=Symbol.for("__hud_uuid__"),t.isVerboseLoggingEnabled="true"===u.env.HUD_LOG_EXPRESS,t.skipLayerNamesLogs=new Set(["query","expressInit","mounted_app"]),t.skipStackNamesLogs=new Set(["router"])},7246:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(2546),o=r(523),s=r(8949),i=r(714);class a extends i.FrameworkPatcher{static originalRequestSymbol=Symbol.for("hudOriginalRequest");static hudPatched=Symbol.for("hudPatched");_patch(e){try{if((0,n.setIsNextJsApp)(!0),!e.NextRequestAdapter)return o.instrument_logger.error("Could not find NextRequestAdapter in exports"),e;const t=e.NextRequestAdapter;if(t[a.hudPatched])return o.instrument_logger.debug("NextRequestAdapter already patched"),e;const r=t.fromNodeNextRequest;if(!r)return o.instrument_logger.error("Could not find NextRequestAdapter.fromNodeNextRequest"),e;t.fromNodeNextRequest=function(...e){const t=r.apply(this,e);try{t[a.originalRequestSymbol]=e[0]._req}catch(e){o.instrument_logger.error("Failed to patch NextRequestAdapter",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t},(0,s.copyPropertiesToTarget)(r,t.fromNodeNextRequest),t[a.hudPatched]=!0,o.instrument_logger.info("Successfully patched NextRequestAdapter.fromNodeNextRequest")}catch(e){o.instrument_logger.error("Failed to patch NextRequestAdapter",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return e}}t.default=a},7603:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getObservabilityIdentifiers=function(e){const t=l();return{datadog_trace_id:t?.trace_id,datadog_span_id:t?.span_id,otel_trace_id:g(),w3c_trace_context:i(e),w3c_baggage:c(e,"baggage"),amazon_trace_id:c(e,"x-amzn-trace-id"),b3_propagation:a(e),jaeger_trace_id:c(e,"uber-trace-id")}},t.getExtraHeaders=function(e){const t={};for(const r of n.hudConfig.dynamicConfig.extraHeaders){const n=c(e,r);void 0!==n&&(t[r]=n)}return t},t.getDatadogIds=l,t.getOtelTraceId=g;const n=r(5809),o=r(2546),s=r(523);function i(e){try{return{traceparent:c(e,"traceparent"),tracestate:c(e,"tracestate")}}catch{return}}function a(e){try{return{full:c(e,"b3"),trace_id:c(e,"x-b3-traceid"),span_id:c(e,"x-b3-spanid"),parent_span_id:c(e,"x-b3-parentspanid")}}catch{return}}function c(e,t){try{return e.headers[t]}catch{return}}function u(e){let t;return()=>(void 0===t&&(t=function(e){try{const t=o.myRequire.resolve(e),r=o.myRequire.cache[t];return void 0===r?(s.instrument_logger.info("requireFromCache: codeModule is undefined",{path:e,fullPath:t}),null):"object"!=typeof r.exports?(s.instrument_logger.warn("requireFromCache: codeModule.exports is not an object",{path:e}),null):r.exports}catch(t){return s.instrument_logger.warn("requireFromCache: error",{path:e,error:t}),null}}(e)),t)}const d=u("dd-trace/packages/datadog-core");function l(){try{const e=d();if(null===e)return;const{storage:t}=e,r=t("legacy").getStore();return{trace_id:r.span._spanContext.toTraceId(),span_id:r.span._spanContext.toSpanId()}}catch{return}}const f=u("@opentelemetry/api");function g(){try{const e=f();if(null===e)return;const{trace:t}=e;return t.getActiveSpan()?.spanContext().traceId}catch{return}}},7808:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getMachineMetrics=function(){try{const e=(0,o.getLastMetrics)();return{cpu_usage:e.cpuUsage?l(e.cpuUsage,e.timestamp):void 0,memory_usage:d(),event_loop_utilization:e.elu?u(e.elu):void 0}}catch(e){return void i.app_logger.error("Error getting machine metrics",e)}},t.getCpuUsage=l;const o=r(8269),s=r(2546),i=r(523),a=n(r(857)),c=r(2987);function u(e){try{return c.performance.eventLoopUtilization(e).utilization}catch(e){return void i.app_logger.error("Error getting event loop utilization",e)}}function d(){try{const e=process.memoryUsage(),t=a.default.totalmem();return{rss:e.rss,heap_total:e.heapTotal,heap_used:e.heapUsed,external:e.external,system_memory:t,rss_percentage:e.rss/t*100}}catch(e){return void i.app_logger.error("Error getting memory usage",e)}}function l(e,t){try{const r=process.cpuUsage(),n=1e3*(Date.now()-t),o=(0,s.getCpuLimit)(i.app_logger),a=(r.user-e.user)/n,c=(r.system-e.system)/n;return{user_time:a,system_time:c,limit:o,user_percent_of_limit:"number"==typeof o?a/o*100:void 0,system_percent_of_limit:"number"==typeof o?c/o*100:void 0}}catch(e){return void i.app_logger.error("Error getting cpu usage",e)}}},8064:e=>{"use strict";e.exports=require("semver")},8269:e=>{"use strict";e.exports=require("./globalstate")},8528:e=>{"use strict";e.exports=require("./dto")},8611:e=>{"use strict";e.exports=require("http")},8901:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HttpEndpointMetric=void 0;const n=r(9873);class o extends n.FlowMetric{statusCode;route;method;constructor(e){super(e)}_createUsableMetric(e){return this}setRequestAttributes(e){const t=e.url||e.path;this.route=t?.split("?")[0],this.method=e.method}setResponseAttributes(e){this.statusCode=e.statusCode}toRaw(){if(this.statusCode&&this.route&&this.method)return{flow_id:this.flowId,type:"EndpointMetric",duration:this.duration,status_code:this.statusCode,route:this.route,method:this.method}}}t.HttpEndpointMetric=o},8949:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AsyncFunction=void 0,t.wrapFlow=function(e,r,c=!0,u,d,l){let f;if(r[i])return r;const g=(0,s.getFlowStateStorage)();return g?(r[i]=!0,f=r instanceof t.AsyncFunction?async function(...t){let s;try{s=e(t)}catch(e){o.instrument_logger.error("Failed to get flowId",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}if(!s||hudRunningMode!==n.HudRunningMode.enabled)return await r.apply(this,t);const i={};if(u)try{u(s,i,t)}catch(e){o.instrument_logger.error("Failed to execute beforeCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const e=g.run({flowId:s,shouldLinkFunction:c},Reflect.apply,r,this,t),n=await e;if(d)try{d(s,i)}catch(e){o.instrument_logger.error("Failed to execute afterCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return n}catch(e){if(l)try{l(s,i,e)}catch(e){o.instrument_logger.error("Failed to execute catchCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}throw e}}:function(...t){let s;try{s=e(t)}catch(e){o.instrument_logger.error("Failed to get flowId",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}if(!s||hudRunningMode!==n.HudRunningMode.enabled)return r.apply(this,t);const i={};if(u)try{u(s,i,t)}catch(e){o.instrument_logger.error("Failed to execute beforeCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const e=g.run({flowId:s,shouldLinkFunction:c},Reflect.apply,r,this,t);if(d)if(e instanceof Promise)e.then(()=>{try{d(s,i)}catch(e){o.instrument_logger.error("Failed to execute afterCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}});else try{d(s,i)}catch(e){o.instrument_logger.error("Failed to execute afterCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return e}catch(e){if(l)try{l(s,i,e)}catch(e){o.instrument_logger.error("Failed to execute catchCallbackHook",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}throw e}},a(r,f),f):r},t.copyPropertiesToTarget=a;const n=r(8528),o=r(523),s=r(7131);t.AsyncFunction=(async()=>{}).constructor;const i=Symbol.for("hudMarked");function a(e,t){const r=Object.getOwnPropertyDescriptors(e),n=Reflect.ownKeys(r);Object.setPrototypeOf(t,e),n.forEach(e=>{try{Object.defineProperty(t,e,r[e])}catch{}})}},9063:e=>{"use strict";e.exports=require("require-in-the-middle")},9589:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(8528),s=r(8269),i=r(2546),a=r(523),c=r(8949),u=r(714),d=r(5459),l=n(r(7246));class f extends u.FrameworkPatcher{static nextJSHudMarked=Symbol.for("hudNextJSMarked");static routeInfoSymbol=Symbol.for("hudNextJSRouteInfo");static standardMethods=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];_patch(e){return(0,i.setIsNextJsApp)(!0),this._patchBaseServer(e),a.instrument_logger.info("Patched Next.js successfully"),e}_patchBaseServer(e){try{const t=e.default;if(t[f.nextJSHudMarked])return e;const r=t.prototype.renderToResponseWithComponentsImpl;if(!r)return a.instrument_logger.error("Could not find renderToResponseWithComponentsImpl on BaseServer.prototype"),e;t.prototype.renderToResponseWithComponentsImpl=async function(e,t,...n){try{const r=t.components;if(r&&r.routeModule&&!r.routeModule[f.nextJSHudMarked]){const t=r.routeModule,n=t.definition?.pathname||e.pathname;f._detectAndPatchSupportedMethods(t,n),t[f.nextJSHudMarked]=!0}}catch(e){a.instrument_logger.error("Failed to patch Next.js route module",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return await r.apply(this,[e,t,...n])},t[f.nextJSHudMarked]=!0,(0,c.copyPropertiesToTarget)(r,t.prototype.renderToResponseWithComponentsImpl)}catch(e){a.instrument_logger.error("Failed to patch Next.js base server",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return e}static _detectAndPatchSupportedMethods(e,t){try{switch(a.instrument_logger.debug("Patching Next.js route module",{pathname:t,kind:e.definition?.kind||"unknown"}),e.definition.kind){case"APP_ROUTE":case"PAGES_API":f._patchApiModule(e,t);break;case"PAGES":case"APP_PAGE":f._patchPageModule(e,t);break;default:a.instrument_logger.warn("Unknown Next.js route module kind",{pathname:t,kind:e.definition?.kind||"unknown"})}}catch(e){a.instrument_logger.error("Error detecting and patching supported methods",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}static _patchApiModule(e,t){if(e.methods)for(const r of f.standardMethods)if("function"==typeof e.methods[r]&&"function"==typeof e.userland?.[r]){const n=(0,i.generateEndpointFlowId)(t,[r]);(0,s.storeEndpointDeclaration)(new o.EndpointDeclaration(n,[r],"nextjs","",t));try{const t=e.methods[r];e.methods[r]=(0,c.wrapFlow)(()=>n,t,!0,(e,t,r)=>{m(r[0],e)})}catch(e){a.instrument_logger.error("Failed to patch Next.js App Route method",{method:r,pathname:t,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}if(e.userland?.default){const r=f.standardMethods.filter(t=>!e.methods?.[t]),n=(0,i.generateEndpointFlowId)(t,r);(0,s.storeEndpointDeclaration)(new o.EndpointDeclaration(n,r,"nextjs","",t));const a=e.userland.default;e.userland={...e.userland,default:(0,c.wrapFlow)(()=>n,a,!0)}}}static _patchPageModule(e,t){const r=(0,i.generateEndpointFlowId)(t,["GET"]);if((0,s.storeEndpointDeclaration)(new o.EndpointDeclaration(r,["GET"],"nextjs","",t)),e.render&&"function"==typeof e.render&&!e.render[this.nextJSHudMarked])try{const t=e.render;e.render=function(...e){try{m(e[0],r)}catch{}return t.apply(this,e)},(0,c.copyPropertiesToTarget)(t,e.render),e.render[this.nextJSHudMarked]=!0}catch(e){a.instrument_logger.error("Failed to patch Next.js Page render method",{pathname:t,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}if(e.userland?.loaderTree)try{p(e.userland.loaderTree,r)}catch(e){a.instrument_logger.error("Failed to patch App Router page component",{pathname:t,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}else a.instrument_logger.warn("No loader tree found on Next.js page component",{pathname:t})}}function g(e,t,r){return(...n)=>{const o=e(...n),s=e=>{if(e&&"function"==typeof e.default&&!e.default[f.nextJSHudMarked]){const n=(0,c.wrapFlow)(()=>r,e.default,t);(e={...e,default:n})[f.nextJSHudMarked]=!0}return e};return o&&"function"==typeof o.then?o.then(s):s(o)}}function p(e,t){const[,r,n]=e;for(const e of Object.keys(n))try{const r=n[e];if(Array.isArray(r)&&"function"==typeof r[0]){const n="page"===e,o=r[0];r[0]=g(o,n,t),(0,c.copyPropertiesToTarget)(o,r[0])}}catch(e){a.instrument_logger.error("Failed to iterate on Next.js components",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}for(const e of Object.values(r))try{p(e,t)}catch(e){a.instrument_logger.error("Failed to walk on Next.js parallel routes",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}function m(e,t){try{let r;if(e&&l.default.originalRequestSymbol in e){const t=e[l.default.originalRequestSymbol];r=(0,d.getHttpMetricFromRequest)(t)}else e&&e.originalRequest&&(r=(0,d.getHttpMetricFromRequest)(e.originalRequest));if(r||(r=(0,d.getHttpMetricFromRequest)(e)),!r)return void a.instrument_logger.error("No endpoint metric found on Next.js request or its original request");r.setFlowId(t)}catch(e){a.instrument_logger.error("Failed to link metric to flow",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}t.default=f},9723:function(e,t,r){"use strict";var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=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 r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=r(8269),c=r(2546),u=r(523),d=r(9896),l=i(r(6928)),f=r(8949),g=r(714);class p extends g.FrameworkPatcher{_patch(e){(0,c.setIsNextJsApp)(!0);const t=this._patchLoadConfig(e);return u.instrument_logger.info("Patched next.js config successfully"),t}_patchLoadConfig(e){const t=e.default,r=async function(...e){const r=await t.call(this,...e);if(!r)return r;try{const t=e[1],n=l.join(t,r.distDir||".next"),o=l.join(n,a.apiManifest),s=l.join(n,a.pageManifest),i=await d.promises.access(o).then(()=>!0).catch(()=>!1),c=await d.promises.access(s).then(()=>!0).catch(()=>!1);(0,a.isNextConfigExtracted)()||!i&&!c||(u.instrument_logger.info("Extracted next.js config successfully"),(0,a.setNextConfig)(r))}catch(e){u.instrument_logger.error("Failed to patch next.js loadConfig",{msg:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0})}return r};(0,f.copyPropertiesToTarget)(t,r);const n=Object.create(Object.getPrototypeOf(e));return Object.defineProperty(n,"default",{enumerable:!0,get:function(){return r}}),(0,f.copyPropertiesToTarget)(e,n),n}}t.default=p},9873:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FlowMetric=void 0;const o=r(8528),s=r(8269),i=n(r(932));t.FlowMetric=class{_state;flowId;duration;_startTime;_msStartTime;constructor(e){this.flowId=e,this.duration=0,this._state="usable"}static createUsableMetric(e){return new this(e)._createUsableMetric(e)}setFlowId(e){this.flowId=e}getFlowId(){return this.flowId}getMsStartTime(){return this._msStartTime}start(){this._startTime=i.default.hrtime.bigint(),this._msStartTime=Date.now()}end(){this._startTime&&(this.duration=Number(i.default.hrtime.bigint()-this._startTime)),this.#e(),this._state="unusable"}#e(){if(hudRunningMode===o.HudRunningMode.enabled){const e=this.toRaw();e&&(0,s.storeFlowMetric)(e)}}}},9896:e=>{"use strict";e.exports=require("fs")}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,r),s.exports}return r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r(2197)})());
2
2
  //# sourceMappingURL=instrument.js.map
package/dist/cjs/lib.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,r){if("object"==typeof exports&&"object"==typeof module)module.exports=r();else if("function"==typeof define&&define.amd)define([],r);else{var o=r();for(var t in o)("object"==typeof exports?exports:e)[t]=o[t]}}(global,()=>(()=>{"use strict";var e={46:function(e,r,o){var t,n=this&&this.__createBinding||(Object.create?function(e,r,o,t){void 0===t&&(t=o);var n=Object.getOwnPropertyDescriptor(r,o);n&&!("get"in n?!r.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(e,t,n)}:function(e,r,o,t){void 0===t&&(t=o),e[t]=r[o]}),i=this&&this.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),s=this&&this.__importStar||(t=function(e){return t=Object.getOwnPropertyNames||function(e){var r=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[r.length]=o);return r},t(e)},function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var o=t(e),s=0;s<o.length;s++)"default"!==o[s]&&n(r,e,o[s]);return i(r,e),r});Object.defineProperty(r,"__esModule",{value:!0}),r.readFile=async function(e,r,o){try{if(r&&o){const t=Buffer.alloc(o-r),n=await u.promises.open(e,"r");return await n.read(t,0,o-r,r),await n.close(),t.toString("utf-8")}return await u.promises.readFile(e,"utf-8")}catch(r){return void a.worker_logger.error("Failed to read file",{filename:e,msg:r instanceof Error?r.message:r})}};const a=o(523),u=s(o(9896))},350:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.incrementInstrumentedFilesCount=function(){i++},r.setInstrumentedFilesCountInterval=function(){let e;return s||(n.instrument_logger.info("Setting interval for instrumented files count logging",{interval:t.hudConfig.logIntervals.instrumentedFilesCount}),e=setInterval(()=>{const e=a();e>0&&(n.instrument_logger.info("Successfully instrumented",{functionsCount:e}),u())},t.hudConfig.logIntervals.instrumentedFilesCount),e.unref(),s=!0),e},r.incrementSentEventsCount=function(e){l[e]=(l[e]||0)+1},r.resetSentEventsCount=c,r.getSentEventsCount=f,r.setSentEventsCountInterval=function(){let e;return d||(n.worker_logger.info("Setting interval for sent events count logging",{interval:t.hudConfig.logIntervals.sentEventsCount}),e=setInterval(()=>{const e=f();Object.keys(e).length>0&&(n.worker_logger.info("Successfully sent events",{sentEventsCount:e}),c())},t.hudConfig.logIntervals.sentEventsCount),e.unref(),d=!0),e};const t=o(5809),n=o(523);let i=0,s=!1;function a(){return i}function u(){i=0}let l={},d=!1;function c(){l={}}function f(){return l}},523:e=>{e.exports=require("./logger")},857:e=>{e.exports=require("os")},1176:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.getInstrumentedThirdPartyModuleInfo=function(e){const r=t.hudConfig.functionsToInstrument||[];for(const o of r)for(const r in o.fileToFunctionsMapping)if(e.endsWith(r))return{functions:o.fileToFunctionsMapping[r],moduleName:o.moduleName}};const t=o(5809)},1493:e=>{e.exports=require("v8")},1569:e=>{e.exports=require("zod")},2784:e=>{e.exports=require("../native/_index")},2987:e=>{e.exports=require("perf_hooks")},3305:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.updateUserConfigFromInit=function(e,r,o){if(void 0!==e&&(t.hudConfig.userConfig.key={value:e,source:"INIT"}),void 0!==r&&(t.hudConfig.userConfig.service={value:r,source:"INIT"}),void 0!==o){let e=o;const r=n.HudSessionOptionsSchema.safeParse(o);r.success?o.tags&&"object"==typeof o.tags&&Object.keys(o.tags).some(e=>e.includes("."))&&(i.customer_logger.log(a.UserErrorLogs.SessionOptionsSessionTagsWithDots()),e.tags=Object.fromEntries(Object.entries(o.tags).map(([e,r])=>[e.replace(".","_"),r]))):(i.customer_logger.log(a.UserErrorLogs.HudSessionOptionsInvalid(r.error.message)),e={}),t.hudConfig.userConfig.tags={value:e.tags,source:"INIT"}}},r.updateUserConfigFromFile=function(){let e;try{e=(0,t.getConfigContent)()}catch(e){throw e instanceof t.HudFailedReadConfigError&&"EACCES"===e.code&&i.customer_logger.log(a.UserErrorLogs.ConfigInaccessible(e.path)),e}if(e)try{const r=u.partial().parse(JSON.parse(e.content));Object.entries(r).forEach(([r,o])=>{!function(e,r,o){e[r]=o}(t.hudConfig.userConfig,r,{value:o,source:"HUD_CONFIG"===e.source?"CONFIG_ENV":"CONFIG_FILE"})})}catch(r){throw r instanceof s.ZodError?r.errors.forEach(r=>{const o=r.path.join(".");i.customer_logger.log(a.UserErrorLogs.ZodErrorInUserConfig(e.source,o))}):i.customer_logger.log(a.UserErrorLogs.JSONErrorInUserConfig(e.source,r.message)),r}},r.updateUserConfigFromEnv=function(){const e=process.env.HUD_KEY,r=process.env.HUD_SERVICE,o=process.env.HUD_ENABLE_DAPULSE,n=(0,t.getModulesToTraceFromEnv)(),i=(0,t.getFrameworksToEnableFromEnv)(),s=process.env.HUD_MAX_INSTRUMENTED_FUNCTIONS,a=process.env.HUD_MIN_POD_MEMORY_MB,u=process.env.HUD_DISABLE_RUNTIME_INSTRUMENTATION;e&&(t.hudConfig.userConfig.key={value:e,source:"ENV"}),r&&(t.hudConfig.userConfig.service={value:r,source:"ENV"}),o&&(t.hudConfig.userConfig.enableDapulse={value:"true"===o,source:"ENV"}),n&&(t.hudConfig.userConfig.includeModules={value:n,source:"ENV"}),i&&(t.hudConfig.userConfig.enableFrameworks={value:i,source:"ENV"}),s&&(t.hudConfig.userConfig.maxMappedFunctions={value:parseInt(s),source:"ENV"}),a&&(t.hudConfig.userConfig.minPodMemoryMB={value:parseInt(a),source:"ENV"}),u&&(t.hudConfig.userConfig.disableRuntimeInstrumentation={value:"true"===u,source:"ENV"})},r.updateUserConfigFromRegisterOptions=function(e,r){if(e.includeModules&&Array.isArray(e.includeModules)&&(t.hudConfig.userConfig.includeModules={value:e.includeModules,source:r}),e.enableFrameworks){const o=n.availableFrameworksSchema.safeParse(e.enableFrameworks);o.success&&(t.hudConfig.userConfig.enableFrameworks={value:o.data,source:r})}e.customOptions&&e.customOptions.dapulseSqsConsumer&&(t.hudConfig.userConfig.enableDapulse={value:"true"===e.customOptions.dapulseSqsConsumer,source:r}),e.maxMappedFunctions&&"number"==typeof e.maxMappedFunctions&&(t.hudConfig.userConfig.maxMappedFunctions={value:e.maxMappedFunctions,source:r}),e.minPodMemoryMB&&"number"==typeof e.minPodMemoryMB&&(t.hudConfig.userConfig.minPodMemoryMB={value:e.minPodMemoryMB,source:r}),e.maxFileSizeBytes&&"number"==typeof e.maxFileSizeBytes&&(t.hudConfig.userConfig.maxFileSizeBytes={value:e.maxFileSizeBytes,source:r}),e.maxTimeUntilInitSessionMs&&"number"==typeof e.maxTimeUntilInitSessionMs&&(t.hudConfig.userConfig.maxTimeUntilInitSessionMs={value:e.maxTimeUntilInitSessionMs,source:r}),void 0!==e.disableRuntimeInstrumentation&&(t.hudConfig.userConfig.disableRuntimeInstrumentation={value:e.disableRuntimeInstrumentation,source:r})};const t=o(5809),n=o(8528),i=o(523),s=o(1569),a=o(9499),u=n.HudOptionsSchema.omit({customOptions:!0}).extend(n.HudSessionOptionsSchema.shape).extend({key:s.z.string().optional(),service:s.z.string().optional(),enable:s.z.boolean().optional(),enableDapulse:s.z.boolean().optional()})},3596:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.safeCall=function(e,r){return r.catch(r=>{(0,t.isAbortError)(r)||e.error("Unhandled exception on async task",{msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0})})};const t=o(9499)},3705:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.isHudEnabled=function(){if("false"===process.env.HUD_ENABLE)return!1;if(globalThis.forceHudEnable)return!0;let e,r;try{if(e=(0,t.getConfigContent)(),e&&(r=JSON.parse(e.content),!1===r.enable))return!1}catch(r){throw r instanceof t.HudFailedReadConfigError&&"EACCES"===r.code?n.customer_logger.log(i.UserErrorLogs.ConfigInaccessible(r.path)):e&&n.customer_logger.log(i.UserErrorLogs.JSONErrorInUserConfig(e.source,r instanceof Error?r.message:void 0)),r}return"true"===process.env.HUD_ENABLE||!0===r?.enable};const t=o(5809),n=o(523),i=o(9499)},3903:e=>{e.exports=require("uuid")},4463:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.getFilesForDeclarations=async function(e,r){const o=new Map;for(const r of e)o.set(`${r.file_path_checksum}|${r.file_checksum}`,r);const n=Array.from(o.entries()).sort(([e],[r])=>e.localeCompare(r)).map(([,e])=>({file_path_checksum:e.file_path_checksum,file_checksum:e.file_checksum})),i=await r(n);if(i.send_all)return t.worker_logger.debug("All file declarations are requested by sink"),e;t.worker_logger.debug("Partial file declarations are requested by sink",{fileCount:i.files.length});const s=[];for(const e of i.files){const r=`${e.file_path_checksum}|${e.file_checksum}`,t=o.get(r);t&&s.push(t)}return s};const t=o(523)},5070:function(e,r,o){var t=this&&this.__createBinding||(Object.create?function(e,r,o,t){void 0===t&&(t=o);var n=Object.getOwnPropertyDescriptor(r,o);n&&!("get"in n?!r.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(e,t,n)}:function(e,r,o,t){void 0===t&&(t=o),e[t]=r[o]}),n=this&&this.__exportStar||function(e,r){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(r,o)||t(r,e,o)};Object.defineProperty(r,"__esModule",{value:!0}),n(o(9499),r),n(o(4463),r),n(o(9525),r),n(o(3705),r),n(o(350),r),n(o(5246),r),n(o(6287),r),n(o(9303),r),n(o(7146),r),n(o(1176),r),n(o(7511),r),n(o(46),r),n(o(5308),r),n(o(3596),r),n(o(5990),r),n(o(5706),r),n(o(5935),r),n(o(6548),r),n(o(6180),r),n(o(3305),r),n(o(7552),r),n(o(8236),r),n(o(8481),r)},5246:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.register=async function(){n.worker_logger.info("registering extension");const e=await fetch(`${s}/register`,{method:"post",body:JSON.stringify({events:["INVOKE"]}),headers:{"Content-Type":"application/json","Lambda-Extension-Name":"hud-extension"}});if(!e.ok)throw n.worker_logger.error("register failed",{status:e.status,statusText:e.statusText,body:await e.text(),baseUrl:s}),new i.HudExtensionRegisterError("register failed");const r=e.headers.get("lambda-extension-identifier");if(!r)throw new i.HudExtensionRegisterError("extension id not found");return r},r.next=u,r.extensionMainLoop=async function(e,r){let o=Date.now();for(n.worker_logger.info("starting extension main loop");;)try{const i=await u(e);if(r.listenerCount("eventloop")>0){const e=r.listenerCount("eventloop"),i=Date.now()-o;r.emit("eventloop",""),o=Date.now();const s=Math.min(t.hudConfig.lambdaBaseGivenTime+e*t.hudConfig.lambdaExtraGivenTimePerRequest,t.hudConfig.lambdaMaxGivenTime);n.worker_logger.debug(`Starting giving time for the eventloop to run at ${(new Date).toISOString()}. ${i}ms since last eventloop request. Given time: ${s}ms`),await new Promise(e=>setTimeout(e,s)),n.worker_logger.debug(`Done giving time for the eventloop to run ${(new Date).toISOString()}`)}if("SHUTDOWN"===i?.eventType)return void n.worker_logger.info("shutting down")}catch(e){e instanceof i.HudExtnensionError?n.worker_logger.warn("Extension tick failed, continuing",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}):n.worker_logger.error("Extension tick failed with unexpected error, continuing",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0});continue}},r.nextLoopDummy=async function(e){for(;;)try{(await a(e)).ok||await new Promise(e=>setTimeout(e,50))}catch{await new Promise(e=>setTimeout(e,50))}};const t=o(5809),n=o(523),i=o(9499),s=`http://${process.env.AWS_LAMBDA_RUNTIME_API}/2020-01-01/extension`;async function a(e){return await fetch(`${s}/event/next`,{method:"get",headers:{"Content-Type":"application/json","Lambda-Extension-Identifier":e}})}async function u(e){const r=await a(e);if(!r.ok)throw n.worker_logger.info("next failed",await r.text()),new i.HudExtensionNextFailedError;return await r.json()}},5308:function(e,r,o){var t,n=this&&this.__createBinding||(Object.create?function(e,r,o,t){void 0===t&&(t=o);var n=Object.getOwnPropertyDescriptor(r,o);n&&!("get"in n?!r.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(e,t,n)}:function(e,r,o,t){void 0===t&&(t=o),e[t]=r[o]}),i=this&&this.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),s=this&&this.__importStar||(t=function(e){return t=Object.getOwnPropertyNames||function(e){var r=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[r.length]=o);return r},t(e)},function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var o=t(e),s=0;s<o.length;s++)"default"!==o[s]&&n(r,e,o[s]);return i(r,e),r});Object.defineProperty(r,"__esModule",{value:!0}),r.isDebuggerAttached=g,r.isSupportedNative=v,r.shouldRunHud=function(){return"false"===process.env.HUD_ENABLE?{shouldRun:!1,error:c.UserErrorLogs.HudEnableIsFalse()}:d.isMainThread?(0,m.isHudEnabled)()?process.versions.bun?{shouldRun:!1,error:c.UserErrorLogs.RunningInBun()}:function(){const e=process.versions.node.split(".")[0];return!!a.hudConfig.supportedNodeVersions.includes(e)}()?process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE&&!function(){try{return"1"===process.env.HUD_INTERNAL_EXEC_WRAPPER_USED}catch{return!1}}()?{shouldRun:!1,error:c.UserErrorLogs.LambdaNotViaLayer()}:g()?{shouldRun:!1,error:c.UserErrorLogs.DebuggerAttached()}:function(){const e=(0,f.getMemoryLimitInfo)();return!!(0,f.isMemoryLimitBigEnough)(e)}()?v()?(0,p.isNextJs)("dev")?{shouldRun:!1,error:c.UserErrorLogs.NextDevNotSupported()}:{shouldRun:!0}:{shouldRun:!1,error:c.UserErrorLogs.UnsupportedNativeBuild()}:{shouldRun:!1,error:c.UserErrorLogs.PodMemoryLimitTooLow(a.hudConfig.userConfig.minPodMemoryMB?.value??Number.MAX_SAFE_INTEGER)}:{shouldRun:!1,error:c.UserErrorLogs.UnsupportedNodeVersion()}:{shouldRun:!1,error:c.UserErrorLogs.HudEnableNotSet(process.env.HUD_ENABLE)}:(u.app_logger.info("required not from main thread"),{shouldRun:!1,error:null})};const a=o(5809),u=o(523),l=s(o(6592)),d=o(5919),c=o(9499),f=o(8958),m=o(3705),p=o(7146);function g(){if("true"===process.env.HUD_ALLOW_DEBUGGER)return!1;if(process.execArgv.some(e=>e.includes("--inspect")||e.includes("--debug")||e.includes("--inspect-brk")||e.includes("--debug-brk")))return!0;try{return"string"==typeof l.url()}catch{return!1}}function v(){return void 0!==o(2784).transform}},5706:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.shouldSupportSourceMap=function(){return!!t.hudConfig.supportSourceMap&&(process.execArgv.includes("--enable-source-maps")&&n.instrument_logger.warn("--enable-source-maps is set, enabling custom source-map-support anyway"),!0)},r.combineSourceMaps=function(e,r){if(0===e.length)return;if(1===e.length&&void 0===e[0].lineOffset)return e[0].map;const o=e.map(e=>({offset:{line:e.transformedLineOffset,column:e.transformedColumnOffset},map:{..."string"==typeof e.map?JSON.parse(e.map):e.map,file:r}})),t={version:3,file:r,sections:o};return JSON.stringify(t)},r.appendInlineSourceMap=function(e,r){let o;return void 0===r?e:(o="string"==typeof r||r instanceof String?Buffer.from(r.toString()).toString("base64"):Buffer.from(JSON.stringify(r)).toString("base64"),e+`\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${o}`)};const t=o(5809),n=o(523)},5809:e=>{e.exports=require("./config")},5919:e=>{e.exports=require("node:worker_threads")},5935:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.suppressTraces=function(e){return function(...r){return t.hudConfig.suppressTraces&&s&&a?(n.app_logger.debug("Running with Suppressed traces"),s.with(a(s.active()),()=>e(...r))):e(...r)}};const t=o(5809),n=o(523),i=o(8481);let s,a;try{const e=(0,i.myRequire)("@opentelemetry/api"),r=(0,i.myRequire)("@opentelemetry/core");s=e.context,a=r.suppressTracing,n.app_logger.info("OpenTelemetry exists",{suppressConfig:t.hudConfig.suppressTraces})}catch{n.app_logger.info("OpenTelemetry api/core does not exist")}},5990:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.sourceFileMetadataToTransferSourceFileMetadata=function(e){return(0,t.omit)(e,"code","map","mapRelativeToChunk")};const t=o(6287)},6180:function(e,r,o){var t,n=this&&this.__createBinding||(Object.create?function(e,r,o,t){void 0===t&&(t=o);var n=Object.getOwnPropertyDescriptor(r,o);n&&!("get"in n?!r.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(e,t,n)}:function(e,r,o,t){void 0===t&&(t=o),e[t]=r[o]}),i=this&&this.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),s=this&&this.__importStar||(t=function(e){return t=Object.getOwnPropertyNames||function(e){var r=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[r.length]=o);return r},t(e)},function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var o=t(e),s=0;s<o.length;s++)"default"!==o[s]&&n(r,e,o[s]);return i(r,e),r});Object.defineProperty(r,"__esModule",{value:!0}),r.unrefSetImmediate=function(e,r){return a.setImmediate(e,{...r,ref:!1})},r.unrefSetTimeout=function(e,r,o){return a.setTimeout(e,r,{...o,ref:!1})},r.unrefSetInterval=function(e,r,o){return a.setInterval(e,r,{...o,ref:!1})};const a=s(o(6460))},6287:(e,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.omit=function(e,...r){const o={...e};return r.forEach(function(e){delete o[e]}),o},r.omitDeep=function e(r,o){const t=o.map(e=>e.split("."));if(null==r||"object"!=typeof r)return r;if(Array.isArray(r))return r.map(r=>e(r,o));const n={...r};for(const r of t){if(0===r.length)continue;const o=r[0];o in n&&(1!==r.length?n[o]=e(n[o],[r.slice(1).join(".")]):delete n[o])}return n},r.pickDeep=function e(r,o){if(Array.isArray(r))return r.map(r=>e(r,o));if("object"!=typeof r||null===r)return r;const t={},n={};for(const e of o){const[r,...o]=e.split(".");n[r]=n[r]??[],o.length>0&&"pick"!==n[r]?n[r].push(o.join(".")):n[r]="pick"}for(const o in n){if(!(o in r))continue;const i=r[o];"pick"===n[o]?t[o]=i:Array.isArray(i)?t[o]=i.map(r=>"object"==typeof r&&null!==r?e(r,n[o]):{}):"object"==typeof i&&null!==i&&(t[o]=e(i,n[o]))}return t}},6460:e=>{e.exports=require("timers/promises")},6548:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.getUserTsNodeConfig=function(e=!0){const r=function(){try{const e=i.myRequire.resolve("ts-node");if(!e)return;if(!i.myRequire.cache[e])return;const r=(0,i.myRequire)("ts-node"),o=process[r.REGISTER_INSTANCE];if(!o)return;return o.options}catch{return}}();if(r){if(!r.transpileOnly)throw e&&t.customer_logger.log(n.UserErrorLogs.TsNodeNotTranspileOnly()),t.app_logger.warn("ts-node is used but not configured to transpile only"),new n.HudNoTranspileOnlyError;return{cwd:r.cwd,project:r.project,projectSearchDir:r.projectSearchDir}}if(process.argv[0].endsWith("ts-node"))throw e&&t.customer_logger.log(n.UserErrorLogs.TsNodeNotFoundEvenThoughRunWithTsNode()),t.app_logger.info("ts-node not found even run with ts-node"),new n.HudTsNodeNotFoundButUsed};const t=o(523),n=o(9499),i=o(8481)},6592:e=>{e.exports=require("node:inspector")},7146:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.detectNextJsApp=function(){const e=a("start");l(e),e&&n.app_logger.info("Detected Next.js application running with 'next start' command")},r.isNextJs=a,r.isNextJsApp=function(){return s},r.setIsNextJsApp=l;const t=o(5809),n=o(523),i=o(9499);let s=!1;function a(e){return!(!process.argv.some(e=>"next"===e)&&!process.argv.some(e=>e.includes("/dist/bin/next"))||!process.argv.some(r=>r===e))||!("dev"!==e||!process.argv.some(e=>e.includes("/next/dist/server/lib/start-server")))}let u=!1;function l(e){s=e,e&&!u&&(u=!0,globalThis.hudNextJsPluginIndicator=setTimeout(d,t.hudConfig.timeoutOnNextJsPlugin),globalThis.hudNextJsPluginIndicator.unref())}function d(){n.customer_logger.log(i.UserErrorLogs.NextJsPluginNotUsed())}},7511:function(e,r,o){var t,n=this&&this.__createBinding||(Object.create?function(e,r,o,t){void 0===t&&(t=o);var n=Object.getOwnPropertyDescriptor(r,o);n&&!("get"in n?!r.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(e,t,n)}:function(e,r,o,t){void 0===t&&(t=o),e[t]=r[o]}),i=this&&this.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),s=this&&this.__importStar||(t=function(e){return t=Object.getOwnPropertyNames||function(e){var r=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[r.length]=o);return r},t(e)},function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var o=t(e),s=0;s<o.length;s++)"default"!==o[s]&&n(r,e,o[s]);return i(r,e),r}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.getCpuLimit=void 0,r.loopLogThreadPerformance=async function(e,r,o){let t=d.performance.eventLoopUtilization(),n=d.performance.nodeTiming.toJSON();for await(const i of(0,m.unrefSetInterval)(r,void 0,{signal:o}))try{const r=d.performance.eventLoopUtilization(),o=d.performance.eventLoopUtilization(r,t);t=r;const i=c.getHeapStatistics(),s=d.performance.nodeTiming.toJSON(),a=s.idleTime-n.idleTime,u=s.duration-n.duration,l=a/u;n=s,e.info("thread performance statistics",{thread_elu_percentage:100*o.utilization,memory:{thread_heap_utilization_percentage:i.total_heap_size/i.heap_size_limit*100},idleTime:a,totalTime:u,idleTimePercentage:l})}catch(r){e.error("Failed logging thread performance statistics",{msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0})}},r.getCpuLimitUnsafe=p,r.loopLogProcessPerformance=async function(e,o,t){const n=l.default.totalmem(),i=(0,r.getCpuLimit)(e);let s=process.cpuUsage();for await(const r of(0,m.unrefSetInterval)(o,void 0,{signal:t}))try{const r=process.memoryUsage(),t=process.uptime(),a=process.cpuUsage(),u={user:a.user-s.user,system:a.system-s.system};s=a;let l=(u.user+u.system)/(1e3*o);i&&"number"==typeof i&&(l/=i),e.info("process performance statistics",{memory:{process_memory_rss:r.rss,process_memory_utilization_percentage:r.rss/n*100},cpu:100*l,cpuStats:{limit:i,usagePercentage:100*l},uptime:t})}catch(r){e.error("Failed logging process performance statistics",{msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0})}};const u=o(9896),l=a(o(857)),d=o(2987),c=s(o(1493)),f=o(5935),m=o(6180);function p(e){e.info("Trying to detect CPU limit");try{const r=(0,u.readFileSync)("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8"),o=(0,u.readFileSync)("/sys/fs/cgroup/cpu/cpu.cfs_period_us","utf8");return e.info("CPU limit detected for cgroups v1",{cpuQuota:r,cpuPeriod:o}),"-1"===r.toString().trim()?"unlimited":parseInt(r.toString())/parseInt(o.toString())}catch(r){try{const r=(0,u.readFileSync)("/sys/fs/cgroup/cpu.max","utf8"),[o,t,n]=r.trim().split(" ");return e.info("CPU limit detected for cgroups v2",{max:o,period:t}),o&&t?"max"===o?"unlimited":parseInt(o)/parseInt(t):void e.info("cpu.max file is not in the expected format",r)}catch(o){return void e.info("Failed to detect CPU limit",{e:r,e2:o})}}}let g,v=!1;r.getCpuLimit=e=>(v||(g=(0,f.suppressTraces)(p)(e),v=!0),g)},7552:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.HudContextValidationError=void 0,r.validateContext=function(e){try{const r={};for(const o in e){if(Object.keys(r).length>=20){u(n.UserErrorLogs.SetContextMaxKeysExceeded());break}if("string"==typeof o)if(o.length>64)u(n.UserErrorLogs.SetContextKeyTooLong(o));else{if(Array.isArray(e[o])){if(0===e[o].length){u(n.UserErrorLogs.SetContextEmptyArray(o));continue}const t=e[o],i=[];for(let e=0;e<t.length;e++){const r=t[e];if(i.length>=20){u(n.UserErrorLogs.SetContextArrayTooLong(o));break}l(r,o,!0)&&i.push(r)}if(0===i.length){u(n.UserErrorLogs.SetContextArrayAllItemsInvalid(o));continue}r[o]=i;continue}l(e[o],o)&&(r[o]=e[o])}else u(n.UserErrorLogs.SetContextKeyIsNotString(o))}return r}catch(e){throw t.app_logger.error("Failed to validate context",{error:e,stack:e instanceof Error&&null!==e?e.stack:void 0}),new a("Failed to validate context")}};const t=o(523),n=o(9499),i=new Set;let s=20;class a extends Error{}function u(e){s<=0||i.has(e.errCode)||(s--,t.app_logger.info(e.message),t.customer_logger.info(e.message),i.add(e.errCode))}function l(e,r,o=!1){const t=o?`item in array "${r}"`:`"${r}"`;return null==e?(u(n.UserErrorLogs.SetContextValueIsUndefinedOrNull(t)),!1):"object"==typeof e||"function"==typeof e?(u(n.UserErrorLogs.SetContextValueIsNotPrimitive(t)),!1):"string"==typeof e&&e.length>256?(u(n.UserErrorLogs.SetContextValueIsTooLong(t)),!1):""===e?(u(n.UserErrorLogs.SetContextValueIsEmptyString(t)),!1):!(e===1/0||e===-1/0||"number"==typeof e&&isNaN(e))||(u(n.UserErrorLogs.SetContextValueIsNotFiniteNumber(t)),!1)}r.HudContextValidationError=a},8236:(e,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.UserLogs=void 0,r.UserLogs={HudInitSuccess:()=>({level:"info",message:"Session started"}),FirstDecalarationSent:()=>({level:"info",message:"First code mapping sent successfully"}),FirstInvocationSent:()=>({level:"info",message:"First invocation sent successfully"}),HappyFlowCompleted:()=>({level:"info",message:"Your service is sending data successfully"}),FilesLoadedBeforeRegister:()=>({level:"info",message:"Files loaded before register():"}),FileBeforeRegisterTemplate:(e,r)=>({level:"info",message:`${e}. ${r}`}),InitIdleMode:()=>({level:"info",message:"Initialized successfully in idle mode."}),WebpackUploadedSourcemapSuccess:()=>({level:"info",message:"Source maps uploaded successfully."}),HudCliCompletedSuccessfully:e=>({level:"info",message:`Instrumentation completed successfully. ${e} files processed.`})}},8481:(e,r)=>{let o;Object.defineProperty(r,"__esModule",{value:!0}),r.myRequire=void 0;try{o=require}catch{o=void 0}r.myRequire=o},8528:e=>{e.exports=require("./dto")},8958:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.getMemoryLimitInfo=function(){const e=(0,i.getPodMemoryLimit)(n.app_logger);return n.app_logger.info(`Pod memory limit: ${null===e.podMemoryLimitMB?"unknown":e.podMemoryLimitMB+"MB"} from ${e.source}, minimum required: ${t.hudConfig.userConfig.minPodMemoryMB?.value??Number.MAX_SAFE_INTEGER}MB`),e},r.isMemoryLimitBigEnough=function(e){return null===e.podMemoryLimitMB||e.podMemoryLimitMB>=(t.hudConfig.userConfig.minPodMemoryMB?.value??Number.MAX_SAFE_INTEGER)};const t=o(5809),n=o(523),i=o(9303)},9303:function(e,r,o){var t=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.getPodMemoryLimit=function(e){if(null!==s)return s;if("linux"!==i.default.platform())return s=d(),s;let r=function(e,r){for(const e of["/sys/fs/cgroup/memory.max","/sys/fs/cgroup/memory.high"]){const o=l(e);if(!o)continue;const t=o.trim();if("max"===t){r.debug(`Found 'max' value in ${e}, will use system memory instead`);continue}const n=a(t,r);if(null!==n)return{podMemoryLimitMB:n,source:e}}return{podMemoryLimitMB:null,source:null}}(0,e);return null!==r.podMemoryLimitMB?(e.info(`Found pod memory limit: ${r.podMemoryLimitMB}MB from ${r.source}`),r):(r=function(e,r){for(const e of["/sys/fs/cgroup/memory/memory.stat","/sys/fs/cgroup/memory/memory.limit_in_bytes"]){const o=l(e);if(o)if(e.endsWith("memory.stat")){const t=["hierarchical_memory_limit","memory.limit_in_bytes","limit_in_bytes"],n=o.split("\n");for(const o of t){const t=n.find(e=>e.startsWith(o));if(t){const n=u(t.split(" ")[1],`${e}:${o}`,r);if(null!==n.podMemoryLimitMB)return n}}}else{const t=u(o.trim(),e,r);if(null!==t.podMemoryLimitMB)return t}}return{podMemoryLimitMB:null,source:null}}(0,e),null!==r.podMemoryLimitMB?(e.info(`Found pod memory limit: ${r.podMemoryLimitMB}MB from ${r.source}`),r):(r=d(),e.info(`No container memory limit found, using system memory: ${r.podMemoryLimitMB}MB`),s=r,r))};const n=o(9896),i=t(o(857));let s=null;function a(e,r){const o=parseInt(e);if(isNaN(o))return null;const t=Math.floor(o/1048576);return t<=0||t>=131072?(r.debug(`Treating memory value (${e} bytes) as unlimited.`),null):t}function u(e,r,o){if(!e)return{podMemoryLimitMB:null,source:null};const t=a(e,o);return null!==t?{podMemoryLimitMB:t,source:r}:{podMemoryLimitMB:null,source:null}}function l(e){try{return(0,n.readFileSync)(e,"utf8")}catch{return null}}function d(){const e=i.default.totalmem();return{podMemoryLimitMB:Math.floor(e/1048576),source:"system-memory"}}},9499:(e,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.UserErrorLogs=r.HudNoMessageInSqsConsumerEmit=r.HudNoErrorInSqsConsumerEmit=r.HudNoEventTypeInSqsConsumerEmit=r.HudFailExtractSqsQueueName=r.HudNoCallbackInSqsConsumerOn=r.HudNoEventTypeInSqsConsumerOn=r.HudNoQueueUrlInSqsConsumer=r.HudSqsError=r.HudExtensionNextFailedError=r.HudExtensionRegisterError=r.HudExtnensionError=r.HudBadLoggerError=r.HudInitNetworkError=r.HudTsNodeNotFoundButUsed=r.HudSessionThrottle=r.HudNoTranspileOnlyError=r.HudClientExceededMaxRetries=r.HudClientUnauthorizedError=r.HudTimeoutError=r.HudWorkloadCollectorError=r.HudAssert=r.HudUnsupportedError=r.HudEditError=r.HudWorkerError=r.HudClientError=r.HudInitError=r.HudError=void 0,r.isAbortError=function(e){return e instanceof Error&&"AbortError"===e.name},r.getFirstError=function(){return u},r.setFirstError=function(e){e&&u===a&&(u=e)},r.getNetworkError=function(e){return{ECONNABORTED:r.UserErrorLogs.InitFailedDueNetworkTimeout(),ECONNREFUSED:r.UserErrorLogs.InitFailedDueNetworkRST(),ENOTFOUND:r.UserErrorLogs.InitFailedDueDnsFailed(),SELF_SIGNED_CERT_IN_CHAIN:r.UserErrorLogs.InitFailedDueSelfSignedCert(),ERR_BAD_RESPONSE:r.UserErrorLogs.InitFailedDueBackendError()}[e]??r.UserErrorLogs.InitFailedDueGenericNetworkError()};class o extends Error{code=9e3;name=this.constructor.name;constructor(e){super(e)}}r.HudError=o;class t extends o{code=9001}r.HudInitError=t,r.HudClientError=class extends o{code=9002;originalAxiosErrorCode;constructor(e,r){super(e),this.originalAxiosErrorCode=r}},r.HudWorkerError=class extends o{code=9003};class n extends o{code=9004}r.HudEditError=n,r.HudUnsupportedError=class extends n{code=9005},r.HudAssert=class extends n{code=9006},r.HudWorkloadCollectorError=class extends o{code=9007},r.HudTimeoutError=class extends o{code=9008},r.HudClientUnauthorizedError=class extends o{code=9009},r.HudClientExceededMaxRetries=class extends o{code=9010},r.HudNoTranspileOnlyError=class extends o{code=9011},r.HudSessionThrottle=class extends t{code=9012},r.HudTsNodeNotFoundButUsed=class extends o{code=9013},r.HudInitNetworkError=class extends o{code=9014;originalAxiosErrorCode;constructor(e,r){super(e),this.originalAxiosErrorCode=r}},r.HudBadLoggerError=class extends o{code=9101};class i extends o{code=9200}r.HudExtnensionError=i,r.HudExtensionRegisterError=class extends i{code=9201},r.HudExtensionNextFailedError=class extends i{code=9202};class s extends o{code=9250}r.HudSqsError=s,r.HudNoQueueUrlInSqsConsumer=class extends s{code=9251},r.HudNoEventTypeInSqsConsumerOn=class extends s{code=9252},r.HudNoCallbackInSqsConsumerOn=class extends s{code=9253},r.HudFailExtractSqsQueueName=class extends s{code=9254},r.HudNoEventTypeInSqsConsumerEmit=class extends s{code=9255},r.HudNoErrorInSqsConsumerEmit=class extends s{code=9256},r.HudNoMessageInSqsConsumerEmit=class extends s{code=9257};const a=9999;let u=a;r.UserErrorLogs={HudServiceNotSet:()=>({level:"error",errCode:"E1001",moreInfo:!0,message:"Can't load Hud, HUD_SERVICE was not set. Please set service name using the environment variable HUD_SERVICE."}),HudServiceInvalid:()=>({level:"error",errCode:"E1002",moreInfo:!0,message:"Can't load Hud, HUD_SERVICE value has invalid service name. Please set service name using the environment variable HUD_SERVICE."}),HudApiKeyNotSet:()=>({level:"error",errCode:"E1004",moreInfo:!0,message:"Can't load Hud, HUD_KEY was not set. Please set API key using the environment variable HUD_KEY."}),HudApiKeyInvalid:()=>({level:"error",errCode:"E1005",moreInfo:!0,message:"Can't load Hud, HUD_KEY value has invalid API key. Please set a valid key in environment variable HUD_KEY."}),HudSessionOptionsInvalid:e=>({level:"warn",errCode:"E1006",moreInfo:!0,message:`Options parameter is not a valid object, defaulting to empty options. Reason: ${JSON.stringify(JSON.parse(e))}.`}),BothApiKeyAndServiceNotSet:()=>({level:"error",errCode:"E1007",moreInfo:!0,message:"Can't load Hud, HUD_KEY and HUD_SERVICE were not set. Please set API key using the environment variable HUD_KEY and service name using the environment variable HUD_SERVICE."}),SessionOptionsSessionTagsWithDots:()=>({level:"warn",errCode:"E1008",moreInfo:!0,message:"Options.tags object keys can't contain dots; they have been replaced with underscores."}),ApiKeyDenied:e=>({level:"error",errCode:"E1011",moreInfo:!0,message:`Can't load Hud, the provided key is invalid. Please provide a valid HUD_KEY in your ${{ENV:"environment variable",CONFIG_FILE:"file",CONFIG_ENV:"HUD_CONFIG",INIT:"init function",SETUP:"setup function"}[e]}.`}),ShutdownGracefully:e=>({level:"error",errCode:`E${e}`,message:"SDK has initiated a graceful shutdown. Your application remains unaffected"}),UnsupportedNodeVersion:()=>({level:"error",errCode:"E1012",moreInfo:!0,message:"Can't load Hud due to an unsupported node version."}),UnsupportedSyntax:()=>({level:"error",errCode:"E1014",moreInfo:!0,message:"Can't load Hud due to an unsupported syntax version."}),UnsupportedLambdaMemory:e=>({level:"error",errCode:"E1015",moreInfo:!0,message:`Can't load Hud as lambda function memory size is less than ${e}MB.`}),JSONErrorInUserConfig:(e,r)=>({level:"error",errCode:"E1016",moreInfo:!0,message:`Can't load Hud, the config file contains an invalid JSON. Please set a valid json in Hud's config ${e}`+(r?`, Error: ${r}.`:".")}),ZodErrorInUserConfig:(e,r)=>({level:"error",errCode:"E1017",moreInfo:!0,message:`Can't load Hud, the config file contains an invalid value for field: ${r}. Please set a valid value for ${r} in the config ${e}.`}),ConfigInaccessible:e=>({level:"error",errCode:"E1018",moreInfo:!0,message:`Can't load Hud, the config file is inaccessible. Please make sure your node application has read permissions to the Hud config file, ${e}.`}),SetupCalledWithoutKey:()=>({level:"error",errCode:"E1019",moreInfo:!0,message:"API key not found or invalid. SDK has initiated a graceful shutdown. Your application remains unaffected."}),SetupCalledWithoutService:()=>({level:"error",errCode:"E1020",moreInfo:!0,message:"Service name parameter not found or invalid. SDK has initiated a graceful shutdown. Your application remains unaffected."}),HudEnableIsFalse:()=>({level:"warn",errCode:"E1021",moreInfo:!0,message:"HUD_ENABLE is set to false. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InstrumentedFunctionCountExceeded:e=>({level:"error",errCode:"E1022",moreInfo:!0,message:`SDK limit of ${e} instrumented functions exceeded. SDK has initiated a graceful shutdown. Your application remains unaffected.`}),PodMemoryLimitTooLow:e=>({level:"error",errCode:"E1023",moreInfo:!0,message:`Insufficient memory available. Minimum required:(${e}MB). SDK has initiated a graceful shutdown. Your application remains unaffected.`}),DebuggerAttached:()=>({level:"error",errCode:"E1024",message:"Did not load as debugger is attached."}),InitSessionBeforeRegister:()=>({level:"error",errCode:"E1025",moreInfo:!0,message:"register() was not called, or called after initSession() - please call register() before initSession() and run again. Your application continues normally without Hud."}),RegisterMisplacedNoDeclarations:()=>({level:"warn",errCode:"E1026",moreInfo:!0,message:"Warning - No code has been mapped so far. This probably means register() was called too late — after your code was already loaded. Move it to the top of your entry file to enable proper mapping. Your application continues normally without Hud data."}),UnsupportedFrameworkVersion:e=>({level:"warn",errCode:"E1029",message:`Warning - Unsupported version of ${e} framework(s). This means Hud won't track your framework invocations. Your application continues normally, but with partial Hud data. See the compatibility matrix for details: https://docs.hud.io/docs/hud-sdk-compatibility-matrix-for-node#/`}),UninstrumentedFilesLogThresholdExceeded:e=>({level:"warn",errCode:"E1027",message:`Warning - ${e} of your code files were imported before register(). This means Hud won't track all of your functions. Please move register() call to an earlier location. To view the list of files use register({verbose: true}). Your application continues normally, but with partial Hud data.`,moreInfo:!0}),UninstrumentedFrameworks:e=>({level:"warn",errCode:"E1028",message:`Warning - The framework(s): ${e.map(e=>`"${e}"`).join(", ")} was imported before register(). This means Hud won't track your framework invocations. Please move register() call to an earlier location. Your application continues normally, but with partial Hud data.`}),YesInstrumentationNoMetrics:()=>({level:"warn",errCode:"E1032",moreInfo:!0,message:"Warning - Code mapped successfully, but no function activity was tracked. Make sure your service is running and actively handling requests."}),HudEnableNotSet:e=>({level:"error",moreInfo:!0,message:`Did not load as HUD_ENABLE is ${void 0===e?"undefined":"set to a non-true value"}. Please set HUD_ENABLE=true to run Hud.`}),LambdaNotViaLayer:()=>({level:"error",errCode:"E1034",message:"Can't load Hud, lambda support is currently in beta. Contact Hud to get early access."}),RunningInBun:()=>({level:"error",errCode:"E1035",message:"Hud does not support Bun yet. The SDK has initiated a graceful shutdown. Your application remains unaffected. See the compatibility matrix for details: https://docs.hud.io/docs/hud-sdk-compatibility-matrix-for-node"}),RunningOnWindows:()=>({level:"error",errCode:"E1036",message:"Hud does not support Windows yet. The SDK has initiated a graceful shutdown. Your application remains unaffected. See the compatibility matrix for details: https://docs.hud.io/docs/hud-sdk-compatibility-matrix-for-node"}),UnsupportedNativeBuild:()=>({level:"error",errCode:"E1037",message:"Hud does not support this platform yet. The SDK has initiated a graceful shutdown. Your application remains unaffected. See the compatibility matrix for details: https://docs.hud.io/docs/hud-sdk-compatibility-matrix-for-node"}),TsNodeNotTranspileOnly:()=>({level:"error",errCode:"E1038",message:"detected ts-node is used without the transpileOnly flag, which is not supported yet. SDK has initiated a graceful shutdown. Your application remains unaffected.",moreInfo:!0}),TsNodeNotFoundEvenThoughRunWithTsNode:()=>({level:"error",errCode:"E1039",message:"'ts-node' was detected but could not be resolved by Hud. This may happen if 'ts-node' is installed globally. Try installing it locally in your project. The SDK has initiated a graceful shutdown. Your application remains unaffected.",moreInfo:!0}),InitFailedDueGenericNetworkError:()=>({level:"error",moreInfo:!0,errCode:"E1040",message:"A network error occurred during SDK initialization. Please check your internet connection and try again. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InitFailedDueNetworkTimeout:()=>({level:"error",moreInfo:!0,errCode:"E1041",message:"The SDK failed to connect to Hud's backend due to a timeout during SDK initialization. Please verify your firewall settings to ensure outbound connections are allowed. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InitFailedDueNetworkRST:()=>({level:"error",moreInfo:!0,errCode:"E1042",message:"The SDK connection to Hud's backend was reset unexpectedly (RST) during SDK initialization. Please check your firewall or network security settings. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InitFailedDueSelfSignedCert:()=>({level:"error",moreInfo:!0,errCode:"E1043",message:"SSL certificate verification failed during SDK initialization. If your organization uses a self-signed certificate, set the NODE_EXTRA_CA_CERTS environment variable to the path of your CA certificate file. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InitFailedDueDnsFailed:()=>({level:"error",moreInfo:!0,errCode:"E1044",message:"The SDK failed to resolve DNS when attempting to connect to Hud's backend during SDK initialization. If the problem persists, please contact support. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InitFailedDueBackendError:()=>({level:"error",moreInfo:!0,errCode:"E1045",message:"The SDK was unable to complete initialization due to a temporary issue with Hud's backend. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InitTimeout:e=>({moreInfo:!0,level:"error",message:`SDK imported but not initialized. Please ensure to call '${e?"hud.initSession(KEY, SERVICE)":"hud.init()"}' to initialize the SDK.`}),RehookCalledBeforeRegister:()=>({level:"error",errCode:"E1046",moreInfo:!0,message:"register() was not called, or called after rehook() - please call register() before rehook() and run again. Your application continues normally with partial hud data."}),EsbuildSourceMapFound:()=>({level:"error",errCode:"E1047",message:"Source maps were detected for files modified by the Esbuild plugin, which is not yet supported. SDK has initiated a graceful shutdown. Your application remains unaffected."}),EsbuildMissingKey:()=>({level:"error",errCode:"ES0001",moreInfo:!0,message:"missing HUD_KEY, skipping Hud plugin, your build is unaffected."}),EsbuildFailedProcessingFile:e=>({level:"error",errCode:"ES0002",moreInfo:!0,message:`failed processing file "${e}", reverting to original loader.`}),EsbuildFailedBundling:()=>({level:"error",errCode:"ES0003",moreInfo:!0,message:"encountered unexpected file bundling, build aborted."}),EsbuildFailedParsingSourcemap:()=>({level:"error",errCode:"ES0004",moreInfo:!0,message:"failed parsing source maps, skipping upload, Hud will run without source maps."}),EsbuildFailedUploadingSourcemap:e=>({level:"error",errCode:"ES0005",moreInfo:!0,message:`failed uploading source map: ${e}, Hud will run without source maps.`}),EsbuildFailedUploadingSourcemapUnauthorized:()=>({level:"error",errCode:"ES0006",moreInfo:!0,message:"failed uploading source map: unauthorized, Hud will run without source maps."}),EsbuildUnsupportedPlatform:()=>({level:"error",errCode:"ES0007",message:'Can\'t load Hud, as our esbuild plugin supports "node" mode only. Your app remains unaffected. For more information visit docs.hud.io/docs/support-matrix'}),NextDevNotSupported:()=>({level:"error",moreInfo:!0,errCode:"NX0001",message:"Next.js dev server is not supported. Please use 'next start' instead."}),SourceMapCleanupFailed:()=>({level:"error",moreInfo:!0,errCode:"NX0002",message:"Source maps cleanup failed. Build stopped to prevent unintentional inclusion of source maps."}),WebpackFailedUploadingSourcemap:()=>({level:"error",errCode:"NX0003",moreInfo:!0,message:"Failed uploading source maps, Hud will run without source maps."}),NextJsPluginNotUsed:()=>({level:"warn",errCode:"NX0004",message:"Next.js support is in closed beta. Request access at: https://docs.hud.io/docs/support"}),EsbuildUnsupportedWindows:()=>({level:"error",errCode:"ES0008",message:"Can't load Hud, as our esbuild plugin does not supports windows. Your app remains unaffected. For more information visit docs.hud.io/docs/support-matrix"}),EsbuildSourceMapInline:()=>({level:"error",errCode:"ES0009",message:"detected sourcemap is used as 'inline' or 'both', which is not supported yet. SDK has initiated a graceful shutdown. Your application remains unaffected."}),HudCliInvalidKey:()=>({level:"error",errCode:"CI1001",moreInfo:!0,message:"Initialization failed - the provided API key is invalid. Instrumentation has been disabled."}),HudCliNoJsFiles:()=>({level:"error",errCode:"CI1002",moreInfo:!0,message:"No JavaScript files found in the specified directories. Instrumentation aborted."}),HudCliAllFilesInstrumented:()=>({level:"warn",errCode:"CI1003",moreInfo:!0,message:"All files in the specified directory are already instrumented. No further action taken."}),HudCliSomeFilesInstrumented:()=>({level:"warn",errCode:"CI1004",moreInfo:!0,message:"Detected that some files are already instrumented. Skipping re-instrumentation for these files."}),HudCliUnkownError:()=>({level:"error",errCode:"CI1005",moreInfo:!0,message:"An unexpected error occurred during instrumentation. Instrumentation process aborted."}),HudCliInstrumentedFunctionCountExceeded:e=>({level:"error",errCode:"CI1006",moreInfo:!0,message:`CI limit of ${e} instrumented functions exceeded. Instrumentation has been halted. Your source files remain unchanged.`}),HudCliUploadFailed:()=>({level:"warn",errCode:"CI1007",moreInfo:!0,message:"Failed to upload code mapping. Existing functions will continue to report, but new or updated ones won't be tracked."}),HudCliInvalidDirectory:e=>({level:"error",errCode:"CI1008",moreInfo:!0,message:`Provided directory does not exist: ${e}. Instrumentation aborted.`}),SetContextBeforeRegister:()=>({level:"warn",errCode:"E1101",message:"Warning - setContext() was called before register(). Please call register() before setContext()."}),SetContextNoAsyncContext:()=>({level:"warn",errCode:"E1103",message:"Warning - setContext() was called outside of an endpoint flow and was skipped. Make sure setContext() is only called within a registered endpoint handler."}),SetContextMaxKeysExceeded:()=>({level:"warn",errCode:"E1104",message:"Warning - A maximum of 20 context keys is allowed. Additional keys were ignored. Pass fewer than 20 keys to setContext()."}),SetContextKeyIsNotString:e=>({level:"warn",errCode:"E1105",message:`Warning - Context key "${e}" must be a string. This entry was skipped. Only string keys are supported in setContext().`}),SetContextKeyTooLong:e=>({level:"warn",errCode:"E1106",message:`Warning - Context key "${e}" exceeds the 64-character limit and was skipped. Shorten the key to 64 characters or fewer.`}),SetContextEmptyArray:e=>({level:"warn",errCode:"E1107",message:`Warning - Context key "${e}" is an empty array and was skipped. Use a non-empty array.`}),SetContextArrayTooLong:e=>({level:"warn",errCode:"E1108",message:`Warning - A maximum of 20 items is allowed in array "${e}". Additional items were ignored. Trim the array to 20 items or fewer.`}),SetContextArrayAllItemsInvalid:e=>({level:"warn",errCode:"E1109",message:`Warning - Context key "${e}" is invalid. All items in the array are unsupported. Entry was skipped. Use an array containing only strings, numbers, or booleans.`}),SetContextValueIsNotPrimitive:e=>({level:"warn",errCode:"E1110",message:`Warning - Value for ${e} must be a primitive or an array of primitives. Entry was skipped. Use a string, number, boolean, or an array of these types.`}),SetContextValueIsUndefinedOrNull:e=>({level:"warn",errCode:"E1111",message:`Warning - Value for ${e} is undefined or null. Entry was skipped. Provide a defined primitive value or a non-empty array.`}),SetContextValueIsTooLong:e=>({level:"warn",errCode:"E1112",message:`Warning - Value for ${e} exceeds the 256-character limit. Entry was skipped. Shorten the value to 256 characters or fewer.`}),SetContextValueIsEmptyString:e=>({level:"error",errCode:"E1113",message:`Warning - Context key ${e} is invalid. Key must be non-empty. Entry was skipped. Use a non-empty string as the key.`}),SetContextValueIsNotFiniteNumber:e=>({level:"error",errCode:"E1114",message:`Warning - Value for ${e} is invalid. Must be a finite number. Entry was skipped. Use a numeric value that is not Infinity or NaN.`})}},9525:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.generateEndpointFlowId=function(e,r){return(0,t.v5)(`${e.toString()}|${Array.from(r).sort().join(",")}`,n)},r.generateGraphqlFlowId=function(e,r){return(0,t.v5)(`${e}|${r}`,n)},r.generateKafkaFlowId=function(e,r,o){return(0,t.v5)(`${e.toString()}|${r}|${o}`,n)},r.generateSqsFlowId=function(e,r,o=""){const i=`${e}|${r}|${o}`;return(0,t.v5)(i,n)};const t=o(3903),n="fa79d8b7-069c-4bbf-9c00-34bfc8b3a5a6"},9896:e=>{e.exports=require("fs")}},r={};return function o(t){var n=r[t];if(void 0!==n)return n.exports;var i=r[t]={exports:{}};return e[t].call(i.exports,i,i.exports,o),i.exports}(5070)})());
1
+ !function(e,r){if("object"==typeof exports&&"object"==typeof module)module.exports=r();else if("function"==typeof define&&define.amd)define([],r);else{var o=r();for(var t in o)("object"==typeof exports?exports:e)[t]=o[t]}}(global,()=>(()=>{"use strict";var e={46:function(e,r,o){var t,n=this&&this.__createBinding||(Object.create?function(e,r,o,t){void 0===t&&(t=o);var n=Object.getOwnPropertyDescriptor(r,o);n&&!("get"in n?!r.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(e,t,n)}:function(e,r,o,t){void 0===t&&(t=o),e[t]=r[o]}),i=this&&this.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),s=this&&this.__importStar||(t=function(e){return t=Object.getOwnPropertyNames||function(e){var r=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[r.length]=o);return r},t(e)},function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var o=t(e),s=0;s<o.length;s++)"default"!==o[s]&&n(r,e,o[s]);return i(r,e),r});Object.defineProperty(r,"__esModule",{value:!0}),r.readFile=async function(e,r,o){try{if(r&&o){const t=Buffer.alloc(o-r),n=await u.promises.open(e,"r");return await n.read(t,0,o-r,r),await n.close(),t.toString("utf-8")}return await u.promises.readFile(e,"utf-8")}catch(r){return void a.worker_logger.error("Failed to read file",{filename:e,msg:r instanceof Error?r.message:r})}};const a=o(523),u=s(o(9896))},350:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.incrementInstrumentedFilesCount=function(){i++},r.setInstrumentedFilesCountInterval=function(){let e;return s||(n.instrument_logger.info("Setting interval for instrumented files count logging",{interval:t.hudConfig.logIntervals.instrumentedFilesCount}),e=setInterval(()=>{const e=a();e>0&&(n.instrument_logger.info("Successfully instrumented",{functionsCount:e}),u())},t.hudConfig.logIntervals.instrumentedFilesCount),e.unref(),s=!0),e},r.incrementSentEventsCount=function(e){l[e]=(l[e]||0)+1},r.resetSentEventsCount=c,r.getSentEventsCount=f,r.setSentEventsCountInterval=function(){let e;return d||(n.worker_logger.info("Setting interval for sent events count logging",{interval:t.hudConfig.logIntervals.sentEventsCount}),e=setInterval(()=>{const e=f();Object.keys(e).length>0&&(n.worker_logger.info("Successfully sent events",{sentEventsCount:e}),c())},t.hudConfig.logIntervals.sentEventsCount),e.unref(),d=!0),e};const t=o(5809),n=o(523);let i=0,s=!1;function a(){return i}function u(){i=0}let l={},d=!1;function c(){l={}}function f(){return l}},523:e=>{e.exports=require("./logger")},857:e=>{e.exports=require("os")},1176:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.getInstrumentedThirdPartyModuleInfo=function(e){const r=t.hudConfig.functionsToInstrument||[];for(const o of r)for(const r in o.fileToFunctionsMapping)if(e.endsWith(r))return{functions:o.fileToFunctionsMapping[r],moduleName:o.moduleName}};const t=o(5809)},1493:e=>{e.exports=require("v8")},1569:e=>{e.exports=require("zod")},1943:e=>{e.exports=require("fs/promises")},2784:e=>{e.exports=require("../native/_index")},2987:e=>{e.exports=require("perf_hooks")},3305:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.updateUserConfigFromInit=function(e,r,o){if(void 0!==e&&(t.hudConfig.userConfig.key={value:e,source:"INIT"}),void 0!==r&&(t.hudConfig.userConfig.service={value:r,source:"INIT"}),void 0!==o){let e=o;const r=n.HudSessionOptionsSchema.safeParse(o);r.success?o.tags&&"object"==typeof o.tags&&Object.keys(o.tags).some(e=>e.includes("."))&&(i.customer_logger.log(a.UserErrorLogs.SessionOptionsSessionTagsWithDots()),e.tags=Object.fromEntries(Object.entries(o.tags).map(([e,r])=>[e.replace(".","_"),r]))):(i.customer_logger.log(a.UserErrorLogs.HudSessionOptionsInvalid(r.error.message)),e={}),t.hudConfig.userConfig.tags={value:e.tags,source:"INIT"}}},r.updateUserConfigFromFile=function(){let e;try{e=(0,t.getConfigContent)()}catch(e){throw e instanceof t.HudFailedReadConfigError&&"EACCES"===e.code&&i.customer_logger.log(a.UserErrorLogs.ConfigInaccessible(e.path)),e}if(e)try{const r=u.partial().parse(JSON.parse(e.content));Object.entries(r).forEach(([r,o])=>{!function(e,r,o){e[r]=o}(t.hudConfig.userConfig,r,{value:o,source:"HUD_CONFIG"===e.source?"CONFIG_ENV":"CONFIG_FILE"})})}catch(r){throw r instanceof s.ZodError?r.errors.forEach(r=>{const o=r.path.join(".");i.customer_logger.log(a.UserErrorLogs.ZodErrorInUserConfig(e.source,o))}):i.customer_logger.log(a.UserErrorLogs.JSONErrorInUserConfig(e.source,r.message)),r}},r.updateUserConfigFromEnv=function(){const e=process.env.HUD_KEY,r=process.env.HUD_SERVICE,o=process.env.HUD_ENABLE_DAPULSE,n=(0,t.getModulesToTraceFromEnv)(),i=(0,t.getFrameworksToEnableFromEnv)(),s=process.env.HUD_MAX_INSTRUMENTED_FUNCTIONS,a=process.env.HUD_MIN_POD_MEMORY_MB,u=process.env.HUD_DISABLE_RUNTIME_INSTRUMENTATION;e&&(t.hudConfig.userConfig.key={value:e,source:"ENV"}),r&&(t.hudConfig.userConfig.service={value:r,source:"ENV"}),o&&(t.hudConfig.userConfig.enableDapulse={value:"true"===o,source:"ENV"}),n&&(t.hudConfig.userConfig.includeModules={value:n,source:"ENV"}),i&&(t.hudConfig.userConfig.enableFrameworks={value:i,source:"ENV"}),s&&(t.hudConfig.userConfig.maxMappedFunctions={value:parseInt(s),source:"ENV"}),a&&(t.hudConfig.userConfig.minPodMemoryMB={value:parseInt(a),source:"ENV"}),u&&(t.hudConfig.userConfig.disableRuntimeInstrumentation={value:"true"===u,source:"ENV"})},r.updateUserConfigFromRegisterOptions=function(e,r){if(e.includeModules&&Array.isArray(e.includeModules)&&(t.hudConfig.userConfig.includeModules={value:e.includeModules,source:r}),e.enableFrameworks){const o=n.availableFrameworksSchema.safeParse(e.enableFrameworks);o.success&&(t.hudConfig.userConfig.enableFrameworks={value:o.data,source:r})}e.customOptions&&e.customOptions.dapulseSqsConsumer&&(t.hudConfig.userConfig.enableDapulse={value:"true"===e.customOptions.dapulseSqsConsumer,source:r}),e.maxMappedFunctions&&"number"==typeof e.maxMappedFunctions&&(t.hudConfig.userConfig.maxMappedFunctions={value:e.maxMappedFunctions,source:r}),e.minPodMemoryMB&&"number"==typeof e.minPodMemoryMB&&(t.hudConfig.userConfig.minPodMemoryMB={value:e.minPodMemoryMB,source:r}),e.maxFileSizeBytes&&"number"==typeof e.maxFileSizeBytes&&(t.hudConfig.userConfig.maxFileSizeBytes={value:e.maxFileSizeBytes,source:r}),e.maxTimeUntilInitSessionMs&&"number"==typeof e.maxTimeUntilInitSessionMs&&(t.hudConfig.userConfig.maxTimeUntilInitSessionMs={value:e.maxTimeUntilInitSessionMs,source:r}),void 0!==e.disableRuntimeInstrumentation&&(t.hudConfig.userConfig.disableRuntimeInstrumentation={value:e.disableRuntimeInstrumentation,source:r})};const t=o(5809),n=o(8528),i=o(523),s=o(1569),a=o(9499),u=n.HudOptionsSchema.omit({customOptions:!0}).extend(n.HudSessionOptionsSchema.shape).extend({key:s.z.string().optional(),service:s.z.string().optional(),enable:s.z.boolean().optional(),enableDapulse:s.z.boolean().optional()})},3596:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.safeCall=function(e,r){return r.catch(r=>{(0,t.isAbortError)(r)||e.error("Unhandled exception on async task",{msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0})})};const t=o(9499)},3705:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.isHudEnabled=function(){if("false"===process.env.HUD_ENABLE)return!1;if(globalThis.forceHudEnable)return!0;let e,r;try{if(e=(0,t.getConfigContent)(),e&&(r=JSON.parse(e.content),!1===r.enable))return!1}catch(r){throw r instanceof t.HudFailedReadConfigError&&"EACCES"===r.code?n.customer_logger.log(i.UserErrorLogs.ConfigInaccessible(r.path)):e&&n.customer_logger.log(i.UserErrorLogs.JSONErrorInUserConfig(e.source,r instanceof Error?r.message:void 0)),r}return"true"===process.env.HUD_ENABLE||!0===r?.enable};const t=o(5809),n=o(523),i=o(9499)},3903:e=>{e.exports=require("uuid")},4463:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.getFilesForDeclarations=async function(e,r){const o=new Map;for(const r of e)o.set(`${r.file_path_checksum}|${r.file_checksum}`,r);const n=Array.from(o.entries()).sort(([e],[r])=>e.localeCompare(r)).map(([,e])=>({file_path_checksum:e.file_path_checksum,file_checksum:e.file_checksum})),i=await r(n);if(i.send_all)return t.worker_logger.debug("All file declarations are requested by sink"),e;t.worker_logger.debug("Partial file declarations are requested by sink",{fileCount:i.files.length});const s=[];for(const e of i.files){const r=`${e.file_path_checksum}|${e.file_checksum}`,t=o.get(r);t&&s.push(t)}return s};const t=o(523)},5042:function(e,r,o){var t=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.getAllModules=async function e(r,o=3){if(o<=0)return[];const t=[],s=i.default.join(r,"package.json");try{const e=await n.default.readFile(s,"utf-8"),o=JSON.parse(e),i=o.name||void 0,a=o.version||void 0;t.push({name:i,version:a,path:r})}catch{}const a=i.default.join(r,"node_modules");try{await n.default.access(a);const r=await n.default.readdir(a);for(const s of r)if(s.startsWith("@")){const r=i.default.join(a,s);let u=[];try{u=await n.default.readdir(r)}catch{continue}for(const n of u){const s=i.default.join(r,n);t.push(...await e(s,o-1))}}else{const r=i.default.join(a,s);t.push(...await e(r,o-1))}}catch{}return t};const n=t(o(1943)),i=t(o(6928))},5070:function(e,r,o){var t=this&&this.__createBinding||(Object.create?function(e,r,o,t){void 0===t&&(t=o);var n=Object.getOwnPropertyDescriptor(r,o);n&&!("get"in n?!r.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(e,t,n)}:function(e,r,o,t){void 0===t&&(t=o),e[t]=r[o]}),n=this&&this.__exportStar||function(e,r){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(r,o)||t(r,e,o)};Object.defineProperty(r,"__esModule",{value:!0}),n(o(9499),r),n(o(4463),r),n(o(9525),r),n(o(3705),r),n(o(350),r),n(o(5246),r),n(o(6287),r),n(o(9303),r),n(o(5042),r),n(o(7146),r),n(o(1176),r),n(o(7511),r),n(o(46),r),n(o(5308),r),n(o(3596),r),n(o(5990),r),n(o(5706),r),n(o(5935),r),n(o(6548),r),n(o(6180),r),n(o(3305),r),n(o(7552),r),n(o(8236),r),n(o(8481),r)},5246:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.register=async function(){n.worker_logger.info("registering extension");const e=await fetch(`${s}/register`,{method:"post",body:JSON.stringify({events:["INVOKE"]}),headers:{"Content-Type":"application/json","Lambda-Extension-Name":"hud-extension"}});if(!e.ok)throw n.worker_logger.error("register failed",{status:e.status,statusText:e.statusText,body:await e.text(),baseUrl:s}),new i.HudExtensionRegisterError("register failed");const r=e.headers.get("lambda-extension-identifier");if(!r)throw new i.HudExtensionRegisterError("extension id not found");return r},r.next=u,r.extensionMainLoop=async function(e,r){let o=Date.now();for(n.worker_logger.info("starting extension main loop");;)try{const i=await u(e);if(r.listenerCount("eventloop")>0){const e=r.listenerCount("eventloop"),i=Date.now()-o;r.emit("eventloop",""),o=Date.now();const s=Math.min(t.hudConfig.lambdaBaseGivenTime+e*t.hudConfig.lambdaExtraGivenTimePerRequest,t.hudConfig.lambdaMaxGivenTime);n.worker_logger.debug(`Starting giving time for the eventloop to run at ${(new Date).toISOString()}. ${i}ms since last eventloop request. Given time: ${s}ms`),await new Promise(e=>setTimeout(e,s)),n.worker_logger.debug(`Done giving time for the eventloop to run ${(new Date).toISOString()}`)}if("SHUTDOWN"===i?.eventType)return void n.worker_logger.info("shutting down")}catch(e){e instanceof i.HudExtnensionError?n.worker_logger.warn("Extension tick failed, continuing",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}):n.worker_logger.error("Extension tick failed with unexpected error, continuing",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0});continue}},r.nextLoopDummy=async function(e){for(;;)try{(await a(e)).ok||await new Promise(e=>setTimeout(e,50))}catch{await new Promise(e=>setTimeout(e,50))}};const t=o(5809),n=o(523),i=o(9499),s=`http://${process.env.AWS_LAMBDA_RUNTIME_API}/2020-01-01/extension`;async function a(e){return await fetch(`${s}/event/next`,{method:"get",headers:{"Content-Type":"application/json","Lambda-Extension-Identifier":e}})}async function u(e){const r=await a(e);if(!r.ok)throw n.worker_logger.info("next failed",await r.text()),new i.HudExtensionNextFailedError;return await r.json()}},5308:function(e,r,o){var t,n=this&&this.__createBinding||(Object.create?function(e,r,o,t){void 0===t&&(t=o);var n=Object.getOwnPropertyDescriptor(r,o);n&&!("get"in n?!r.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(e,t,n)}:function(e,r,o,t){void 0===t&&(t=o),e[t]=r[o]}),i=this&&this.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),s=this&&this.__importStar||(t=function(e){return t=Object.getOwnPropertyNames||function(e){var r=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[r.length]=o);return r},t(e)},function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var o=t(e),s=0;s<o.length;s++)"default"!==o[s]&&n(r,e,o[s]);return i(r,e),r});Object.defineProperty(r,"__esModule",{value:!0}),r.isDebuggerAttached=g,r.isSupportedNative=v,r.shouldRunHud=function(){return"false"===process.env.HUD_ENABLE?{shouldRun:!1,error:c.UserErrorLogs.HudEnableIsFalse()}:d.isMainThread?(0,m.isHudEnabled)()?process.versions.bun?{shouldRun:!1,error:c.UserErrorLogs.RunningInBun()}:function(){const e=process.versions.node.split(".")[0];return!!a.hudConfig.supportedNodeVersions.includes(e)}()?process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE&&!function(){try{return"1"===process.env.HUD_INTERNAL_EXEC_WRAPPER_USED}catch{return!1}}()?{shouldRun:!1,error:c.UserErrorLogs.LambdaNotViaLayer()}:g()?{shouldRun:!1,error:c.UserErrorLogs.DebuggerAttached()}:function(){const e=(0,f.getMemoryLimitInfo)();return!!(0,f.isMemoryLimitBigEnough)(e)}()?v()?(0,p.isNextJs)("dev")?{shouldRun:!1,error:c.UserErrorLogs.NextDevNotSupported()}:{shouldRun:!0}:{shouldRun:!1,error:c.UserErrorLogs.UnsupportedNativeBuild()}:{shouldRun:!1,error:c.UserErrorLogs.PodMemoryLimitTooLow(a.hudConfig.userConfig.minPodMemoryMB?.value??Number.MAX_SAFE_INTEGER)}:{shouldRun:!1,error:c.UserErrorLogs.UnsupportedNodeVersion()}:{shouldRun:!1,error:c.UserErrorLogs.HudEnableNotSet(process.env.HUD_ENABLE)}:(u.app_logger.info("required not from main thread"),{shouldRun:!1,error:null})};const a=o(5809),u=o(523),l=s(o(6592)),d=o(5919),c=o(9499),f=o(8958),m=o(3705),p=o(7146);function g(){if("true"===process.env.HUD_ALLOW_DEBUGGER)return!1;if(process.execArgv.some(e=>e.includes("--inspect")||e.includes("--debug")||e.includes("--inspect-brk")||e.includes("--debug-brk")))return!0;try{return"string"==typeof l.url()}catch{return!1}}function v(){return void 0!==o(2784).transform}},5706:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.shouldSupportSourceMap=function(){return!!t.hudConfig.supportSourceMap&&(process.execArgv.includes("--enable-source-maps")&&n.instrument_logger.warn("--enable-source-maps is set, enabling custom source-map-support anyway"),!0)},r.combineSourceMaps=function(e,r){if(0===e.length)return;if(1===e.length&&void 0===e[0].lineOffset)return e[0].map;const o=e.map(e=>({offset:{line:e.transformedLineOffset,column:e.transformedColumnOffset},map:{..."string"==typeof e.map?JSON.parse(e.map):e.map,file:r}})),t={version:3,file:r,sections:o};return JSON.stringify(t)},r.appendInlineSourceMap=function(e,r){let o;return void 0===r?e:(o="string"==typeof r||r instanceof String?Buffer.from(r.toString()).toString("base64"):Buffer.from(JSON.stringify(r)).toString("base64"),e+`\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${o}`)};const t=o(5809),n=o(523)},5809:e=>{e.exports=require("./config")},5919:e=>{e.exports=require("node:worker_threads")},5935:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.suppressTraces=function(e){return function(...r){return t.hudConfig.suppressTraces&&s&&a?(n.app_logger.debug("Running with Suppressed traces"),s.with(a(s.active()),()=>e(...r))):e(...r)}};const t=o(5809),n=o(523),i=o(8481);let s,a;try{const e=(0,i.myRequire)("@opentelemetry/api"),r=(0,i.myRequire)("@opentelemetry/core");s=e.context,a=r.suppressTracing,n.app_logger.info("OpenTelemetry exists",{suppressConfig:t.hudConfig.suppressTraces})}catch{n.app_logger.info("OpenTelemetry api/core does not exist")}},5990:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.sourceFileMetadataToTransferSourceFileMetadata=function(e){return(0,t.omit)(e,"code","map","mapRelativeToChunk")};const t=o(6287)},6180:function(e,r,o){var t,n=this&&this.__createBinding||(Object.create?function(e,r,o,t){void 0===t&&(t=o);var n=Object.getOwnPropertyDescriptor(r,o);n&&!("get"in n?!r.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(e,t,n)}:function(e,r,o,t){void 0===t&&(t=o),e[t]=r[o]}),i=this&&this.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),s=this&&this.__importStar||(t=function(e){return t=Object.getOwnPropertyNames||function(e){var r=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[r.length]=o);return r},t(e)},function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var o=t(e),s=0;s<o.length;s++)"default"!==o[s]&&n(r,e,o[s]);return i(r,e),r});Object.defineProperty(r,"__esModule",{value:!0}),r.unrefSetImmediate=function(e,r){return a.setImmediate(e,{...r,ref:!1})},r.unrefSetTimeout=function(e,r,o){return a.setTimeout(e,r,{...o,ref:!1})},r.unrefSetInterval=function(e,r,o){return a.setInterval(e,r,{...o,ref:!1})};const a=s(o(6460))},6287:(e,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.omit=function(e,...r){const o={...e};return r.forEach(function(e){delete o[e]}),o},r.omitDeep=function e(r,o){const t=o.map(e=>e.split("."));if(null==r||"object"!=typeof r)return r;if(Array.isArray(r))return r.map(r=>e(r,o));const n={...r};for(const r of t){if(0===r.length)continue;const o=r[0];o in n&&(1!==r.length?n[o]=e(n[o],[r.slice(1).join(".")]):delete n[o])}return n},r.pickDeep=function e(r,o){if(Array.isArray(r))return r.map(r=>e(r,o));if("object"!=typeof r||null===r)return r;const t={},n={};for(const e of o){const[r,...o]=e.split(".");n[r]=n[r]??[],o.length>0&&"pick"!==n[r]?n[r].push(o.join(".")):n[r]="pick"}for(const o in n){if(!(o in r))continue;const i=r[o];"pick"===n[o]?t[o]=i:Array.isArray(i)?t[o]=i.map(r=>"object"==typeof r&&null!==r?e(r,n[o]):{}):"object"==typeof i&&null!==i&&(t[o]=e(i,n[o]))}return t}},6460:e=>{e.exports=require("timers/promises")},6548:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.getUserTsNodeConfig=function(e=!0){const r=function(){try{const e=i.myRequire.resolve("ts-node");if(!e)return;if(!i.myRequire.cache[e])return;const r=(0,i.myRequire)("ts-node"),o=process[r.REGISTER_INSTANCE];if(!o)return;return o.options}catch{return}}();if(r){if(!r.transpileOnly)throw e&&t.customer_logger.log(n.UserErrorLogs.TsNodeNotTranspileOnly()),t.app_logger.warn("ts-node is used but not configured to transpile only"),new n.HudNoTranspileOnlyError;return{cwd:r.cwd,project:r.project,projectSearchDir:r.projectSearchDir}}if(process.argv[0].endsWith("ts-node"))throw e&&t.customer_logger.log(n.UserErrorLogs.TsNodeNotFoundEvenThoughRunWithTsNode()),t.app_logger.info("ts-node not found even run with ts-node"),new n.HudTsNodeNotFoundButUsed};const t=o(523),n=o(9499),i=o(8481)},6592:e=>{e.exports=require("node:inspector")},6928:e=>{e.exports=require("path")},7146:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.detectNextJsApp=function(){const e=a("start");l(e),e&&n.app_logger.info("Detected Next.js application running with 'next start' command")},r.isNextJs=a,r.isNextJsApp=function(){return s},r.setIsNextJsApp=l;const t=o(5809),n=o(523),i=o(9499);let s=!1;function a(e){return!(!process.argv.some(e=>"next"===e)&&!process.argv.some(e=>e.includes("/dist/bin/next"))||!process.argv.some(r=>r===e))||!("dev"!==e||!process.argv.some(e=>e.includes("/next/dist/server/lib/start-server")))}let u=!1;function l(e){s=e,e&&!u&&(u=!0,globalThis.hudNextJsPluginIndicator=setTimeout(d,t.hudConfig.timeoutOnNextJsPlugin),globalThis.hudNextJsPluginIndicator.unref())}function d(){n.customer_logger.log(i.UserErrorLogs.NextJsPluginNotUsed())}},7511:function(e,r,o){var t,n=this&&this.__createBinding||(Object.create?function(e,r,o,t){void 0===t&&(t=o);var n=Object.getOwnPropertyDescriptor(r,o);n&&!("get"in n?!r.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(e,t,n)}:function(e,r,o,t){void 0===t&&(t=o),e[t]=r[o]}),i=this&&this.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),s=this&&this.__importStar||(t=function(e){return t=Object.getOwnPropertyNames||function(e){var r=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[r.length]=o);return r},t(e)},function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var o=t(e),s=0;s<o.length;s++)"default"!==o[s]&&n(r,e,o[s]);return i(r,e),r}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.getCpuLimit=void 0,r.loopLogThreadPerformance=async function(e,r,o){let t=d.performance.eventLoopUtilization(),n=d.performance.nodeTiming.toJSON();for await(const i of(0,m.unrefSetInterval)(r,void 0,{signal:o}))try{const r=d.performance.eventLoopUtilization(),o=d.performance.eventLoopUtilization(r,t);t=r;const i=c.getHeapStatistics(),s=d.performance.nodeTiming.toJSON(),a=s.idleTime-n.idleTime,u=s.duration-n.duration,l=a/u;n=s,e.info("thread performance statistics",{thread_elu_percentage:100*o.utilization,memory:{thread_heap_utilization_percentage:i.total_heap_size/i.heap_size_limit*100},idleTime:a,totalTime:u,idleTimePercentage:l})}catch(r){e.error("Failed logging thread performance statistics",{msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0})}},r.getCpuLimitUnsafe=p,r.loopLogProcessPerformance=async function(e,o,t){const n=l.default.totalmem(),i=(0,r.getCpuLimit)(e);let s=process.cpuUsage();for await(const r of(0,m.unrefSetInterval)(o,void 0,{signal:t}))try{const r=process.memoryUsage(),t=process.uptime(),a=process.cpuUsage(),u={user:a.user-s.user,system:a.system-s.system};s=a;let l=(u.user+u.system)/(1e3*o);i&&"number"==typeof i&&(l/=i),e.info("process performance statistics",{memory:{process_memory_rss:r.rss,process_memory_utilization_percentage:r.rss/n*100},cpu:100*l,cpuStats:{limit:i,usagePercentage:100*l},uptime:t})}catch(r){e.error("Failed logging process performance statistics",{msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0})}};const u=o(9896),l=a(o(857)),d=o(2987),c=s(o(1493)),f=o(5935),m=o(6180);function p(e){e.info("Trying to detect CPU limit");try{const r=(0,u.readFileSync)("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8"),o=(0,u.readFileSync)("/sys/fs/cgroup/cpu/cpu.cfs_period_us","utf8");return e.info("CPU limit detected for cgroups v1",{cpuQuota:r,cpuPeriod:o}),"-1"===r.toString().trim()?"unlimited":parseInt(r.toString())/parseInt(o.toString())}catch(r){try{const r=(0,u.readFileSync)("/sys/fs/cgroup/cpu.max","utf8"),[o,t,n]=r.trim().split(" ");return e.info("CPU limit detected for cgroups v2",{max:o,period:t}),o&&t?"max"===o?"unlimited":parseInt(o)/parseInt(t):void e.info("cpu.max file is not in the expected format",r)}catch(o){return void e.info("Failed to detect CPU limit",{e:r,e2:o})}}}let g,v=!1;r.getCpuLimit=e=>(v||(g=(0,f.suppressTraces)(p)(e),v=!0),g)},7552:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.HudContextValidationError=void 0,r.validateContext=function(e){try{const r={};for(const o in e){if(Object.keys(r).length>=20){u(n.UserErrorLogs.SetContextMaxKeysExceeded());break}if("string"==typeof o)if(o.length>64)u(n.UserErrorLogs.SetContextKeyTooLong(o));else{if(Array.isArray(e[o])){if(0===e[o].length){u(n.UserErrorLogs.SetContextEmptyArray(o));continue}const t=e[o],i=[];for(let e=0;e<t.length;e++){const r=t[e];if(i.length>=20){u(n.UserErrorLogs.SetContextArrayTooLong(o));break}l(r,o,!0)&&i.push(r)}if(0===i.length){u(n.UserErrorLogs.SetContextArrayAllItemsInvalid(o));continue}r[o]=i;continue}l(e[o],o)&&(r[o]=e[o])}else u(n.UserErrorLogs.SetContextKeyIsNotString(o))}return r}catch(e){throw t.app_logger.error("Failed to validate context",{error:e,stack:e instanceof Error&&null!==e?e.stack:void 0}),new a("Failed to validate context")}};const t=o(523),n=o(9499),i=new Set;let s=20;class a extends Error{}function u(e){s<=0||i.has(e.errCode)||(s--,t.app_logger.info(e.message),t.customer_logger.info(e.message),i.add(e.errCode))}function l(e,r,o=!1){const t=o?`item in array "${r}"`:`"${r}"`;return null==e?(u(n.UserErrorLogs.SetContextValueIsUndefinedOrNull(t)),!1):"object"==typeof e||"function"==typeof e?(u(n.UserErrorLogs.SetContextValueIsNotPrimitive(t)),!1):"string"==typeof e&&e.length>256?(u(n.UserErrorLogs.SetContextValueIsTooLong(t)),!1):""===e?(u(n.UserErrorLogs.SetContextValueIsEmptyString(t)),!1):!(e===1/0||e===-1/0||"number"==typeof e&&isNaN(e))||(u(n.UserErrorLogs.SetContextValueIsNotFiniteNumber(t)),!1)}r.HudContextValidationError=a},8236:(e,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.UserLogs=void 0,r.UserLogs={HudInitSuccess:()=>({level:"info",message:"Session started"}),FirstDecalarationSent:()=>({level:"info",message:"First code mapping sent successfully"}),FirstInvocationSent:()=>({level:"info",message:"First invocation sent successfully"}),HappyFlowCompleted:()=>({level:"info",message:"Your service is sending data successfully"}),FilesLoadedBeforeRegister:()=>({level:"info",message:"Files loaded before register():"}),FileBeforeRegisterTemplate:(e,r)=>({level:"info",message:`${e}. ${r}`}),InitIdleMode:()=>({level:"info",message:"Initialized successfully in idle mode."}),WebpackUploadedSourcemapSuccess:()=>({level:"info",message:"Source maps uploaded successfully."}),HudCliCompletedSuccessfully:e=>({level:"info",message:`Instrumentation completed successfully. ${e} files processed.`})}},8481:(e,r)=>{let o;Object.defineProperty(r,"__esModule",{value:!0}),r.myRequire=void 0;try{o=require}catch{o=void 0}r.myRequire=o},8528:e=>{e.exports=require("./dto")},8958:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.getMemoryLimitInfo=function(){const e=(0,i.getPodMemoryLimit)(n.app_logger);return n.app_logger.info(`Pod memory limit: ${null===e.podMemoryLimitMB?"unknown":e.podMemoryLimitMB+"MB"} from ${e.source}, minimum required: ${t.hudConfig.userConfig.minPodMemoryMB?.value??Number.MAX_SAFE_INTEGER}MB`),e},r.isMemoryLimitBigEnough=function(e){return null===e.podMemoryLimitMB||e.podMemoryLimitMB>=(t.hudConfig.userConfig.minPodMemoryMB?.value??Number.MAX_SAFE_INTEGER)};const t=o(5809),n=o(523),i=o(9303)},9303:function(e,r,o){var t=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.getPodMemoryLimit=function(e){if(null!==s)return s;if("linux"!==i.default.platform())return s=d(),s;let r=function(e,r){for(const e of["/sys/fs/cgroup/memory.max","/sys/fs/cgroup/memory.high"]){const o=l(e);if(!o)continue;const t=o.trim();if("max"===t){r.debug(`Found 'max' value in ${e}, will use system memory instead`);continue}const n=a(t,r);if(null!==n)return{podMemoryLimitMB:n,source:e}}return{podMemoryLimitMB:null,source:null}}(0,e);return null!==r.podMemoryLimitMB?(e.info(`Found pod memory limit: ${r.podMemoryLimitMB}MB from ${r.source}`),r):(r=function(e,r){for(const e of["/sys/fs/cgroup/memory/memory.stat","/sys/fs/cgroup/memory/memory.limit_in_bytes"]){const o=l(e);if(o)if(e.endsWith("memory.stat")){const t=["hierarchical_memory_limit","memory.limit_in_bytes","limit_in_bytes"],n=o.split("\n");for(const o of t){const t=n.find(e=>e.startsWith(o));if(t){const n=u(t.split(" ")[1],`${e}:${o}`,r);if(null!==n.podMemoryLimitMB)return n}}}else{const t=u(o.trim(),e,r);if(null!==t.podMemoryLimitMB)return t}}return{podMemoryLimitMB:null,source:null}}(0,e),null!==r.podMemoryLimitMB?(e.info(`Found pod memory limit: ${r.podMemoryLimitMB}MB from ${r.source}`),r):(r=d(),e.info(`No container memory limit found, using system memory: ${r.podMemoryLimitMB}MB`),s=r,r))};const n=o(9896),i=t(o(857));let s=null;function a(e,r){const o=parseInt(e);if(isNaN(o))return null;const t=Math.floor(o/1048576);return t<=0||t>=131072?(r.debug(`Treating memory value (${e} bytes) as unlimited.`),null):t}function u(e,r,o){if(!e)return{podMemoryLimitMB:null,source:null};const t=a(e,o);return null!==t?{podMemoryLimitMB:t,source:r}:{podMemoryLimitMB:null,source:null}}function l(e){try{return(0,n.readFileSync)(e,"utf8")}catch{return null}}function d(){const e=i.default.totalmem();return{podMemoryLimitMB:Math.floor(e/1048576),source:"system-memory"}}},9499:(e,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.UserErrorLogs=r.HudNoMessageInSqsConsumerEmit=r.HudNoErrorInSqsConsumerEmit=r.HudNoEventTypeInSqsConsumerEmit=r.HudFailExtractSqsQueueName=r.HudNoCallbackInSqsConsumerOn=r.HudNoEventTypeInSqsConsumerOn=r.HudNoQueueUrlInSqsConsumer=r.HudSqsError=r.HudExtensionNextFailedError=r.HudExtensionRegisterError=r.HudExtnensionError=r.HudBadLoggerError=r.HudInitNetworkError=r.HudTsNodeNotFoundButUsed=r.HudSessionThrottle=r.HudNoTranspileOnlyError=r.HudClientExceededMaxRetries=r.HudClientUnauthorizedError=r.HudTimeoutError=r.HudWorkloadCollectorError=r.HudAssert=r.HudUnsupportedError=r.HudEditError=r.HudWorkerError=r.HudClientError=r.HudInitError=r.HudError=void 0,r.isAbortError=function(e){return e instanceof Error&&"AbortError"===e.name},r.getFirstError=function(){return u},r.setFirstError=function(e){e&&u===a&&(u=e)},r.getNetworkError=function(e){return{ECONNABORTED:r.UserErrorLogs.InitFailedDueNetworkTimeout(),ECONNREFUSED:r.UserErrorLogs.InitFailedDueNetworkRST(),ENOTFOUND:r.UserErrorLogs.InitFailedDueDnsFailed(),SELF_SIGNED_CERT_IN_CHAIN:r.UserErrorLogs.InitFailedDueSelfSignedCert(),ERR_BAD_RESPONSE:r.UserErrorLogs.InitFailedDueBackendError()}[e]??r.UserErrorLogs.InitFailedDueGenericNetworkError()};class o extends Error{code=9e3;name=this.constructor.name;constructor(e){super(e)}}r.HudError=o;class t extends o{code=9001}r.HudInitError=t,r.HudClientError=class extends o{code=9002;originalAxiosErrorCode;constructor(e,r){super(e),this.originalAxiosErrorCode=r}},r.HudWorkerError=class extends o{code=9003};class n extends o{code=9004}r.HudEditError=n,r.HudUnsupportedError=class extends n{code=9005},r.HudAssert=class extends n{code=9006},r.HudWorkloadCollectorError=class extends o{code=9007},r.HudTimeoutError=class extends o{code=9008},r.HudClientUnauthorizedError=class extends o{code=9009},r.HudClientExceededMaxRetries=class extends o{code=9010},r.HudNoTranspileOnlyError=class extends o{code=9011},r.HudSessionThrottle=class extends t{code=9012},r.HudTsNodeNotFoundButUsed=class extends o{code=9013},r.HudInitNetworkError=class extends o{code=9014;originalAxiosErrorCode;constructor(e,r){super(e),this.originalAxiosErrorCode=r}},r.HudBadLoggerError=class extends o{code=9101};class i extends o{code=9200}r.HudExtnensionError=i,r.HudExtensionRegisterError=class extends i{code=9201},r.HudExtensionNextFailedError=class extends i{code=9202};class s extends o{code=9250}r.HudSqsError=s,r.HudNoQueueUrlInSqsConsumer=class extends s{code=9251},r.HudNoEventTypeInSqsConsumerOn=class extends s{code=9252},r.HudNoCallbackInSqsConsumerOn=class extends s{code=9253},r.HudFailExtractSqsQueueName=class extends s{code=9254},r.HudNoEventTypeInSqsConsumerEmit=class extends s{code=9255},r.HudNoErrorInSqsConsumerEmit=class extends s{code=9256},r.HudNoMessageInSqsConsumerEmit=class extends s{code=9257};const a=9999;let u=a;r.UserErrorLogs={HudServiceNotSet:()=>({level:"error",errCode:"E1001",moreInfo:!0,message:"Can't load Hud, HUD_SERVICE was not set. Please set service name using the environment variable HUD_SERVICE."}),HudServiceInvalid:()=>({level:"error",errCode:"E1002",moreInfo:!0,message:"Can't load Hud, HUD_SERVICE value has invalid service name. Please set service name using the environment variable HUD_SERVICE."}),HudApiKeyNotSet:()=>({level:"error",errCode:"E1004",moreInfo:!0,message:"Can't load Hud, HUD_KEY was not set. Please set API key using the environment variable HUD_KEY."}),HudApiKeyInvalid:()=>({level:"error",errCode:"E1005",moreInfo:!0,message:"Can't load Hud, HUD_KEY value has invalid API key. Please set a valid key in environment variable HUD_KEY."}),HudSessionOptionsInvalid:e=>({level:"warn",errCode:"E1006",moreInfo:!0,message:`Options parameter is not a valid object, defaulting to empty options. Reason: ${JSON.stringify(JSON.parse(e))}.`}),BothApiKeyAndServiceNotSet:()=>({level:"error",errCode:"E1007",moreInfo:!0,message:"Can't load Hud, HUD_KEY and HUD_SERVICE were not set. Please set API key using the environment variable HUD_KEY and service name using the environment variable HUD_SERVICE."}),SessionOptionsSessionTagsWithDots:()=>({level:"warn",errCode:"E1008",moreInfo:!0,message:"Options.tags object keys can't contain dots; they have been replaced with underscores."}),ApiKeyDenied:e=>({level:"error",errCode:"E1011",moreInfo:!0,message:`Can't load Hud, the provided key is invalid. Please provide a valid HUD_KEY in your ${{ENV:"environment variable",CONFIG_FILE:"file",CONFIG_ENV:"HUD_CONFIG",INIT:"init function",SETUP:"setup function"}[e]}.`}),ShutdownGracefully:e=>({level:"error",errCode:`E${e}`,message:"SDK has initiated a graceful shutdown. Your application remains unaffected"}),UnsupportedNodeVersion:()=>({level:"error",errCode:"E1012",moreInfo:!0,message:"Can't load Hud due to an unsupported node version."}),UnsupportedSyntax:()=>({level:"error",errCode:"E1014",moreInfo:!0,message:"Can't load Hud due to an unsupported syntax version."}),UnsupportedLambdaMemory:e=>({level:"error",errCode:"E1015",moreInfo:!0,message:`Can't load Hud as lambda function memory size is less than ${e}MB.`}),JSONErrorInUserConfig:(e,r)=>({level:"error",errCode:"E1016",moreInfo:!0,message:`Can't load Hud, the config file contains an invalid JSON. Please set a valid json in Hud's config ${e}`+(r?`, Error: ${r}.`:".")}),ZodErrorInUserConfig:(e,r)=>({level:"error",errCode:"E1017",moreInfo:!0,message:`Can't load Hud, the config file contains an invalid value for field: ${r}. Please set a valid value for ${r} in the config ${e}.`}),ConfigInaccessible:e=>({level:"error",errCode:"E1018",moreInfo:!0,message:`Can't load Hud, the config file is inaccessible. Please make sure your node application has read permissions to the Hud config file, ${e}.`}),SetupCalledWithoutKey:()=>({level:"error",errCode:"E1019",moreInfo:!0,message:"API key not found or invalid. SDK has initiated a graceful shutdown. Your application remains unaffected."}),SetupCalledWithoutService:()=>({level:"error",errCode:"E1020",moreInfo:!0,message:"Service name parameter not found or invalid. SDK has initiated a graceful shutdown. Your application remains unaffected."}),HudEnableIsFalse:()=>({level:"warn",errCode:"E1021",moreInfo:!0,message:"HUD_ENABLE is set to false. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InstrumentedFunctionCountExceeded:e=>({level:"error",errCode:"E1022",moreInfo:!0,message:`SDK limit of ${e} instrumented functions exceeded. SDK has initiated a graceful shutdown. Your application remains unaffected.`}),PodMemoryLimitTooLow:e=>({level:"error",errCode:"E1023",moreInfo:!0,message:`Insufficient memory available. Minimum required:(${e}MB). SDK has initiated a graceful shutdown. Your application remains unaffected.`}),DebuggerAttached:()=>({level:"error",errCode:"E1024",message:"Did not load as debugger is attached."}),InitSessionBeforeRegister:()=>({level:"error",errCode:"E1025",moreInfo:!0,message:"register() was not called, or called after initSession() - please call register() before initSession() and run again. Your application continues normally without Hud."}),RegisterMisplacedNoDeclarations:()=>({level:"warn",errCode:"E1026",moreInfo:!0,message:"Warning - No code has been mapped so far. This probably means register() was called too late — after your code was already loaded. Move it to the top of your entry file to enable proper mapping. Your application continues normally without Hud data."}),UnsupportedFrameworkVersion:e=>({level:"warn",errCode:"E1029",message:`Warning - Unsupported version of ${e} framework(s). This means Hud won't track your framework invocations. Your application continues normally, but with partial Hud data. See the compatibility matrix for details: https://docs.hud.io/docs/hud-sdk-compatibility-matrix-for-node#/`}),UninstrumentedFilesLogThresholdExceeded:e=>({level:"warn",errCode:"E1027",message:`Warning - ${e} of your code files were imported before register(). This means Hud won't track all of your functions. Please move register() call to an earlier location. To view the list of files use register({verbose: true}). Your application continues normally, but with partial Hud data.`,moreInfo:!0}),UninstrumentedFrameworks:e=>({level:"warn",errCode:"E1028",message:`Warning - The framework(s): ${e.map(e=>`"${e}"`).join(", ")} was imported before register(). This means Hud won't track your framework invocations. Please move register() call to an earlier location. Your application continues normally, but with partial Hud data.`}),YesInstrumentationNoMetrics:()=>({level:"warn",errCode:"E1032",moreInfo:!0,message:"Warning - Code mapped successfully, but no function activity was tracked. Make sure your service is running and actively handling requests."}),HudEnableNotSet:e=>({level:"error",moreInfo:!0,message:`Did not load as HUD_ENABLE is ${void 0===e?"undefined":"set to a non-true value"}. Please set HUD_ENABLE=true to run Hud.`}),LambdaNotViaLayer:()=>({level:"error",errCode:"E1034",message:"Can't load Hud, lambda support is currently in beta. Contact Hud to get early access."}),RunningInBun:()=>({level:"error",errCode:"E1035",message:"Hud does not support Bun yet. The SDK has initiated a graceful shutdown. Your application remains unaffected. See the compatibility matrix for details: https://docs.hud.io/docs/hud-sdk-compatibility-matrix-for-node"}),RunningOnWindows:()=>({level:"error",errCode:"E1036",message:"Hud does not support Windows yet. The SDK has initiated a graceful shutdown. Your application remains unaffected. See the compatibility matrix for details: https://docs.hud.io/docs/hud-sdk-compatibility-matrix-for-node"}),UnsupportedNativeBuild:()=>({level:"error",errCode:"E1037",message:"Hud does not support this platform yet. The SDK has initiated a graceful shutdown. Your application remains unaffected. See the compatibility matrix for details: https://docs.hud.io/docs/hud-sdk-compatibility-matrix-for-node"}),TsNodeNotTranspileOnly:()=>({level:"error",errCode:"E1038",message:"detected ts-node is used without the transpileOnly flag, which is not supported yet. SDK has initiated a graceful shutdown. Your application remains unaffected.",moreInfo:!0}),TsNodeNotFoundEvenThoughRunWithTsNode:()=>({level:"error",errCode:"E1039",message:"'ts-node' was detected but could not be resolved by Hud. This may happen if 'ts-node' is installed globally. Try installing it locally in your project. The SDK has initiated a graceful shutdown. Your application remains unaffected.",moreInfo:!0}),InitFailedDueGenericNetworkError:()=>({level:"error",moreInfo:!0,errCode:"E1040",message:"A network error occurred during SDK initialization. Please check your internet connection and try again. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InitFailedDueNetworkTimeout:()=>({level:"error",moreInfo:!0,errCode:"E1041",message:"The SDK failed to connect to Hud's backend due to a timeout during SDK initialization. Please verify your firewall settings to ensure outbound connections are allowed. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InitFailedDueNetworkRST:()=>({level:"error",moreInfo:!0,errCode:"E1042",message:"The SDK connection to Hud's backend was reset unexpectedly (RST) during SDK initialization. Please check your firewall or network security settings. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InitFailedDueSelfSignedCert:()=>({level:"error",moreInfo:!0,errCode:"E1043",message:"SSL certificate verification failed during SDK initialization. If your organization uses a self-signed certificate, set the NODE_EXTRA_CA_CERTS environment variable to the path of your CA certificate file. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InitFailedDueDnsFailed:()=>({level:"error",moreInfo:!0,errCode:"E1044",message:"The SDK failed to resolve DNS when attempting to connect to Hud's backend during SDK initialization. If the problem persists, please contact support. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InitFailedDueBackendError:()=>({level:"error",moreInfo:!0,errCode:"E1045",message:"The SDK was unable to complete initialization due to a temporary issue with Hud's backend. SDK has initiated a graceful shutdown. Your application remains unaffected."}),InitTimeout:e=>({moreInfo:!0,level:"error",message:`SDK imported but not initialized. Please ensure to call '${e?"hud.initSession(KEY, SERVICE)":"hud.init()"}' to initialize the SDK.`}),RehookCalledBeforeRegister:()=>({level:"error",errCode:"E1046",moreInfo:!0,message:"register() was not called, or called after rehook() - please call register() before rehook() and run again. Your application continues normally with partial hud data."}),EsbuildSourceMapFound:()=>({level:"error",errCode:"E1047",message:"Source maps were detected for files modified by the Esbuild plugin, which is not yet supported. SDK has initiated a graceful shutdown. Your application remains unaffected."}),EsbuildMissingKey:()=>({level:"error",errCode:"ES0001",moreInfo:!0,message:"missing HUD_KEY, skipping Hud plugin, your build is unaffected."}),EsbuildFailedProcessingFile:e=>({level:"error",errCode:"ES0002",moreInfo:!0,message:`failed processing file "${e}", reverting to original loader.`}),EsbuildFailedBundling:()=>({level:"error",errCode:"ES0003",moreInfo:!0,message:"encountered unexpected file bundling, build aborted."}),EsbuildFailedParsingSourcemap:()=>({level:"error",errCode:"ES0004",moreInfo:!0,message:"failed parsing source maps, skipping upload, Hud will run without source maps."}),EsbuildFailedUploadingSourcemap:e=>({level:"error",errCode:"ES0005",moreInfo:!0,message:`failed uploading source map: ${e}, Hud will run without source maps.`}),EsbuildFailedUploadingSourcemapUnauthorized:()=>({level:"error",errCode:"ES0006",moreInfo:!0,message:"failed uploading source map: unauthorized, Hud will run without source maps."}),EsbuildUnsupportedPlatform:()=>({level:"error",errCode:"ES0007",message:'Can\'t load Hud, as our esbuild plugin supports "node" mode only. Your app remains unaffected. For more information visit docs.hud.io/docs/support-matrix'}),NextDevNotSupported:()=>({level:"error",moreInfo:!0,errCode:"NX0001",message:"Next.js dev server is not supported. Please use 'next start' instead."}),SourceMapCleanupFailed:()=>({level:"error",moreInfo:!0,errCode:"NX0002",message:"Source maps cleanup failed. Build stopped to prevent unintentional inclusion of source maps."}),WebpackFailedUploadingSourcemap:()=>({level:"error",errCode:"NX0003",moreInfo:!0,message:"Failed uploading source maps, Hud will run without source maps."}),NextJsPluginNotUsed:()=>({level:"warn",errCode:"NX0004",message:"Next.js support is in closed beta. Request access at: https://docs.hud.io/docs/support"}),EsbuildUnsupportedWindows:()=>({level:"error",errCode:"ES0008",message:"Can't load Hud, as our esbuild plugin does not supports windows. Your app remains unaffected. For more information visit docs.hud.io/docs/support-matrix"}),EsbuildSourceMapInline:()=>({level:"error",errCode:"ES0009",message:"detected sourcemap is used as 'inline' or 'both', which is not supported yet. SDK has initiated a graceful shutdown. Your application remains unaffected."}),HudCliInvalidKey:()=>({level:"error",errCode:"CI1001",moreInfo:!0,message:"Initialization failed - the provided API key is invalid. Instrumentation has been disabled."}),HudCliNoJsFiles:()=>({level:"error",errCode:"CI1002",moreInfo:!0,message:"No JavaScript files found in the specified directories. Instrumentation aborted."}),HudCliAllFilesInstrumented:()=>({level:"warn",errCode:"CI1003",moreInfo:!0,message:"All files in the specified directory are already instrumented. No further action taken."}),HudCliSomeFilesInstrumented:()=>({level:"warn",errCode:"CI1004",moreInfo:!0,message:"Detected that some files are already instrumented. Skipping re-instrumentation for these files."}),HudCliUnkownError:()=>({level:"error",errCode:"CI1005",moreInfo:!0,message:"An unexpected error occurred during instrumentation. Instrumentation process aborted."}),HudCliInstrumentedFunctionCountExceeded:e=>({level:"error",errCode:"CI1006",moreInfo:!0,message:`CI limit of ${e} instrumented functions exceeded. Instrumentation has been halted. Your source files remain unchanged.`}),HudCliUploadFailed:()=>({level:"warn",errCode:"CI1007",moreInfo:!0,message:"Failed to upload code mapping. Existing functions will continue to report, but new or updated ones won't be tracked."}),HudCliInvalidDirectory:e=>({level:"error",errCode:"CI1008",moreInfo:!0,message:`Provided directory does not exist: ${e}. Instrumentation aborted.`}),SetContextBeforeRegister:()=>({level:"warn",errCode:"E1101",message:"Warning - setContext() was called before register(). Please call register() before setContext()."}),SetContextNoAsyncContext:()=>({level:"warn",errCode:"E1103",message:"Warning - setContext() was called outside of an endpoint flow and was skipped. Make sure setContext() is only called within a registered endpoint handler."}),SetContextMaxKeysExceeded:()=>({level:"warn",errCode:"E1104",message:"Warning - A maximum of 20 context keys is allowed. Additional keys were ignored. Pass fewer than 20 keys to setContext()."}),SetContextKeyIsNotString:e=>({level:"warn",errCode:"E1105",message:`Warning - Context key "${e}" must be a string. This entry was skipped. Only string keys are supported in setContext().`}),SetContextKeyTooLong:e=>({level:"warn",errCode:"E1106",message:`Warning - Context key "${e}" exceeds the 64-character limit and was skipped. Shorten the key to 64 characters or fewer.`}),SetContextEmptyArray:e=>({level:"warn",errCode:"E1107",message:`Warning - Context key "${e}" is an empty array and was skipped. Use a non-empty array.`}),SetContextArrayTooLong:e=>({level:"warn",errCode:"E1108",message:`Warning - A maximum of 20 items is allowed in array "${e}". Additional items were ignored. Trim the array to 20 items or fewer.`}),SetContextArrayAllItemsInvalid:e=>({level:"warn",errCode:"E1109",message:`Warning - Context key "${e}" is invalid. All items in the array are unsupported. Entry was skipped. Use an array containing only strings, numbers, or booleans.`}),SetContextValueIsNotPrimitive:e=>({level:"warn",errCode:"E1110",message:`Warning - Value for ${e} must be a primitive or an array of primitives. Entry was skipped. Use a string, number, boolean, or an array of these types.`}),SetContextValueIsUndefinedOrNull:e=>({level:"warn",errCode:"E1111",message:`Warning - Value for ${e} is undefined or null. Entry was skipped. Provide a defined primitive value or a non-empty array.`}),SetContextValueIsTooLong:e=>({level:"warn",errCode:"E1112",message:`Warning - Value for ${e} exceeds the 256-character limit. Entry was skipped. Shorten the value to 256 characters or fewer.`}),SetContextValueIsEmptyString:e=>({level:"error",errCode:"E1113",message:`Warning - Context key ${e} is invalid. Key must be non-empty. Entry was skipped. Use a non-empty string as the key.`}),SetContextValueIsNotFiniteNumber:e=>({level:"error",errCode:"E1114",message:`Warning - Value for ${e} is invalid. Must be a finite number. Entry was skipped. Use a numeric value that is not Infinity or NaN.`})}},9525:(e,r,o)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.generateEndpointFlowId=function(e,r){return(0,t.v5)(`${e.toString()}|${Array.from(r).sort().join(",")}`,n)},r.generateGraphqlFlowId=function(e,r){return(0,t.v5)(`${e}|${r}`,n)},r.generateKafkaFlowId=function(e,r,o){return(0,t.v5)(`${e.toString()}|${r}|${o}`,n)},r.generateSqsFlowId=function(e,r,o=""){const i=`${e}|${r}|${o}`;return(0,t.v5)(i,n)};const t=o(3903),n="fa79d8b7-069c-4bbf-9c00-34bfc8b3a5a6"},9896:e=>{e.exports=require("fs")}},r={};return function o(t){var n=r[t];if(void 0!==n)return n.exports;var i=r[t]={exports:{}};return e[t].call(i.exports,i,i.exports,o),i.exports}(5070)})());
2
2
  //# sourceMappingURL=lib.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 o=t();for(var n in o)("object"==typeof exports?exports:e)[n]=o[n]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},857:e=>{e.exports=require("os")},1638:e=>{e.exports=require("./declarations")},1886:function(e,t,o){var n,r=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),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||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[t.length]=o);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o=n(e),a=0;a<o.length;a++)"default"!==o[a]&&r(t,e,o[a]);return i(t,e),t}),s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const c=a(o(9896)),l=o(8167),g=o(5809),d=o(2546),u=a(o(523)),f=o(523),m=o(8528),p=o(2546),w=o(4672),h=o(8269),k=o(2546),y=o(6982),_=o(6261),v=s(o(6928)),b=o(4678),C=o(6304),x=l.parentPort,S=l.workerData.apiKey,M=l.workerData.service,F=l.workerData.startTime,D=l.workerData.tags,E=l.workerData.lambdaExtensionId,I=l.workerData.shouldCreateDeclaraionWorker;let L,T=new AbortController,O=!1,R=!1;const A=p.safeCall.bind(p.safeCall,f.worker_logger);if(g.hudConfig.userConfig=l.workerData.userConfig,f.worker_logger.info("Worker started"),null===x)throw new p.HudWorkerError("Failed to get port");const W=new Set;let P;E&&(P=new _.EventEmitter,P.setMaxListeners(0),A((0,k.extensionMainLoop)(E,P))),x.postMessage({msg:"started"}),(0,p.setSentEventsCountInterval)();const q=new w.HudClient(P);function N(){O||(O=!0,u.customer_logger.log(d.UserLogs.FirstDecalarationSent()),R&&u.customer_logger.log(d.UserLogs.HappyFlowCompleted()))}async function K(e,t,n,r){if(0!==e.length)for(const i of e)try{if(r&&(0,_.once)(r,"eventloop"),f.worker_logger.debug("Sending file to parser worker",{filename:i.filename}),n){n.postMessage({msg:"SourceFileMetadata",content:i});continue}const{filename:e,indexOffset:s,indexOffsetEnd:c}=i,l=await(0,p.readFile)(e,s,c);if(!l)continue;const{parseDeclarations:g}=await Promise.resolve().then(()=>a(o(1638))),d=await g(i,l,void 0,L);await j(d,t),d.declarations.length>0&&N()}catch(e){f.worker_logger.error("Failed to parse declarations",{filename:i.filename,error:e})}else N()}async function j(e,t){e.blacklist&&e.blacklist.uuids.length>0&&(x?.postMessage(m.KeepAliveMessage),e.blacklist.uuids.forEach(e=>{W.add(e)}),await t.batch("CorruptedFile",[e.blacklist],{event_version:"1.0.0"}));for(let o=0;o<e.declarations.length;o+=g.hudConfig.communicationBatchSize)x?.postMessage(m.KeepAliveMessage),await t.batch("FunctionDeclaration",e.declarations.slice(o,o+g.hudConfig.communicationBatchSize),{event_version:m.FUNCTION_DECLARATION_VERSION})}function U(e){return`investigation-${e?.context?.timestamp??Date.now()}-${(0,y.randomUUID)()}.json`}async function B(e,t){await c.promises.writeFile(v.default.join(t.path,U(e)),JSON.stringify(e,null,2))}async function H(e,t,o,n={}){for(let r=0;r<e.length;r+=g.hudConfig.communicationBatchSize)x?.postMessage(m.KeepAliveMessage),await o.batch(t,e.slice(r,r+g.hudConfig.communicationBatchSize),n)}q.initSession(S,M,F,D).then(async e=>{q.setSession(e);const{sessionId:t}=e;f.worker_logger.info("Initialized successfuly",{sessionId:t});const o=m.HudSessionInitStatus.success;x.postMessage({msg:"initialized",content:{status:o}}),await async function(e){if(null===x)throw new p.HudWorkerError("Failed to get port");const t=await e.getRemoteConfig();return t?(f.worker_logger.info("Remote configuration exists"),g.hudConfig.dynamicConfig=(0,g.updateDynamicConfig)(t,g.hudConfig,f.worker_logger),f.worker_logger.info("Current dynamic configuration:",{currentDynamicConfig:g.hudConfig.dynamicConfig})):f.worker_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:g.hudConfig.dynamicConfig}),x.postMessage({msg:"initDynamicConfig",content:t}),t}(q);try{await async function(e,t){if(null===x)throw new p.HudWorkerError("Failed to get port");const o=I?function(e,t){const o=p.myRequire.resolve(`${g.SDK_MODULE_NAME}/declarationWorker`),n=new l.Worker(o);return n.unref(),n.on("message",o=>{"eventlooptime"!==o?A(j(o,e)):t&&(0,_.once)(t,"eventloop")}),n.on("error",e=>{f.worker_logger.error("Declaration parser worker failed",{msg:e instanceof Error?e.message:void 0})}),n.on("exit",e=>{f.worker_logger.warn("Declaration parser worker exited",{code:e})}),n}(e,t):void 0;x.on("message",n=>{const{msg:r,content:i}=n;switch(f.worker_logger.debug("Got message from main thread",{msg:r}),r){case"Terminate":A(async function(e,t){const o=process.hrtime();f.worker_logger.warn("Notified to terminate. flushing.",{grace:e.grace}),await G(e.logBuffers,t),await $({filenames:e.logFiles},t),await G((0,f.getSavedLogs)(),t),await $({filenames:Array.from(z())},t),await J();const n=process.hrtime(o),r=1e3*n[0]+n[1]/1e6;f.worker_logger.info("Done flushing. responsing to parent",{grace:e.grace,termination_time_ms:r}),x?.postMessage({msg:"terminated"}),x?.close()}(i,e));break;case"StartPeriodicTasks":A(async function(e){A((0,b.loopWorkloadDataCollector)(e,g.hudConfig.workloadMetadata,g.hudConfig.workloadMetadata.sendInterval,T.signal)),A((0,p.loopLogProcessPerformance)(f.worker_logger,g.hudConfig.logPerfInterval,T.signal)),A((0,p.loopLogThreadPerformance)(f.worker_logger,g.hudConfig.logPerfInterval,T.signal)),A(async function(e,t,o){for await(const n of(0,p.unrefSetInterval)(t,void 0,{signal:o.signal})){x?.postMessage(m.KeepAliveMessage);const t=(0,f.getSavedLogs)();await G(t,e)}}(e,g.hudConfig.logsSendInterval,T))}(e));break;case"Abort":A(J());break;case"Invocations":A(async function(e,t,o){const n=e;f.worker_logger.debug("Got invocations message",{msg:t,size:e.length});const r=n.filter(e=>!W.has(e.function_id));for(let e=0;e<r.length;e+=g.hudConfig.communicationBatchSize)x?.postMessage(m.KeepAliveMessage),await o.batch("Invocations",r.slice(e,e+g.hudConfig.communicationBatchSize),{event_version:"1.0.1"});R||(R=!0,u.customer_logger.log(d.UserLogs.FirstInvocationSent()),O&&u.customer_logger.log(d.UserLogs.HappyFlowCompleted()))}(i,r,e));break;case"FlowMetrics":A(async function(e,t,o){const{aggregatedMetrics:n}=e;f.worker_logger.debug("Got aggregated flow metrics message",{msg:t,size:Object.keys(n).length}),x?.postMessage(m.KeepAliveMessage);for(const e in n){const{eventVersion:t,metrics:r}=n[e];if(0!==r.length)for(let n=0;n<r.length;n+=g.hudConfig.communicationBatchSize)x?.postMessage(m.KeepAliveMessage),await o.batch(e,r.slice(n,n+g.hudConfig.communicationBatchSize),t?{event_version:t}:{})}}(i,r,e));break;case"ProcessedFiles":A(async function(e,t,o,n){if("true"===process.env.HUD_SKIP_DECLS)return f.worker_logger.debug("Skipping file declarations"),void await K([],t,o,n);if("true"===process.env.HUD_FORCE_ALL_DECLS)return f.worker_logger.debug("Forcing all file declarations"),void await K(e,t,o,n);try{const r=await(0,p.getFilesForDeclarations)(e,t.sendFileDeclarations.bind(t));await K(r,t,o,n)}catch{return f.worker_logger.error("Failed to send file declarations, parsing all files"),void await K(e,t,o,n)}}(i,e,o,t));break;case"GetMode":A(async function(e,t){const{runningMode:o}=e,n=await t.getMode({runningMode:o});x?.postMessage({msg:"GetMode",content:{mode:n}})}(i,e));break;case"EndpointDeclaration":A(async function(e,t,o){for(let n=0;n<e.length;n+=g.hudConfig.communicationBatchSize)x?.postMessage(m.KeepAliveMessage),await o.batch(t,e.slice(n,n+g.hudConfig.communicationBatchSize),{event_version:"1.0.2"})}(i,r,e));break;case"Runtime":case"PreInitLoadedModules":case"PostInitLoadedModules":case"PatchedModules":A(async function(e,t,o){x?.postMessage(m.KeepAliveMessage),await o.send(t,e)}(i,r,e));break;case"GraphQLResolvers":case"GraphQLDocuments":case"KafkaJSTopics":A(H(i,r,e));break;case"SqsQueue":A(H(i,r,e,{event_version:"1.0.1"}));break;case"StaticNextJsEndpoints":A(async function(e,t){const o=JSON.parse(e.NextConfig),n=await(0,h.extractNextEndpointDeclarations)(o);await H(n,"EndpointDeclaration",t)}(i,e));break;case"Investigations":A(async function(e,t){const o=g.hudConfig.investigation.store,n=[];for(const r of e)try{const e=(0,C.createRegexes)(g.hudConfig.dynamicConfig.censorshipRegexes),i={...(0,C.censorInvestigation)(r,{valueRegexToRedact:e,keysToRedact:g.hudConfig.dynamicConfig.blacklistParams,whitelistNestedFields:g.hudConfig.dynamicConfig.forensicsWhitelistFields,blacklistNestedFields:g.hudConfig.dynamicConfig.forensicsBlacklistFields}),version:g.hudConfig.investigation.objectVersion};if("disk"===o.type)await B(i,o);else if("s3"===o.type){const e=U(i),o=await t.storeObject(e,Buffer.from(JSON.stringify(i)));if(!o){f.worker_logger.error("Failed to store investigation",{investigationSaveName:e});continue}if(!r.context){f.worker_logger.error("Investigation has no context, even though it should");continue}const a={version:g.hudConfig.investigation.objectVersion,flow_type:r.context.type,flow_uuid:"sqs"===r.context.type?r.context.flow_id:r.context.endpoint_uuid,s3_pointer:o,timestamp:r.context.timestamp,exceptions:r.exceptions.map(e=>({name:e.name,functions:e.executionFlow.map(e=>e.function_id)}))};n.push(a)}}catch(e){f.worker_logger.error("Failed to save investigation",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}n.length>0&&await t.batch("FlowInvestigation",n)}(i,e));break;case"LogFilename":A($(i,e));break;case"Logs":A(async function(e,t){x?.postMessage(m.KeepAliveMessage),await t.logs(e.logs)}(i,e));break;case"TsNodeConfig":L=i.tsConfig,o&&o.postMessage({msg:"TsNodeConfig",content:{tsOptions:L}});break;case"Reingest":A(async function(e,t){for(const o of e){N();try{await t.triggerReingest(o)}catch(e){f.worker_logger.error("Failed to trigger reingest",{buildId:o,error:e})}}}(i,e));break;default:f.worker_logger.error("Unknown command",{msg:r})}})}(q,P)}catch(e){f.worker_logger.error("CRITICAL: Worker's main failed",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}).catch(e=>{if(e instanceof p.HudSessionThrottle)return f.worker_logger.info("Session throttled, exiting worker"),void x.postMessage({msg:"throttled"});if(e instanceof p.HudClientError)return f.worker_logger.error("Posting network error to main thread",{message:e.message,originalMessage:e.originalAxiosErrorCode}),void x.postMessage({msg:"networkError",content:{message:e.message,originalMessage:e.originalAxiosErrorCode}});throw f.worker_logger.error("Failed initiating session, exiting worker",{msg:e.message,stack:e.stack}),e});const z=(0,p.suppressTraces)(f.renewFileTransports);async function $(e,t){for(const o of e.filenames)x?.postMessage(m.KeepAliveMessage),await t.logs(c.readFileSync(o,{encoding:"utf-8"})),g.hudConfig.deleteLogsAfterSending&&c.unlinkSync(o);const o=z();for(const e of o)x?.postMessage(m.KeepAliveMessage),await t.logs(c.readFileSync(e,{encoding:"utf-8"})),g.hudConfig.deleteLogsAfterSending&&c.unlinkSync(e)}async function G(e,t){const o=e.join("\n");o.length>0&&await t.logs(o)}async function J(){T.abort(),T=new AbortController}},2546:e=>{e.exports=require("./lib")},4672:e=>{e.exports=require("./client")},4678:function(e,t,o){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.loopWorkloadDataCollector=async function(e,t,o,n){try{const i=new l(e,t),a=await i.getWorkloadData();await r(i,a);for await(const e of(0,s.unrefSetInterval)(o,void 0,{signal:n}))await r(i,a)}catch(e){(0,s.isAbortError)(e)||c.worker_logger.error("Failed collecting workload metadata",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}async function r(e,t){try{await e.send(t)}catch(e){c.worker_logger.error("Failed to send workload metadata, skipping",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}};const r=n(o(8938)),i=o(9896),a=n(o(857)),s=o(2546),c=o(523);class l{client;config;constructor(e,t){this.client=e,this.config=t}getOperatingSystem(){return a.default.platform()}isKubernetesPod(){return!!process.env.KUBERNETES_SERVICE_HOST}getFileContentSilentFail(e){try{return(0,i.readFileSync)(e,"utf8")}catch{return c.worker_logger.debug(`Could not read file ${e}`),null}}getKubernetesWorkloadData(){if("linux"!==this.getOperatingSystem())return c.worker_logger.info("Kubernetes workload data is only available on Linux, current OS is "+this.getOperatingSystem()),null;if(!this.isKubernetesPod())return null;const e=a.default.hostname(),t=this.getFileContentSilentFail(this.config.kubernetes.namespaceFile),o=this.getFileContentSilentFail(this.config.kubernetes.uuidFile),n=(0,s.getCpuLimit)(c.worker_logger),r=(0,s.getPodMemoryLimit)(c.worker_logger),i=null!==r.podMemoryLimitMB?r.podMemoryLimitMB.toString():null;return{product_uuid:o?.trim()||null,pod_name:e.trim(),pod_namespace:t?.trim()||null,pod_memory_limit:i?.trim()||null,pod_cpu_limit:n?.toString()||null}}async getLocalAWSWorkloadData(){const e=(0,i.readFileSync)(this.config.aws.metadataFile,"utf8"),t=JSON.parse(e),o=t.ds.dynamic["instance-identity"].document;return{workload_id:o.instanceId,workload_instance_type:o.instanceType,region:o.region,ami_id:o.imageId,launched_date:o.pendingTime,life_cycle:t.ds["meta-data"]["instance-life-cycle"]}}async getIMDSWorkloadData(){let e;try{e=await(0,s.suppressTraces)(async()=>await r.default.put(`${this.config.aws.imds.baseURL}${this.config.aws.imds.tokenURI}`,{},{timeout:this.config.aws.imds.requestTimeout,headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}}))()}catch(e){throw new s.HudWorkloadCollectorError(`Could not retrieve instance metadata token: ${e}`)}const t={"X-aws-ec2-metadata-token":e.data};let o;try{o=await(0,s.suppressTraces)(async()=>await r.default.get(`${this.config.aws.imds.baseURL}${this.config.aws.imds.identityURI}`,{timeout:this.config.aws.imds.requestTimeout,headers:t}))()}catch(e){throw new s.HudWorkloadCollectorError(`Could not retrieve instance identity document: ${e}`)}const n=o.data;let i;try{i=await(0,s.suppressTraces)(async()=>await r.default.get(`${this.config.aws.imds.baseURL}${this.config.aws.imds.lifeCycleURI}`,{timeout:this.config.aws.imds.requestTimeout,headers:t}))()}catch(e){throw new s.HudWorkloadCollectorError(`Could not retrieve instance life cycle: ${e}`)}const a=i.data;return{workload_id:n.instanceId,workload_instance_type:n.instanceType,region:n.region,ami_id:n.imageId,launched_date:n.pendingTime,life_cycle:a}}async getAWSWorkloadData(){try{return await this.getLocalAWSWorkloadData()}catch(e){c.worker_logger.info("Failed to get workload metadata from local file",{msg:e.message})}try{return await this.getIMDSWorkloadData()}catch(e){c.worker_logger.info("Failed to get workload metadata from IMDS",{msg:e.message})}return null}async getWorkloadData(){return{aws_workload_data:await this.getAWSWorkloadData(),kubernetes_workload_data:this.getKubernetesWorkloadData()}}async send(e){c.worker_logger.info("Sending workload metadata to the server",{msg:e}),await this.client.send("WorkloadData",e)}}},5809:e=>{e.exports=require("./config")},6261:e=>{e.exports=require("events")},6304:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createRegexes=function(e){return e.map(e=>({regex:new RegExp(e.regex,"g"),replacement:e.replacement}))},t.censorInvestigation=function(e,t){const o=e.context?function(e,t,o){const n={system_info:e?.system_info,machine_metrics:e?.machine_metrics,observability_identifiers:e?.observability_identifiers};if("http"===e.type)return{...n,...r(e,t,o)};if("sqs"===e.type)return{...n,...i(e,t,o)};throw new Error(`Unknown context type: ${e}`)}(e.context,t.valueRegexToRedact,t.keysToRedact):void 0;let s={status:e.status,context:o,exceptions:e.exceptions.map(e=>({name:e.name,message:e.message?a(e.message,t.valueRegexToRedact):void 0,stackTrace:e.stackTrace,executionFlow:e.executionFlow})),...e.userContext?{userContext:e.userContext}:{}};return t.whitelistNestedFields.length>0&&(s=(0,n.pickDeep)(s,t.whitelistNestedFields)),t.blacklistNestedFields.length>0&&(s=(0,n.omitDeep)(s,t.blacklistNestedFields)),s};const n=o(2546);function r(e,t,o){return{type:e.type,endpoint_uuid:e.endpoint_uuid,status_code:e.status_code,route:a(e?.route,t),params:s(e?.params,t,o),query:s(e?.query,t,o),request_body:s(e?.request_body,t,o),method:e?.method,timestamp:e?.timestamp,extra_headers:e.extra_headers??{}}}function i(e,t,o){return{type:e.type,flow_id:e.flow_id,messages:s(e.messages,t,o),timestamp:e.timestamp}}function a(e,t){for(const o of t)e=e.replace(o.regex,o.replacement);return e}function s(e,t,o){if("string"==typeof e)return a(e,t);if("object"==typeof e&&null!==e)for(const n in e)o.includes(n)?e[n]="[REDACTED]":e[n]=s(e[n],t,o);return e}},6928:e=>{e.exports=require("path")},6982:e=>{e.exports=require("crypto")},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")},8938:e=>{e.exports=require("axios")},9896:e=>{e.exports=require("fs")}},t={};return function o(n){var r=t[n];if(void 0!==r)return r.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,o),i.exports}(1886)})());
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 n in o)("object"==typeof exports?exports:e)[n]=o[n]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},857:e=>{e.exports=require("os")},1638:e=>{e.exports=require("./declarations")},1886:function(e,t,o){var n,r=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),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||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[t.length]=o);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o=n(e),a=0;a<o.length;a++)"default"!==o[a]&&r(t,e,o[a]);return i(t,e),t}),s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const c=a(o(9896)),l=o(8167),g=o(5809),d=o(2546),u=a(o(523)),f=o(523),m=o(8528),p=o(2546),w=o(4672),h=o(8269),k=o(2546),y=o(6982),_=o(6261),v=s(o(6928)),b=o(4678),C=o(6304),x=l.parentPort,S=l.workerData.apiKey,M=l.workerData.service,F=l.workerData.startTime,D=l.workerData.tags,E=l.workerData.lambdaExtensionId,I=l.workerData.shouldCreateDeclaraionWorker;let L,T=new AbortController,A=!1,O=!1;const R=p.safeCall.bind(p.safeCall,f.worker_logger);if(g.hudConfig.userConfig=l.workerData.userConfig,f.worker_logger.info("Worker started"),null===x)throw new p.HudWorkerError("Failed to get port");const W=new Set;let P;E&&(P=new _.EventEmitter,P.setMaxListeners(0),R((0,k.extensionMainLoop)(E,P))),x.postMessage({msg:"started"}),(0,p.setSentEventsCountInterval)();const q=new w.HudClient(P);function N(){A||(A=!0,u.customer_logger.log(d.UserLogs.FirstDecalarationSent()),O&&u.customer_logger.log(d.UserLogs.HappyFlowCompleted()))}async function K(e,t,n,r){if(0!==e.length)for(const i of e)try{if(r&&(0,_.once)(r,"eventloop"),f.worker_logger.debug("Sending file to parser worker",{filename:i.filename}),n){n.postMessage({msg:"SourceFileMetadata",content:i});continue}const{filename:e,indexOffset:s,indexOffsetEnd:c}=i,l=await(0,p.readFile)(e,s,c);if(!l)continue;const{parseDeclarations:g}=await Promise.resolve().then(()=>a(o(1638))),d=await g(i,l,void 0,L);await j(d,t),d.declarations.length>0&&N()}catch(e){f.worker_logger.error("Failed to parse declarations",{filename:i.filename,error:e})}else N()}async function j(e,t){e.blacklist&&e.blacklist.uuids.length>0&&(x?.postMessage(m.KeepAliveMessage),e.blacklist.uuids.forEach(e=>{W.add(e)}),await t.batch("CorruptedFile",[e.blacklist],{event_version:"1.0.0"}));for(let o=0;o<e.declarations.length;o+=g.hudConfig.communicationBatchSize)x?.postMessage(m.KeepAliveMessage),await t.batch("FunctionDeclaration",e.declarations.slice(o,o+g.hudConfig.communicationBatchSize),{event_version:m.FUNCTION_DECLARATION_VERSION})}function U(e){return`investigation-${e?.context?.timestamp??Date.now()}-${(0,y.randomUUID)()}.json`}async function B(e,t){await c.promises.writeFile(v.default.join(t.path,U(e)),JSON.stringify(e,null,2))}async function H(e,t,o,n={}){for(let r=0;r<e.length;r+=g.hudConfig.communicationBatchSize)x?.postMessage(m.KeepAliveMessage),await o.batch(t,e.slice(r,r+g.hudConfig.communicationBatchSize),n)}async function z(e,t,o){x?.postMessage(m.KeepAliveMessage),await o.send(t,e)}q.initSession(S,M,F,D).then(async e=>{q.setSession(e);const{sessionId:t}=e;f.worker_logger.info("Initialized successfuly",{sessionId:t});const o=m.HudSessionInitStatus.success;x.postMessage({msg:"initialized",content:{status:o}}),await async function(e){if(null===x)throw new p.HudWorkerError("Failed to get port");const t=await e.getRemoteConfig();return t?(f.worker_logger.info("Remote configuration exists"),g.hudConfig.dynamicConfig=(0,g.updateDynamicConfig)(t,g.hudConfig,f.worker_logger),f.worker_logger.info("Current dynamic configuration:",{currentDynamicConfig:g.hudConfig.dynamicConfig})):f.worker_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:g.hudConfig.dynamicConfig}),x.postMessage({msg:"initDynamicConfig",content:t}),t}(q);try{await async function(e,t){if(null===x)throw new p.HudWorkerError("Failed to get port");const o=I?function(e,t){const o=p.myRequire.resolve(`${g.SDK_MODULE_NAME}/declarationWorker`),n=new l.Worker(o);return n.unref(),n.on("message",o=>{"eventlooptime"!==o?R(j(o,e)):t&&(0,_.once)(t,"eventloop")}),n.on("error",e=>{f.worker_logger.error("Declaration parser worker failed",{msg:e instanceof Error?e.message:void 0})}),n.on("exit",e=>{f.worker_logger.warn("Declaration parser worker exited",{code:e})}),n}(e,t):void 0;x.on("message",n=>{const{msg:r,content:i}=n;switch(f.worker_logger.debug("Got message from main thread",{msg:r}),r){case"Terminate":R(async function(e,t){const o=process.hrtime();f.worker_logger.warn("Notified to terminate. flushing.",{grace:e.grace}),await J(e.logBuffers,t),await G({filenames:e.logFiles},t),await J((0,f.getSavedLogs)(),t),await G({filenames:Array.from($())},t),await V();const n=process.hrtime(o),r=1e3*n[0]+n[1]/1e6;f.worker_logger.info("Done flushing. responsing to parent",{grace:e.grace,termination_time_ms:r}),x?.postMessage({msg:"terminated"}),x?.close()}(i,e));break;case"StartPeriodicTasks":R(async function(e){R((0,b.loopWorkloadDataCollector)(e,g.hudConfig.workloadMetadata,g.hudConfig.workloadMetadata.sendInterval,T.signal)),R((0,p.loopLogProcessPerformance)(f.worker_logger,g.hudConfig.logPerfInterval,T.signal)),R((0,p.loopLogThreadPerformance)(f.worker_logger,g.hudConfig.logPerfInterval,T.signal)),R(async function(e,t,o){for await(const n of(0,p.unrefSetInterval)(t,void 0,{signal:o.signal})){x?.postMessage(m.KeepAliveMessage);const t=(0,f.getSavedLogs)();await J(t,e)}}(e,g.hudConfig.logsSendInterval,T)),R(async function(e){const t=await(0,k.getAllModules)(v.default.resolve("."));await z({modules:t},"InstalledModules",e)}(e))}(e));break;case"Abort":R(V());break;case"Invocations":R(async function(e,t,o){const n=e;f.worker_logger.debug("Got invocations message",{msg:t,size:e.length});const r=n.filter(e=>!W.has(e.function_id));for(let e=0;e<r.length;e+=g.hudConfig.communicationBatchSize)x?.postMessage(m.KeepAliveMessage),await o.batch("Invocations",r.slice(e,e+g.hudConfig.communicationBatchSize),{event_version:"1.0.1"});O||(O=!0,u.customer_logger.log(d.UserLogs.FirstInvocationSent()),A&&u.customer_logger.log(d.UserLogs.HappyFlowCompleted()))}(i,r,e));break;case"FlowMetrics":R(async function(e,t,o){const{aggregatedMetrics:n}=e;f.worker_logger.debug("Got aggregated flow metrics message",{msg:t,size:Object.keys(n).length}),x?.postMessage(m.KeepAliveMessage);for(const e in n){const{eventVersion:t,metrics:r}=n[e];if(0!==r.length)for(let n=0;n<r.length;n+=g.hudConfig.communicationBatchSize)x?.postMessage(m.KeepAliveMessage),await o.batch(e,r.slice(n,n+g.hudConfig.communicationBatchSize),t?{event_version:t}:{})}}(i,r,e));break;case"ProcessedFiles":R(async function(e,t,o,n){if("true"===process.env.HUD_SKIP_DECLS)return f.worker_logger.debug("Skipping file declarations"),void await K([],t,o,n);if("true"===process.env.HUD_FORCE_ALL_DECLS)return f.worker_logger.debug("Forcing all file declarations"),void await K(e,t,o,n);try{const r=await(0,p.getFilesForDeclarations)(e,t.sendFileDeclarations.bind(t));await K(r,t,o,n)}catch{return f.worker_logger.error("Failed to send file declarations, parsing all files"),void await K(e,t,o,n)}}(i,e,o,t));break;case"GetMode":R(async function(e,t){const{runningMode:o}=e,n=await t.getMode({runningMode:o});x?.postMessage({msg:"GetMode",content:{mode:n}})}(i,e));break;case"EndpointDeclaration":R(async function(e,t,o){for(let n=0;n<e.length;n+=g.hudConfig.communicationBatchSize)x?.postMessage(m.KeepAliveMessage),await o.batch(t,e.slice(n,n+g.hudConfig.communicationBatchSize),{event_version:"1.0.2"})}(i,r,e));break;case"Runtime":case"PreInitLoadedModules":case"PostInitLoadedModules":case"PatchedModules":R(z(i,r,e));break;case"GraphQLResolvers":case"GraphQLDocuments":case"KafkaJSTopics":R(H(i,r,e));break;case"SqsQueue":R(H(i,r,e,{event_version:"1.0.1"}));break;case"StaticNextJsEndpoints":R(async function(e,t){const o=JSON.parse(e.NextConfig),n=await(0,h.extractNextEndpointDeclarations)(o);await H(n,"EndpointDeclaration",t)}(i,e));break;case"Investigations":R(async function(e,t){const o=g.hudConfig.investigation.store,n=[];for(const r of e)try{const e=(0,C.createRegexes)(g.hudConfig.dynamicConfig.censorshipRegexes),i={...(0,C.censorInvestigation)(r,{valueRegexToRedact:e,keysToRedact:g.hudConfig.dynamicConfig.blacklistParams,whitelistNestedFields:g.hudConfig.dynamicConfig.forensicsWhitelistFields,blacklistNestedFields:g.hudConfig.dynamicConfig.forensicsBlacklistFields}),version:g.hudConfig.investigation.objectVersion};if("disk"===o.type)await B(i,o);else if("s3"===o.type){const e=U(i),o=await t.storeObject(e,Buffer.from(JSON.stringify(i)));if(!o){f.worker_logger.error("Failed to store investigation",{investigationSaveName:e});continue}if(!r.context){f.worker_logger.error("Investigation has no context, even though it should");continue}const a={version:g.hudConfig.investigation.objectVersion,flow_type:r.context.type,flow_uuid:"sqs"===r.context.type?r.context.flow_id:r.context.endpoint_uuid,s3_pointer:o,timestamp:r.context.timestamp,exceptions:r.exceptions.map(e=>({name:e.name,functions:e.executionFlow.map(e=>e.function_id)}))};n.push(a)}}catch(e){f.worker_logger.error("Failed to save investigation",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}n.length>0&&await t.batch("FlowInvestigation",n)}(i,e));break;case"LogFilename":R(G(i,e));break;case"Logs":R(async function(e,t){x?.postMessage(m.KeepAliveMessage),await t.logs(e.logs)}(i,e));break;case"TsNodeConfig":L=i.tsConfig,o&&o.postMessage({msg:"TsNodeConfig",content:{tsOptions:L}});break;case"Reingest":R(async function(e,t){for(const o of e){N();try{await t.triggerReingest(o)}catch(e){f.worker_logger.error("Failed to trigger reingest",{buildId:o,error:e})}}}(i,e));break;default:f.worker_logger.error("Unknown command",{msg:r})}})}(q,P)}catch(e){f.worker_logger.error("CRITICAL: Worker's main failed",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}).catch(e=>{if(e instanceof p.HudSessionThrottle)return f.worker_logger.info("Session throttled, exiting worker"),void x.postMessage({msg:"throttled"});if(e instanceof p.HudClientError)return f.worker_logger.error("Posting network error to main thread",{message:e.message,originalMessage:e.originalAxiosErrorCode}),void x.postMessage({msg:"networkError",content:{message:e.message,originalMessage:e.originalAxiosErrorCode}});throw f.worker_logger.error("Failed initiating session, exiting worker",{msg:e.message,stack:e.stack}),e});const $=(0,p.suppressTraces)(f.renewFileTransports);async function G(e,t){for(const o of e.filenames)x?.postMessage(m.KeepAliveMessage),await t.logs(c.readFileSync(o,{encoding:"utf-8"})),g.hudConfig.deleteLogsAfterSending&&c.unlinkSync(o);const o=$();for(const e of o)x?.postMessage(m.KeepAliveMessage),await t.logs(c.readFileSync(e,{encoding:"utf-8"})),g.hudConfig.deleteLogsAfterSending&&c.unlinkSync(e)}async function J(e,t){const o=e.join("\n");o.length>0&&await t.logs(o)}async function V(){T.abort(),T=new AbortController}},2546:e=>{e.exports=require("./lib")},4672:e=>{e.exports=require("./client")},4678:function(e,t,o){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.loopWorkloadDataCollector=async function(e,t,o,n){try{const i=new l(e,t),a=await i.getWorkloadData();await r(i,a);for await(const e of(0,s.unrefSetInterval)(o,void 0,{signal:n}))await r(i,a)}catch(e){(0,s.isAbortError)(e)||c.worker_logger.error("Failed collecting workload metadata",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}async function r(e,t){try{await e.send(t)}catch(e){c.worker_logger.error("Failed to send workload metadata, skipping",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}};const r=n(o(8938)),i=o(9896),a=n(o(857)),s=o(2546),c=o(523);class l{client;config;constructor(e,t){this.client=e,this.config=t}getOperatingSystem(){return a.default.platform()}isKubernetesPod(){return!!process.env.KUBERNETES_SERVICE_HOST}getFileContentSilentFail(e){try{return(0,i.readFileSync)(e,"utf8")}catch{return c.worker_logger.debug(`Could not read file ${e}`),null}}getKubernetesWorkloadData(){if("linux"!==this.getOperatingSystem())return c.worker_logger.info("Kubernetes workload data is only available on Linux, current OS is "+this.getOperatingSystem()),null;if(!this.isKubernetesPod())return null;const e=a.default.hostname(),t=this.getFileContentSilentFail(this.config.kubernetes.namespaceFile),o=this.getFileContentSilentFail(this.config.kubernetes.uuidFile),n=(0,s.getCpuLimit)(c.worker_logger),r=(0,s.getPodMemoryLimit)(c.worker_logger),i=null!==r.podMemoryLimitMB?r.podMemoryLimitMB.toString():null;return{product_uuid:o?.trim()||null,pod_name:e.trim(),pod_namespace:t?.trim()||null,pod_memory_limit:i?.trim()||null,pod_cpu_limit:n?.toString()||null}}async getLocalAWSWorkloadData(){const e=(0,i.readFileSync)(this.config.aws.metadataFile,"utf8"),t=JSON.parse(e),o=t.ds.dynamic["instance-identity"].document;return{workload_id:o.instanceId,workload_instance_type:o.instanceType,region:o.region,ami_id:o.imageId,launched_date:o.pendingTime,life_cycle:t.ds["meta-data"]["instance-life-cycle"]}}async getIMDSWorkloadData(){let e;try{e=await(0,s.suppressTraces)(async()=>await r.default.put(`${this.config.aws.imds.baseURL}${this.config.aws.imds.tokenURI}`,{},{timeout:this.config.aws.imds.requestTimeout,headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}}))()}catch(e){throw new s.HudWorkloadCollectorError(`Could not retrieve instance metadata token: ${e}`)}const t={"X-aws-ec2-metadata-token":e.data};let o;try{o=await(0,s.suppressTraces)(async()=>await r.default.get(`${this.config.aws.imds.baseURL}${this.config.aws.imds.identityURI}`,{timeout:this.config.aws.imds.requestTimeout,headers:t}))()}catch(e){throw new s.HudWorkloadCollectorError(`Could not retrieve instance identity document: ${e}`)}const n=o.data;let i;try{i=await(0,s.suppressTraces)(async()=>await r.default.get(`${this.config.aws.imds.baseURL}${this.config.aws.imds.lifeCycleURI}`,{timeout:this.config.aws.imds.requestTimeout,headers:t}))()}catch(e){throw new s.HudWorkloadCollectorError(`Could not retrieve instance life cycle: ${e}`)}const a=i.data;return{workload_id:n.instanceId,workload_instance_type:n.instanceType,region:n.region,ami_id:n.imageId,launched_date:n.pendingTime,life_cycle:a}}async getAWSWorkloadData(){try{return await this.getLocalAWSWorkloadData()}catch(e){c.worker_logger.info("Failed to get workload metadata from local file",{msg:e.message})}try{return await this.getIMDSWorkloadData()}catch(e){c.worker_logger.info("Failed to get workload metadata from IMDS",{msg:e.message})}return null}async getWorkloadData(){return{aws_workload_data:await this.getAWSWorkloadData(),kubernetes_workload_data:this.getKubernetesWorkloadData()}}async send(e){c.worker_logger.info("Sending workload metadata to the server",{msg:e}),await this.client.send("WorkloadData",e)}}},5809:e=>{e.exports=require("./config")},6261:e=>{e.exports=require("events")},6304:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createRegexes=function(e){return e.map(e=>({regex:new RegExp(e.regex,"g"),replacement:e.replacement}))},t.censorInvestigation=function(e,t){const o=e.context?function(e,t,o){const n={system_info:e?.system_info,machine_metrics:e?.machine_metrics,observability_identifiers:e?.observability_identifiers};if("http"===e.type)return{...n,...r(e,t,o)};if("sqs"===e.type)return{...n,...i(e,t,o)};throw new Error(`Unknown context type: ${e}`)}(e.context,t.valueRegexToRedact,t.keysToRedact):void 0;let s={status:e.status,context:o,exceptions:e.exceptions.map(e=>({name:e.name,message:e.message?a(e.message,t.valueRegexToRedact):void 0,stackTrace:e.stackTrace,executionFlow:e.executionFlow})),...e.userContext?{userContext:e.userContext}:{}};return t.whitelistNestedFields.length>0&&(s=(0,n.pickDeep)(s,t.whitelistNestedFields)),t.blacklistNestedFields.length>0&&(s=(0,n.omitDeep)(s,t.blacklistNestedFields)),s};const n=o(2546);function r(e,t,o){return{type:e.type,endpoint_uuid:e.endpoint_uuid,status_code:e.status_code,route:a(e?.route,t),params:s(e?.params,t,o),query:s(e?.query,t,o),request_body:s(e?.request_body,t,o),method:e?.method,timestamp:e?.timestamp,extra_headers:e.extra_headers??{}}}function i(e,t,o){return{type:e.type,flow_id:e.flow_id,messages:s(e.messages,t,o),timestamp:e.timestamp}}function a(e,t){for(const o of t)e=e.replace(o.regex,o.replacement);return e}function s(e,t,o){if("string"==typeof e)return a(e,t);if("object"==typeof e&&null!==e)for(const n in e)o.includes(n)?e[n]="[REDACTED]":e[n]=s(e[n],t,o);return e}},6928:e=>{e.exports=require("path")},6982:e=>{e.exports=require("crypto")},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")},8938:e=>{e.exports=require("axios")},9896:e=>{e.exports=require("fs")}},t={};return function o(n){var r=t[n];if(void 0!==r)return r.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,o),i.exports}(1886)})());
2
2
  //# sourceMappingURL=worker.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hud-sdk",
3
- "version": "1.6.23",
3
+ "version": "1.6.24",
4
4
  "description": "Hud's Node SDK",
5
5
  "homepage": "https://www.hud.io/",
6
6
  "keywords": [
@@ -195,6 +195,7 @@
195
195
  "kafkajs": "^2.2.4",
196
196
  "koa": "^2.15.3",
197
197
  "koa-router": "^12.0.1",
198
+ "memfs": "^4.36.0",
198
199
  "npm-run-all": "^4.1.5",
199
200
  "prettier": "3.2.5",
200
201
  "prettier-plugin-organize-imports": "^4.1.0",