hud-sdk
Version:
Hud's Node SDK
2 lines • 25.3 kB
JavaScript
!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),p=r(2546),m=r(7274),v=r(2702),w=r(8269),k=r(2546),y=r(6281),C=r(2546),b=r(6261),_=a.app_logger,E=p.safeCall.bind(p.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 p.HudClientUnauthorizedError).code&&a.customer_logger.log(p.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,p.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 p.HudTimeoutError))throw i;r=await this.getMessageFromWorker(t,e/2,!1)}if(!r)throw new p.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 p.HudTimeoutError))throw i;t=await this.getMessageFromWorker(r,e/10,!1)}if("throttled"===t?.msg)throw new p.HudSessionThrottle;if("networkError"===t?.msg)throw _.error("networkError",{error:t.content.error}),new p.HudInitNetworkError(t.content.message,t.content.originalMessage);if(!t||"initialized"!==t?.msg||void 0===t?.content)throw new p.HudInitError("Worker not initialized successfully");if(t?.content.status!==l.HudSessionInitStatus.success)throw new p.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.periodicSendInvocations()),E(this.periodicSendProcessedFiles()),E(this.periodicSendEndpoints()),E(this.periodicSendLazyEndpoints()),E(this.periodicSendFlowMetrics()),E(this.periodicSendGarphQL()),E(this.periodicSendKafkaJS()),E(this.periodicSendSqs()),E(this.sendStaticNextJsEndpointsOnce()),E(this.periodicSendInvestigations()),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,p.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 p.HudTimeoutError}catch(e){if(!(0,p.isAbortError)(e))throw(0,p.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,m.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 periodicSendInvocations(){const e=new h.SketchManager(c.hudConfig.huddBinWidth),t=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,r=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,r,t=>{const r=(0,m.prepCalls)(t,e);return this._sendArray("Invocations",r),!0},"periodicSendInvocations")}async periodicSendFlowMetrics(){const e=c.hudConfig.dynamicConfig.flowMetricFirstSendTimeout,t=c.hudConfig.dynamicConfig.flowMetricInterval;await this.setupPeriodicTask(e,t,e=>{const t=(0,f.getFlowMetrics)(e);return Object.keys(t).length>0&&this._sendObject("FlowMetrics",{aggregatedMetrics:t}),!0},"periodicSendFlowMetrics")}async periodicSendGarphQL(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendGraphQLResolvers(),this.sendGraphQLDocuments(),!0),"periodicSendGarphQL")}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 periodicSendInvestigations(){const e=c.hudConfig.dynamicConfig.aggregationInterval;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{const e=(0,w.getClosedInvestigations)();this._sendArray("Investigations",e)}catch(e){_.error("Failed sending Investigations to worker, skipping",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}sendGraphQLResolvers(){try{const e=(0,w.getResolversDeclarations)().map(e=>({id:e.id,operation:e.operation,name:e.name}));this._sendArray("GraphQLResolvers",e)}catch(e){_.error("Failed sending resolvers to worker, skipping",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}sendGraphQLDocuments(){try{const e=(0,w.getDocumentsMetadata)().map(e=>({name:e.name,hash:e.hash,selection_names:e.selectionNames,time_took:e.timeTook}));this._sendArray("GraphQLDocuments",e)}catch(e){_.error("Failed sending documents to worker, skipping",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}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 p.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 p.HudError&&(0,p.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)})());
//# sourceMappingURL=core.js.map