hud-sdk 1.6.7 → 1.6.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/core.js +1 -1
- package/dist/cjs/declarationWorker.js +1 -1
- package/dist/cjs/dto.js +1 -1
- package/dist/cjs/esbuildPlugin.js +1 -1
- package/dist/cjs/globalstate.js +1 -1
- package/dist/cjs/instrument.js +1 -1
- package/dist/cjs/lib.js +1 -1
- package/dist/cjs/on_init.js +1 -1
- package/dist/cjs/on_require.js +1 -1
- package/dist/cjs/on_setup.js +1 -1
- package/dist/cjs/worker.js +1 -1
- package/dist/cjs/wrap.js +1 -1
- package/dist/native/hud-native.darwin-arm64.node +0 -0
- package/dist/native/hud-native.darwin-x64.node +0 -0
- package/dist/native/hud-native.linux-arm64-gnu.node +0 -0
- package/dist/native/hud-native.linux-arm64-musl.node +0 -0
- package/dist/native/hud-native.linux-x64-gnu.node +0 -0
- package/dist/native/hud-native.linux-x64-musl.node +0 -0
- package/dist/native/hud-native.win32-x64-msvc.node +0 -0
- package/dist/native/index.d.ts +2 -0
- package/package.json +2 -3
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 o in r)("object"==typeof exports?exports:e)[o]=r[o]}}(global,(()=>(()=>{"use strict";var e={2546:e=>{e.exports=require("./lib")},2702:function(e,t,r){var o=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,i)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&o(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const s=n(r(2546)),a=r(8528),d=s.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!==a.KeepAliveMessage.msg)return;this._restartTimeout()}catch(e){d.error("Error in keepalive",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_restartTimeout(){const e=setTimeout((()=>{}),this.keepaliveGrace);clearTimeout(this.timeoutId),this.timeoutId=e}start(){this.stop(),this.worker.on("message",this.eventHandler).unref()}stop(){void 0!==this.timeoutId&&clearTimeout(this.timeoutId),this.worker.off("message",this.eventHandler),this.timeoutId=void 0}}},5119:function(e,t,r){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.init=void 0;const i=o(r(6281));t.init=i.default},5994:function(e,t,r){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainThread=void 0;const i=r(8167),n=r(2546),s=r(6281),a=o(r(7320));function d(){globalThis.hudDeclarationsFound&&(n.app_logger.warn("Found Declarations but no metrics"),n.customer_logger.log(n.UserErrorLogs.YesDeclarationsNoMetrics()))}t.MainThread=class{apiKey;service;startTime;messenger;constructor(e,t,r){this.apiKey=e,this.service=t,this.startTime=r}startFailed(e){e instanceof n.HudSessionThrottle?(n.customer_logger.info(n.UserLogs.InitIdleMode()),(0,s._detachAndTerminate)(!1,!1)):e instanceof n.HudInitNetworkError&&e.originalAxiosErrorCode?(n.customer_logger.log((0,n.getNetworkError)(e.originalAxiosErrorCode)),(0,s._detachAndTerminate)(!1,!1)):(n.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,s._detachAndTerminate)())}async start(){if(i.isMainThread)if(this.messenger=await this._createMessenger(),this.messenger.runningInsideLambda)this._start().catch(this.startFailed);else try{await this._start()}catch(e){throw this.startFailed(e),e}}async _start(){if(!this.messenger)throw new n.HudInitError("Messenger not initialized");try{await this.messenger.checkWorkerInitialized(n.hudConfig.workerTimeout),await this._initDynamicConfig(),globalThis.hudMetricsIndicator=setTimeout(d,n.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof n.HudSessionThrottle)throw e;throw n.app_logger.error("Failed to starting worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(){const e=n.myRequire.resolve(`${n.SDK_MODULE_NAME}/worker`),t={...process.env};delete t.NODE_OPTIONS;const r=new i.Worker(e,{workerData:{apiKey:this.apiKey,service:this.service,startTime:this.startTime,shouldRunLambdaExtension:globalThis.hudRuningInsideLambda,shouldCreateDeclaraionWorker:globalThis.hudRuningInsideLambda,userConfig:n.hudConfig.userConfig},execArgv:[],env:t});let o;try{o=new a.default(r),await o.checkWorker(n.hudConfig.workerTimeout)}catch(e){if(e instanceof n.HudSessionThrottle)throw n.app_logger.info("Worker started in idle mode - session throttled"),e;throw n.app_logger.error("Worker failed to start",{msg:e instanceof Error?e.message:void 0}),e}finally{r.unref()}return o}async _initDynamicConfig(){const e=await(this.messenger?.getRemoteConfig());e?(n.app_logger.info("Remote configuration exists"),n.hudConfig.dynamicConfig=(0,n.updateDynamicConfig)(e,n.hudConfig,n.app_logger),(0,n.updateInvestigationRateLimitGlobals)(),n.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:n.hudConfig.dynamicConfig})):n.app_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:n.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._detachAndTerminate=t.isValidParam=void 0;const o=r(2546),i=r(5994),n=r(2546),s=r(8528),a=r(8269),d=r(2546),c=r(7274);let l;t.default=async function(e,t){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void o.app_logger.warn("Already ran init!");if(globalThis.hudRunMutex=!0,(0,a.clearInitGuard)(),!o.app_logger.isValid())return(0,d.setFirstError)((new d.HudBadLoggerError).code),void u(!0,!0);(0,n.updateUserConfigFromInit)(e,t);const r=(0,a.validateAndGetUserInput)();if(!r)return;if(globalThis.hudRunningMode!==s.HudRunningMode.enabled)return;o.app_logger.info("Initializing hud",{userConfig:Object.entries(n.hudConfig.userConfig).filter((([e,t])=>"DEFAULT"!==t.source))}),l=new i.MainThread(r.apiKey,r.service,globalThis.hudStartTime),await l.start(),o.customer_logger.log(d.UserLogs.HudInitSuccess()),l.messenger&&(0,d.safeCall)(o.app_logger,l.messenger.handleLogsTask())}catch(e){try{if(e instanceof d.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(e){o.app_logger.error("Something went wrong in init & e.stack raised an exception")}u()}},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e};let g=!1;function u(e=!0,t=!1){(0,a.detachHud)(e,t),l&&(0,d.safeCall)(o.app_logger,l.terminateMessenger()),globalThis.hudExtensionId&&!g&&(g=!0,(0,d.safeCall)(o.app_logger,(0,o.nextLoopDummy)(globalThis.hudExtensionId))),(0,a.clearUserIndicatorsTimeouts)(),(0,c.resetCallers)()}t._detachAndTerminate=u},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resetCallers=t.prepCalls=t._liftExceptions=void 0;const o=r(8269),i=r(2546);function n(e){const t={};for(const r in e)t[r]=[{count:e[r]}];return t}t._liftExceptions=n,t.prepCalls=function(e,t){const r=(new Date).toISOString(),s=[];return Object.entries(hudCalls).map((([o,a])=>{Object.entries(a).forEach((([a,d])=>{Object.entries(d).forEach((([d,c])=>{try{if(0===c.sampledCount)return;const i={function_id:o,wrapped_flow_id:d||void 0,wrapped_caller_id:a||void 0,timestamp:r,timeslice:e,exceptions:n(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};s.push(i),function(e){e.lastSentCounter=e.count,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(c)}catch(e){i.app_logger.error("Failed preparing invocation, skipping",{func:o,wrappedCaller:a,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}))}))})),s.length>0&&globalThis.hudDeclarationsFound&&(0,o.clearMetricsIndicator)(),s},t.resetCallers=function(){for(const t in globalThis.hudCalls)for(const r in globalThis.hudCalls[t])for(const o in globalThis.hudCalls[t][r])(e=globalThis.hudCalls[t][r][o]).lastSentCounter-=e.count,e.count=0;var e}},7320:function(e,t,r){var o=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,i)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&o(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0});const s=n(r(2546)),a=n(r(6460)),d=r(2546),c=r(8528),l=r(2546),g=r(7131),u=r(8269),h=r(2546),f=r(7274),m=r(2702),p=r(8269),v=r(2546),k=r(6281),w=r(2546),y=r(6261),C=s.app_logger,b=h.safeCall.bind(h.safeCall,C);t.default=class{worker;runningInsideLambda=!1;tsNodeUpdated=!1;abortController;workerKeepaliveGuard;constructor(e){this.worker=e,this.abortController=new AbortController,(0,y.setMaxListeners)(20,this.abortController.signal),this.worker.on("error",this.handleWorkerError).unref(),this.workerKeepaliveGuard=new m.WorkerKeepaliveGuard(e,d.hudConfig.communicationKeepaliveGrace),this._updateTsNodeConfig()&&C.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new h.HudClientUnauthorizedError).code&&s.customer_logger.log(h.UserErrorLogs.ApiKeyDenied(d.hudConfig.userConfig.key?.source)),C.error("Error from worker, stopping hud",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,h.setFirstError)(e?.code),this.stop(),(0,k._detachAndTerminate)()}catch(e){C.error("Error stopping hud",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};stop(){this.abortWorker(),d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.abortController.abort(),this.abortController=new AbortController,(0,u.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),C.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=["startedNoExtension","extensionRegistered"];let r;try{r=await this.getMessageFromWorker(t,e,!0)}catch(o){if(!(o instanceof h.HudTimeoutError))throw o;r=await this.getMessageFromWorker(t,e/2,!1)}if(!r)throw new h.HudInitError("Worker not started");return"extensionRegistered"===r.msg&&(this.runningInsideLambda=!0,globalThis.hudExtensionId=r.content.extensionId),r}async checkWorkerInitialized(e){let t;const r=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(r,e,!0)}catch(o){if(!(o instanceof h.HudTimeoutError))throw o;t=await this.getMessageFromWorker(r,e/10,!1)}if("throttled"===t?.msg)throw new h.HudSessionThrottle;if("networkError"===t?.msg)throw C.error("networkError",{error:t.content.error}),new h.HudInitNetworkError(t.content.message,t.content.originalMessage);if(!t||"initialized"!==t?.msg||void 0===t?.content)throw new h.HudInitError("Worker not initialized successfully");if(t?.content.status!==c.HudSessionInitStatus.success)throw new h.HudInitError("Worker not initialized successfully");return t}async start(){switch(d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case c.HudRunningMode.enabled:C.info("Enabled mode"),b(this.getMode()),b(this.startPeriodicTasks()),b(this.periodicSendInvocations()),b(this.periodicSendProcessedFiles()),b(this.periodicSendEndpoints()),b(this.periodicSendFlowMetrics()),b(this.periodicSendGarphQL()),b(this.periodicSendKafkaJS()),b(this.periodicSendSqs()),b(this.periodicSendInvestigations()),b(this.resetCallerCounters()),b(this.periodicResetGlobalInvestigationCounter()),b(this.periodicResetInvestigationDedupingCache()),b(this.sendLogsPeriodically(d.hudConfig.logsSendInterval)),b(this.sendRuntime()),b(this.sendPatchedModules()),b(this.sendPreloadedModules()),b(this.dumpModulesAfterWhile(6e4)),b((0,h.loopLogThreadPerformance)(C,d.hudConfig.logPerfInterval,this.abortController.signal));break;case c.HudRunningMode.disabled:C.info("Disabled mode"),b(this.getMode());break;case c.HudRunningMode.detached:C.info("Detached"),(0,k._detachAndTerminate)(!1,!1),this.stop();break;default:C.error("Running mode not handled")}}async getMessageFromWorker(e,t,r=!1,o){let i;e=Array.isArray(e)?e:[e];const n=new AbortController,s=()=>{n.abort()};this.abortController.signal.addEventListener("abort",s);const d=a.setTimeout(t,void 0,{signal:n.signal,ref:r}),c=t=>{try{e.includes(t.msg)&&(i=t,n.abort(),C.info("Received message from worker (canceling timeout)",t))}catch(e){C.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(),o&&this.worker.postMessage(o);try{throw await d,C.warn("Timeout waiting for message from worker"),new h.HudTimeoutError}catch(e){if(!(0,h.isAbortError)(e))throw(0,h.setFirstError)(e.code),e}finally{this.abortController.signal.removeEventListener("abort",s),this.worker.off("message",c)}return i}async getMode(){for await(const e of(0,l.unrefSetInterval)(d.hudConfig.modeInterval,void 0,{signal:this.abortController.signal}))try{const e={msg:"GetMode",content:{startTime:globalThis.hudStartTime,runningMode:globalThis.hudRunningMode}},t=await this.getMessageFromWorker(e.msg,d.hudConfig.workerMessageTimeout,!1,e);if(t?.msg!==e.msg||void 0===t?.content.mode){C.error("Unexpected message from worker",t);continue}t.content.mode!==globalThis.hudRunningMode&&await this.restart(t?.content.mode)}catch(e){C.error("Failed getting mode from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async getRemoteConfig(){const e="initDynamicConfig";try{const t=await this.getMessageFromWorker(e,d.hudConfig.workerMessageTimeout,!0);if(t?.msg!==e||void 0===t?.content)throw new Error(`Unexpected message from worker: ${t}`);return t?.content}catch(e){C.error("Failed getting remote configuration from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async resetCallerCounters(){const e=d.hudConfig.callerResetInterval;for await(const t of(0,l.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{C.info("Resetting caller",{interval:e}),(0,f.resetCallers)()}catch(e){C.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=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;let r=!0;await this.setupPeriodicTask(e,t,(()=>{if(r){r=!1;try{this._updateTsNodeConfig()&&C.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 g.SketchManager(d.hudConfig.huddBinWidth),t=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,r=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,r,(t=>{const r=(0,f.prepCalls)(t,e);return this._sendArray("Invocations",r),!0}),"periodicSendInvocations")}async periodicSendFlowMetrics(){const e=d.hudConfig.dynamicConfig.flowMetricFirstSendTimeout,t=d.hudConfig.dynamicConfig.flowMetricInterval;await this.setupPeriodicTask(e,t,(e=>{const t=(0,u.getFlowMetrics)();return t.length>0&&this._sendObject("FlowMetrics",{timeslice:e,rawMetrics:t}),!0}),"periodicSendFlowMetrics")}async periodicSendGarphQL(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,(()=>(this.sendGraphQLResolvers(),this.sendGraphQLDocuments(),!0)),"periodicSendGarphQL")}async periodicSendKafkaJS(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,(()=>{const e=(0,p.getKafkaJSTopics)();return this._sendArray("KafkaJSTopics",e),!0}),"periodicSendKafkaJS")}async periodicSendSqs(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,(()=>{const e=(0,p.getSqsQueues)();return e.length>0&&this._sendArray("SqsQueue",e),!0}),"periodicSendSqs")}async periodicSendInvestigations(){const e=d.hudConfig.dynamicConfig.aggregationInterval;for await(const t of(0,l.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{const e=(0,p.getClosedInvestigations)();this._sendArray("Investigations",e)}catch(e){C.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,p.getResolversDeclarations)().map((e=>({id:e.id,operation:e.operation,name:e.name})));this._sendArray("GraphQLResolvers",e)}catch(e){C.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,p.getDocumentsMetadata)().map((e=>({name:e.name,hash:e.hash,selection_names:e.selectionNames,time_took:e.timeTook})));this._sendArray("GraphQLDocuments",e)}catch(e){C.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=d.hudConfig.endpointsFirstSendWaitTime,t=d.hudConfig.endpointsInterval;await this.setupPeriodicTask(e,t,(()=>(this.sendEndpoints(),!0)),"periodicSendEndpoints")}sendEndpoints(){const e=(0,p.getExpressEndpointDeclarations)(),t=(0,u.getKoaEndpointDeclarationsFromStorage)(),r=e.concat(t).map((e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path})));this._sendArray("EndpointDeclaration",r)}async terminateWorker(){try{const e=(0,v.suppressTraces)(s.renewFileTransports),t=s.getSavedLogs(),r=e();await this.getMessageFromWorker("terminated",d.hudConfig.workerGrace,!1,{msg:"Terminate",content:{grace:d.hudConfig.workerGrace,logBuffers:t,logFiles:Array.from(r)}})}catch(e){if(!(e instanceof h.HudTimeoutError))throw C.error("Unexpected error, terminating worker"),await this.worker.terminate(),e;C.error("Grace period timeout, terminating worker"),await this.worker.terminate()}C.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}):C.warn("Didn't get module, weird....")}async dumpModulesAfterWhile(e){await(0,l.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(v.myRequire.cache);this._sendObject("PostInitLoadedModules",{modules:t})}async sendPatchedModules(){if(!globalThis.hudPatched)return void C.error("Cant find patched modules");const e=Array.from(globalThis.hudPatched);this._sendObject("PatchedModules",{modules:e})}async handleLogsTask(){try{const e=(0,v.suppressTraces)(s.renewFileTransports),t=s.getSavedLogs();for(const e of t)try{this._sendObject("Logs",{logs:e})}catch(e){C.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){C.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,l.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))await this.handleLogsTask()}async setupPeriodicTask(e,t,r,o){function i(e){let t=!0;try{t=r(e)}catch(e){C.error("Failed in periodic task",{taskName:o,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t}if(await(0,l.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal}),i(e)){for await(const e of(0,l.unrefSetInterval)(t,void 0,{signal:this.abortController.signal}))if(!i(t))return void C.warn("Periodic task failed, stopping task",{firstRun:!1,taskName:o})}else C.warn("Periodic task failed, stopping task",{firstRun:!0,taskName:o})}async periodicResetGlobalInvestigationCounter(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;for await(const t of(0,l.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{C.info("Resetting global investigation counter",{interval:e}),(0,p.setGlobalInvestigationTracking)(0)}catch(e){C.error("Failed resetting global investigation counter",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicResetInvestigationDedupingCache(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;for await(const t of(0,l.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{C.info("Resetting investigation deduping cache",{interval:e}),(0,p.resetInvestigationDedupingCache)()}catch(e){C.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,w.getUserTsNodeConfig)();return!!e&&(this.tsNodeUpdated=!0,C.info("tsconfig found, sending config to worker"),this._sendObject("TsNodeConfig",{tsConfig:e}),!0)}catch(e){throw this.tsNodeUpdated=!0,this.stop(),e instanceof h.HudError&&(0,h.setFirstError)(e.code),(0,k._detachAndTerminate)(!1),e}}}},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")}},t={};function r(o){var i=t[o];if(void 0!==i)return i.exports;var n=t[o]={exports:{}};return e[o].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 o in r)("object"==typeof exports?exports:e)[o]=r[o]}}(global,()=>(()=>{"use strict";var e={2546:e=>{e.exports=require("./lib")},2702:function(e,t,r){var o=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,i)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&o(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const s=n(r(2546)),a=r(8528),d=s.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!==a.KeepAliveMessage.msg)return;this._restartTimeout()}catch(e){d.error("Error in keepalive",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_restartTimeout(){const e=setTimeout(()=>{},this.keepaliveGrace);clearTimeout(this.timeoutId),this.timeoutId=e}start(){this.stop(),this.worker.on("message",this.eventHandler).unref()}stop(){void 0!==this.timeoutId&&clearTimeout(this.timeoutId),this.worker.off("message",this.eventHandler),this.timeoutId=void 0}}},5119:function(e,t,r){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.init=void 0;const i=o(r(6281));t.init=i.default},5994:function(e,t,r){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainThread=void 0;const i=r(8167),n=r(2546),s=r(6281),a=o(r(7320));function d(){globalThis.hudDeclarationsFound&&(n.app_logger.warn("Found Declarations but no metrics"),n.customer_logger.log(n.UserErrorLogs.YesDeclarationsNoMetrics()))}t.MainThread=class{apiKey;service;startTime;messenger;constructor(e,t,r){this.apiKey=e,this.service=t,this.startTime=r}startFailed(e){e instanceof n.HudSessionThrottle?(n.customer_logger.info(n.UserLogs.InitIdleMode()),(0,s._detachAndTerminate)(!1,!1)):e instanceof n.HudInitNetworkError&&e.originalAxiosErrorCode?(n.customer_logger.log((0,n.getNetworkError)(e.originalAxiosErrorCode)),(0,s._detachAndTerminate)(!1,!1)):(n.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,s._detachAndTerminate)())}async start(){if(i.isMainThread)if(this.messenger=await this._createMessenger(),this.messenger.runningInsideLambda)this._start().catch(this.startFailed);else try{await this._start()}catch(e){throw this.startFailed(e),e}}async _start(){if(!this.messenger)throw new n.HudInitError("Messenger not initialized");try{await this.messenger.checkWorkerInitialized(n.hudConfig.workerTimeout),await this._initDynamicConfig(),globalThis.hudMetricsIndicator=setTimeout(d,n.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof n.HudSessionThrottle)throw e;throw n.app_logger.error("Failed to starting worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(){const e=n.myRequire.resolve(`${n.SDK_MODULE_NAME}/worker`),t={...process.env};delete t.NODE_OPTIONS;const r=new i.Worker(e,{workerData:{apiKey:this.apiKey,service:this.service,startTime:this.startTime,shouldRunLambdaExtension:globalThis.hudRuningInsideLambda,shouldCreateDeclaraionWorker:globalThis.hudRuningInsideLambda,userConfig:n.hudConfig.userConfig},execArgv:[],env:t});let o;try{o=new a.default(r),await o.checkWorker(n.hudConfig.workerTimeout)}catch(e){if(e instanceof n.HudSessionThrottle)throw n.app_logger.info("Worker started in idle mode - session throttled"),e;throw n.app_logger.error("Worker failed to start",{msg:e instanceof Error?e.message:void 0}),e}finally{r.unref()}return o}async _initDynamicConfig(){const e=await(this.messenger?.getRemoteConfig());e?(n.app_logger.info("Remote configuration exists"),n.hudConfig.dynamicConfig=(0,n.updateDynamicConfig)(e,n.hudConfig,n.app_logger),(0,n.updateInvestigationRateLimitGlobals)(),n.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:n.hudConfig.dynamicConfig})):n.app_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:n.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._detachAndTerminate=t.isValidParam=void 0;const o=r(2546),i=r(5994),n=r(2546),s=r(8528),a=r(8269),d=r(2546),c=r(7274);let l;t.default=async function(e,t){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void o.app_logger.warn("Already ran init!");if(globalThis.hudRunMutex=!0,(0,a.clearInitGuard)(),!o.app_logger.isValid())return(0,d.setFirstError)((new d.HudBadLoggerError).code),void u(!0,!0);(0,n.updateUserConfigFromInit)(e,t);const r=(0,a.validateAndGetUserInput)();if(!r)return;if(globalThis.hudRunningMode!==s.HudRunningMode.enabled)return;o.app_logger.info("Initializing hud",{userConfig:Object.entries(n.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new i.MainThread(r.apiKey,r.service,globalThis.hudStartTime),await l.start(),o.customer_logger.log(d.UserLogs.HudInitSuccess()),l.messenger&&(0,d.safeCall)(o.app_logger,l.messenger.handleLogsTask())}catch(e){try{if(e instanceof d.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(e){o.app_logger.error("Something went wrong in init & e.stack raised an exception")}u()}},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e};let g=!1;function u(e=!0,t=!1){(0,a.detachHud)(e,t),l&&(0,d.safeCall)(o.app_logger,l.terminateMessenger()),globalThis.hudExtensionId&&!g&&(g=!0,(0,d.safeCall)(o.app_logger,(0,o.nextLoopDummy)(globalThis.hudExtensionId))),(0,a.clearUserIndicatorsTimeouts)(),(0,c.resetCallers)()}t._detachAndTerminate=u},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resetCallers=t.prepCalls=t._liftExceptions=void 0;const o=r(8269),i=r(2546);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}t._liftExceptions=s,t.prepCalls=function(e,t){const r=(new Date).toISOString(),n=[];return Object.entries(hudCalls).map(([o,a])=>{Object.entries(a).forEach(([a,d])=>{Object.entries(d).forEach(([d,c])=>{try{if(0===c.sampledCount)return;const i={function_id:o,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(i),function(e){e.lastSentCounter=e.count,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(c)}catch(e){i.app_logger.error("Failed preparing invocation, skipping",{func:o,wrappedCaller:a,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})})}),n.length>0&&globalThis.hudDeclarationsFound&&(0,o.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])}},7320:function(e,t,r){var o=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,i)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&o(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0});const s=n(r(2546)),a=n(r(6460)),d=r(2546),c=r(8528),l=r(2546),g=r(7131),u=r(8269),h=r(2546),f=r(7274),m=r(2702),p=r(8269),v=r(2546),k=r(6281),w=r(2546),y=r(6261),C=s.app_logger,b=h.safeCall.bind(h.safeCall,C);t.default=class{worker;runningInsideLambda=!1;tsNodeUpdated=!1;abortController;workerKeepaliveGuard;constructor(e){this.worker=e,this.abortController=new AbortController,(0,y.setMaxListeners)(20,this.abortController.signal),this.worker.on("error",this.handleWorkerError).unref(),this.workerKeepaliveGuard=new m.WorkerKeepaliveGuard(e,d.hudConfig.communicationKeepaliveGrace),this._updateTsNodeConfig()&&C.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new h.HudClientUnauthorizedError).code&&s.customer_logger.log(h.UserErrorLogs.ApiKeyDenied(d.hudConfig.userConfig.key?.source)),C.error("Error from worker, stopping hud",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,h.setFirstError)(e?.code),this.stop(),(0,k._detachAndTerminate)()}catch(e){C.error("Error stopping hud",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};stop(){this.abortWorker(),d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.abortController.abort(),this.abortController=new AbortController,(0,u.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),C.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=["startedNoExtension","extensionRegistered"];let r;try{r=await this.getMessageFromWorker(t,e,!0)}catch(o){if(!(o instanceof h.HudTimeoutError))throw o;r=await this.getMessageFromWorker(t,e/2,!1)}if(!r)throw new h.HudInitError("Worker not started");return"extensionRegistered"===r.msg&&(this.runningInsideLambda=!0,globalThis.hudExtensionId=r.content.extensionId),r}async checkWorkerInitialized(e){let t;const r=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(r,e,!0)}catch(o){if(!(o instanceof h.HudTimeoutError))throw o;t=await this.getMessageFromWorker(r,e/10,!1)}if("throttled"===t?.msg)throw new h.HudSessionThrottle;if("networkError"===t?.msg)throw C.error("networkError",{error:t.content.error}),new h.HudInitNetworkError(t.content.message,t.content.originalMessage);if(!t||"initialized"!==t?.msg||void 0===t?.content)throw new h.HudInitError("Worker not initialized successfully");if(t?.content.status!==c.HudSessionInitStatus.success)throw new h.HudInitError("Worker not initialized successfully");return t}async start(){switch(d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case c.HudRunningMode.enabled:C.info("Enabled mode"),b(this.getMode()),b(this.startPeriodicTasks()),b(this.periodicSendInvocations()),b(this.periodicSendProcessedFiles()),b(this.periodicSendEndpoints()),b(this.periodicSendFlowMetrics()),b(this.periodicSendGarphQL()),b(this.periodicSendKafkaJS()),b(this.periodicSendSqs()),b(this.periodicSendInvestigations()),b(this.periodicSaveMachineMetrics()),b(this.resetCallerCounters()),b(this.periodicResetGlobalInvestigationCounter()),b(this.periodicResetInvestigationDedupingCache()),b(this.sendLogsPeriodically(d.hudConfig.logsSendInterval)),b(this.sendRuntime()),b(this.sendPatchedModules()),b(this.sendPreloadedModules()),b(this.dumpModulesAfterWhile(6e4)),b((0,h.loopLogThreadPerformance)(C,d.hudConfig.logPerfInterval,this.abortController.signal));break;case c.HudRunningMode.disabled:C.info("Disabled mode"),b(this.getMode());break;case c.HudRunningMode.detached:C.info("Detached"),(0,k._detachAndTerminate)(!1,!1),this.stop();break;default:C.error("Running mode not handled")}}async getMessageFromWorker(e,t,r=!1,o){let i;e=Array.isArray(e)?e:[e];const n=new AbortController,s=()=>{n.abort()};this.abortController.signal.addEventListener("abort",s);const d=a.setTimeout(t,void 0,{signal:n.signal,ref:r}),c=t=>{try{e.includes(t.msg)&&(i=t,n.abort(),C.info("Received message from worker (canceling timeout)",t))}catch(e){C.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(),o&&this.worker.postMessage(o);try{throw await d,C.warn("Timeout waiting for message from worker"),new h.HudTimeoutError}catch(e){if(!(0,h.isAbortError)(e))throw(0,h.setFirstError)(e.code),e}finally{this.abortController.signal.removeEventListener("abort",s),this.worker.off("message",c)}return i}async getMode(){for await(const e of(0,l.unrefSetInterval)(d.hudConfig.modeInterval,void 0,{signal:this.abortController.signal}))try{const e={msg:"GetMode",content:{startTime:globalThis.hudStartTime,runningMode:globalThis.hudRunningMode}},t=await this.getMessageFromWorker(e.msg,d.hudConfig.workerMessageTimeout,!1,e);if(t?.msg!==e.msg||void 0===t?.content.mode){C.error("Unexpected message from worker",t);continue}t.content.mode!==globalThis.hudRunningMode&&await this.restart(t?.content.mode)}catch(e){C.error("Failed getting mode from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async getRemoteConfig(){const e="initDynamicConfig";try{const t=await this.getMessageFromWorker(e,d.hudConfig.workerMessageTimeout,!0);if(t?.msg!==e||void 0===t?.content)throw new Error(`Unexpected message from worker: ${t}`);return t?.content}catch(e){C.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,u.saveMachineMetric)();for await(const e of(0,l.unrefSetInterval)(d.hudConfig.dynamicConfig.machineMetricsInterval,void 0,{signal:this.abortController.signal}))(0,u.saveMachineMetric)()}async resetCallerCounters(){const e=d.hudConfig.callerResetInterval;for await(const t of(0,l.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{C.info("Resetting caller",{interval:e}),(0,f.resetCallers)()}catch(e){C.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=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;let r=!0;await this.setupPeriodicTask(e,t,()=>{if(r){r=!1;try{this._updateTsNodeConfig()&&C.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 g.SketchManager(d.hudConfig.huddBinWidth),t=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,r=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,r,t=>{const r=(0,f.prepCalls)(t,e);return this._sendArray("Invocations",r),!0},"periodicSendInvocations")}async periodicSendFlowMetrics(){const e=d.hudConfig.dynamicConfig.flowMetricFirstSendTimeout,t=d.hudConfig.dynamicConfig.flowMetricInterval;await this.setupPeriodicTask(e,t,e=>{const t=(0,u.getFlowMetrics)();return t.length>0&&this._sendObject("FlowMetrics",{timeslice:e,rawMetrics:t}),!0},"periodicSendFlowMetrics")}async periodicSendGarphQL(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendGraphQLResolvers(),this.sendGraphQLDocuments(),!0),"periodicSendGarphQL")}async periodicSendKafkaJS(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,p.getKafkaJSTopics)();return this._sendArray("KafkaJSTopics",e),!0},"periodicSendKafkaJS")}async periodicSendSqs(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,p.getSqsQueues)();return e.length>0&&this._sendArray("SqsQueue",e),!0},"periodicSendSqs")}async periodicSendInvestigations(){const e=d.hudConfig.dynamicConfig.aggregationInterval;for await(const t of(0,l.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{const e=(0,p.getClosedInvestigations)();this._sendArray("Investigations",e)}catch(e){C.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,p.getResolversDeclarations)().map(e=>({id:e.id,operation:e.operation,name:e.name}));this._sendArray("GraphQLResolvers",e)}catch(e){C.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,p.getDocumentsMetadata)().map(e=>({name:e.name,hash:e.hash,selection_names:e.selectionNames,time_took:e.timeTook}));this._sendArray("GraphQLDocuments",e)}catch(e){C.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=d.hudConfig.endpointsFirstSendWaitTime,t=d.hudConfig.endpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendEndpoints(),!0),"periodicSendEndpoints")}sendEndpoints(){const e=(0,p.getExpressEndpointDeclarations)(),t=(0,u.getKoaEndpointDeclarationsFromStorage)(),r=e.concat(t).map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",r)}async terminateWorker(){try{const e=(0,v.suppressTraces)(s.renewFileTransports),t=s.getSavedLogs(),r=e();await this.getMessageFromWorker("terminated",d.hudConfig.workerGrace,!1,{msg:"Terminate",content:{grace:d.hudConfig.workerGrace,logBuffers:t,logFiles:Array.from(r)}})}catch(e){if(!(e instanceof h.HudTimeoutError))throw C.error("Unexpected error, terminating worker"),await this.worker.terminate(),e;C.error("Grace period timeout, terminating worker"),await this.worker.terminate()}C.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}):C.warn("Didn't get module, weird....")}async dumpModulesAfterWhile(e){await(0,l.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(v.myRequire.cache);this._sendObject("PostInitLoadedModules",{modules:t})}async sendPatchedModules(){if(!globalThis.hudPatched)return void C.error("Cant find patched modules");const e=Array.from(globalThis.hudPatched);this._sendObject("PatchedModules",{modules:e})}async handleLogsTask(){try{const e=(0,v.suppressTraces)(s.renewFileTransports),t=s.getSavedLogs();for(const e of t)try{this._sendObject("Logs",{logs:e})}catch(e){C.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){C.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,l.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))await this.handleLogsTask()}async setupPeriodicTask(e,t,r,o){function i(e){let t=!0;try{t=r(e)}catch(e){C.error("Failed in periodic task",{taskName:o,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t}if(await(0,l.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal}),i(e)){for await(const e of(0,l.unrefSetInterval)(t,void 0,{signal:this.abortController.signal}))if(!i(t))return void C.warn("Periodic task failed, stopping task",{firstRun:!1,taskName:o})}else C.warn("Periodic task failed, stopping task",{firstRun:!0,taskName:o})}async periodicResetGlobalInvestigationCounter(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;for await(const t of(0,l.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{C.info("Resetting global investigation counter",{interval:e}),(0,p.setGlobalInvestigationTracking)(0)}catch(e){C.error("Failed resetting global investigation counter",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicResetInvestigationDedupingCache(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;for await(const t of(0,l.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{C.info("Resetting investigation deduping cache",{interval:e}),(0,p.resetInvestigationDedupingCache)()}catch(e){C.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,w.getUserTsNodeConfig)();return!!e&&(this.tsNodeUpdated=!0,C.info("tsconfig found, sending config to worker"),this._sendObject("TsNodeConfig",{tsConfig:e}),!0)}catch(e){throw this.tsNodeUpdated=!0,this.stop(),e instanceof h.HudError&&(0,h.setFirstError)(e.code),(0,k._detachAndTerminate)(!1),e}}}},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")}},t={};function r(o){var i=t[o];if(void 0!==i)return i.exports;var n=t[o]={exports:{}};return e[o].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,r){if("object"==typeof exports&&"object"==typeof module)module.exports=r();else if("function"==typeof define&&define.amd)define([],r);else{var t=r();for(var o in t)("object"==typeof exports?exports:e)[o]=t[o]}}(global,(
|
|
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 t=r();for(var o in t)("object"==typeof exports?exports:e)[o]=t[o]}}(global,()=>(()=>{"use strict";var e={2546:e=>{e.exports=require("./lib")},8167:e=>{e.exports=require("worker_threads")}},r={};function t(o){var n=r[o];if(void 0!==n)return n.exports;var s=r[o]={exports:{}};return e[o](s,s.exports,t),s.exports}var o={};return(()=>{var e=o;Object.defineProperty(e,"__esModule",{value:!0});const r=t(2546),n=t(8167);let s;async function a(e){try{if("TsNodeConfig"===e.msg)return void(s=e.content.tsOptions);n.parentPort?.postMessage("eventlooptime");const t=e.content,{filename:o,indexOffset:a,indexOffsetEnd:i}=t,c=await(0,r.readFile)(o,a,i);if(!c)return;const f=await(0,r.parseDeclarations)(t,c,n.parentPort,s);n.parentPort?.postMessage(f)}catch(e){r.worker_logger.error("Error in declaration worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}n.parentPort?.once("message",a)}n.isMainThread||(n.parentPort?.setMaxListeners(0),(async()=>{n.parentPort?.once("message",a)})())})(),o})());
|
|
2
2
|
//# sourceMappingURL=declarationWorker.js.map
|
package/dist/cjs/dto.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var o=t();for(var r in o)("object"==typeof exports?exports:e)[r]=o[r]}}(global,(
|
|
1
|
+
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var o=t();for(var r in o)("object"==typeof exports?exports:e)[r]=o[r]}}(global,()=>(()=>{"use strict";var e={765:(e,t)=>{var o,r;Object.defineProperty(t,"__esModule",{value:!0}),t.HudSessionInitStatus=t.HudRunningMode=t.KeepAliveMessage=void 0,t.KeepAliveMessage={msg:"keep-alive"},function(e){e[e.detached=0]="detached",e[e.disabled=1]="disabled",e[e.enabled=2]="enabled"}(o||(t.HudRunningMode=o={})),function(e){e[e.success=0]="success",e[e.throttled=1]="throttled"}(r||(t.HudSessionInitStatus=r={}))},878:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.GraphQLSupportedOperations=void 0,function(e){e.query="query",e.mutation="mutation"}(o||(t.GraphQLSupportedOperations=o={}))},1569:e=>{e.exports=require("zod")},2176:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3487:function(e,t,o){var r=this&&this.__createBinding||(Object.create?function(e,t,o,r){void 0===r&&(r=o);var n=Object.getOwnPropertyDescriptor(t,o);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,n)}:function(e,t,o,r){void 0===r&&(r=o),e[r]=t[o]}),n=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||r(t,e,o)};Object.defineProperty(t,"__esModule",{value:!0}),n(o(7935),t),n(o(6910),t),n(o(2176),t),n(o(9107),t),n(o(7022),t),n(o(6604),t),n(o(4909),t),n(o(878),t),n(o(8377),t),n(o(8054),t),n(o(6328),t),n(o(6364),t),n(o(765),t)},4909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6328:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6364:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HudInitOptionsSchema=void 0;const r=o(1569);t.HudInitOptionsSchema=r.z.object({includeModules:r.z.array(r.z.string()).optional(),maxMappedFunctions:r.z.number().optional(),minPodMemoryMB:r.z.number().optional(),maxFileSizeBytes:r.z.number().optional(),maxTimeUntilInitSessionMs:r.z.number().optional(),verbose:r.z.boolean().optional(),disableSourceMapsResolution:r.z.boolean().optional(),customOptions:r.z.record(r.z.string(),r.z.string()).optional()})},6604:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6910:(e,t)=>{var o,r,n;Object.defineProperty(t,"__esModule",{value:!0}),t.EntityType=t.ArgumentTypes=t.ParameterTypes=void 0,function(e){e.Identifier="Identifier",e.RestElement="RestElement",e.ArrayPattern="ArrayPattern",e.AssignmentPattern="AssignmentPattern",e.ObjectPattern="ObjectPattern",e.ObjectProperty="ObjectProperty"}(o||(t.ParameterTypes=o={})),function(e){e.StringLiteral="StringLiteral",e.Identifier="Identifier",e.TemplateString="TemplateString"}(r||(t.ArgumentTypes=r={})),function(e){e.FunctionDeclaration="functionDeclaration",e.FunctionExpression="functionExpression",e.FunctionArrow="functionArrow",e.ClassMethod="classMethod",e.ObjectMethod="objectMethod",e.ClassPrivateMethod="classPrivateMethod",e.ClassDeclaration="classDeclaration",e.ClassExpression="classExpression",e.ObjectExpression="objectExpression",e.Program="program",e.ForLoop="forLoop",e.ForBlock="forBlock",e.ForTest="forTest",e.Block="block",e.While="while",e.DoWhile="doWhile",e.Do="Do",e.WhileTest="whileTest",e.Switch="switch",e.SwitchCase="switchCase",e.Catch="catch",e.With="with",e.If="if",e.IfTest="ifTest",e.IfConsequent="ifConsequent",e.IfAlternate="ifAlternate",e.TryCatch="tryCatch",e.Try="try",e.Finally="finally",e.Other="other",e.File="file"}(n||(t.EntityType=n={}))},7022:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.isSupportedFormat=t.Format=t.FUNCTION_DECLARATION_VERSION=void 0,t.FUNCTION_DECLARATION_VERSION="1.1.2",function(e){e.cjs="commonjs",e.esm="module",e.moduleTypescript="module-typescript",e.commonjsTypescript="commonjs-typescript"}(o||(t.Format=o={})),t.isSupportedFormat=function(e){return Object.values(o).includes(e)}},7935:(e,t)=>{function o(e,t){return t?t instanceof RegExp?e+t.toString():("/"===t[t.length-1]&&t.length>1&&(t=t.slice(0,-1)),(t=e+t).replace(/\/{2,}/g,"/")):t}Object.defineProperty(t,"__esModule",{value:!0}),t.EndpointDeclaration=void 0,t.EndpointDeclaration=class{flow_id;methods;framework;partial_path;path;constructor(e,t,r,n,i,s){this.flow_id=e,this.methods=t,this.framework=r,this.partial_path=s,n||(n=""),this.path=o(n,i),this.partial_path=o(n,s)}}},8054:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8377:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.InvestigationStatus=void 0,function(e){e[e.Open=1]="Open",e[e.Closed=2]="Closed"}(o||(t.InvestigationStatus=o={}))},9107:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})}},t={};return function o(r){var n=t[r];if(void 0!==n)return n.exports;var i=t[r]={exports:{}};return e[r].call(i.exports,i,i.exports,o),i.exports}(3487)})());
|
|
2
2
|
//# sourceMappingURL=dto.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var o=t();for(var r in o)("object"==typeof exports?exports:e)[r]=o[r]}}(global,(()=>(()=>{"use strict";var e={857:e=>{e.exports=require("os")},870:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.limitedParallel=void 0,t.limitedParallel=async function(e,t,o,r=!1){const i=[],n=[];return await Promise.all(Array.from({length:t},(async function(){for(;e.length>0;){const t=e.shift();try{const e=await o(t);i.push(e)}catch(e){if(n.push(e),r)throw e}}}))),{results:i,errors:n}}},2030:e=>{e.exports=require("./instrument")},2305:e=>{e.exports=require("form-data")},2546:e=>{e.exports=require("./lib")},2784:e=>{e.exports=require("../native/_index")},3066:function(e,t,o){var r=this&&this.__createBinding||(Object.create?function(e,t,o,r){void 0===r&&(r=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,i)}:function(e,t,o,r){void 0===r&&(r=o),e[r]=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}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&r(t,e,o);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.requestRelentless=void 0;const a=o(2546),s=n(o(8938)),u=o(5231);t.requestRelentless=async function(e,t,o,r=3){for(let i=0;i<r;i++)try{return await s.default.post(e,t,o)}catch(t){if(t instanceof s.AxiosError&&401===t.response?.status)throw new a.HudClientUnauthorizedError(`Unauthorized request for ${e}`);(0,u.logToHud)(`Failed request to ${e}, attempt ${i+1} of ${r}. Error: ${t}`),await new Promise((e=>setTimeout(e,1)))}throw new a.HudClientExceededMaxRetries(`Exceeded max retries for ${e}`)}},3903:e=>{e.exports=require("uuid")},4414:function(e,t,o){var r=this&&this.__createBinding||(Object.create?function(e,t,o,r){void 0===r&&(r=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,i)}:function(e,t,o,r){void 0===r&&(r=o),e[r]=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}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&r(t,e,o);return i(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.uploadAllSourceMaps=t.uploadSourceMap=void 0;const s=o(2546),u=a(o(2305)),l=n(o(9896)),d=o(5231),c=o(870),f=o(3066);async function p(e){const{buildId:t,filePath:o,hudKey:r}=e,i=new u.default;i.append("build_id",t),i.append("token",r);try{const e=await l.promises.readFile(o,"utf8"),t=JSON.parse(e);delete t.sourcesContent,i.append("sourcemap",JSON.stringify(t),{filename:"sourcemap",contentType:"application/json"})}catch(e){return(0,d.logToHud)(`failed parsing source map, skipping upload. Error: ${e}`),void(0,d.logToUser)(s.UserErrorLogs.EsbuildFailedParsingSourcemap())}try{await(0,f.requestRelentless)(`${s.hudConfig.sink.url}/${s.hudConfig.endpoints.sourceMap}`,i,{headers:{"Content-Type":"multipart/form-data"},timeout:s.hudConfig.esbuildUploadSourceMapTimeout})}catch(e){if(e instanceof Error&&e.message.includes("Unauthorized"))throw e;(0,d.logToHud)(`failed uploading source map. File: ${o}, Error: ${e}`),(0,d.logToUser)(s.UserErrorLogs.EsbuildFailedUploadingSourcemap(o))}}t.uploadSourceMap=p,t.uploadAllSourceMaps=async function(e,t){if(process.env.HUD_SKIP_SOURCEMAP_UPLOAD)(0,d.logToHud)("Skipping source map upload due to env var");else{(0,d.logToHud)(`Uploading source maps for ${e.length} files`);try{const o=[];for(const{buildId:r,filepath:i}of e){const e=`${i}.map`;try{await l.promises.access(e,l.constants.F_OK),o.push({buildId:r,filePath:e,hudKey:t})}catch{(0,d.logToHud)(`No source map found for file: ${i}`)}}await(0,c.limitedParallel)(o,10,p,!0),(0,d.logToHud)("Finished uploading source maps")}catch{return(0,d.logToUser)(s.UserErrorLogs.EsbuildFailedUploadingSourcemapUnauthorized()),void(0,d.setDontSendLogs)()}}}},5231:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getShouldSendLogs=t.setDontSendLogs=t.exportBuildLogs=t.logToHud=t.logToHudDebug=t.logToUser=void 0;const r=o(2546),i=o(6982),n=o(870),a=o(3066),s=r.hudConfig.esbuildPluginMessagePrefix,u=(0,i.randomUUID)(),l=[];let d=!0;function c(e,t=!0){"true"===process.env.HUD_PLUGIN_VERBOSE&&(t&&(e=(0,r.formatLogMessage)(`${s}${e}`)),console.log(e)),l.push({message:e,SessionID:u,timestamp:Date.now()})}async function f(e){await(0,a.requestRelentless)(r.hudConfig.pluginsLogEndpoint,{messages:e},{headers:{"x-hudx-plugin":"true","Content-Type":"application/json"}})}t.logToUser=function(e){let t="";t="string"==typeof e?(0,r.formatLogMessage)(`${s}${e}`):(0,r.formatLogMessage)(`${s}${e.message}`,e.errCode,e.moreInfo),console.log(t),c(t,!1)},t.logToHudDebug=function(e,t=!0){"true"===process.env.HUD_PLUGIN_DEBUG&&c(e,t)},t.logToHud=c,t.exportBuildLogs=async function(e){const t=[];for(let o=0;o<l.length;o+=r.hudConfig.esbuildPluginLogsBatchSize){const i=l.slice(o,o+r.hudConfig.esbuildPluginLogsBatchSize).map((t=>({...t,accessToken:e})));t.push(i)}await(0,n.limitedParallel)(t,10,f)},t.setDontSendLogs=function(){d=!1},t.getShouldSendLogs=function(){return d}},6928:e=>{e.exports=require("path")},6932:function(e,t,o){var r=this&&this.__createBinding||(Object.create?function(e,t,o,r){void 0===r&&(r=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,i)}:function(e,t,o,r){void 0===r&&(r=o),e[r]=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}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&r(t,e,o);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.verifyFileContent=t.createMark=t.markFile=t.markFileAsHudModified=t.verifyAndMarkFinalFiles=t.HudBuildError=void 0;const a=o(2030),s=o(2546),u=n(o(2784)),l=o(3903),d=n(o(9154)),c=o(7085),f=o(5231);class p extends Error{}function g(e,t){return`/*modifiedByHudESBuildPlugin-${t}*/${e}`}function h(e,t){const o=t?"Start":"End";return`;globalThis && (globalThis.${s.hudConfig.esbuildGlobalVar}="${o}:${e}");`}function m(e,t,o){try{(0,f.logToHud)(`Verifying file content: ${t}, with marks`),new d.Script(e),(0,f.logToHud)(`Editing in splits file content: ${t}`);const{transformedCode:r,editedChunksSizes:i}=(0,a.editInSplits)(e,t,o,!0,(e=>!e.includes("node_modules")));if(!r)throw new p(`Failed verify file content, ${t}`);for(let e=0;e<i.length;e+=c.LOG_CHUNKS_SIZE_BATCH){const t=JSON.stringify(i.slice(e,e+c.LOG_CHUNKS_SIZE_BATCH));(0,f.logToHudDebug)(`Edited chunks sizes: ${t}`)}(0,f.logToHud)(`Verifying new file content: ${t}`),new d.Script(r),(0,f.logToHud)(`Verified new file content: ${t}`)}catch(e){throw(0,f.logToHud)(`Failed verify file content, ${t}, error: ${e}`),new p(`Failed verify file content, ${t}`)}}t.HudBuildError=p,t.verifyAndMarkFinalFiles=async function(e,t,o){const r=[];for(const i of e){if(!i.path.endsWith(".js")){t&&await(0,c.writeFileAndFolder)(i.path,i.contents);continue}if(!i.text.includes(s.hudConfig.esbuildGlobalVar)){t&&await(0,c.writeFileAndFolder)(i.path,i.contents);continue}const e=(0,l.v5)(i.contents,s.hudConfig.bundlerBuildUuidNamespace);r.push({filepath:i.path,buildId:e});const n=g(i.text,e);process.env.HUD_SKIP_FILE_VALIDATION||m(n,i.path,o),i.contents=new Uint8Array(Buffer.from(n,"utf8")),t&&await(0,c.writeFileAndFolder)(i.path,i.contents)}return r},t.markFileAsHudModified=g,t.markFile=function(e,t){const o=u.markFile(t,{data:{filename:e,format:"esm"},initialStatements:[h(e,!0)],suffixStatements:[h(e,!1)]});if(!o||!o.code||!o.map)throw new Error("Failed generating ast");return function(e,t){let o;return void 0===t?e:(o="string"==typeof t||t instanceof String?Buffer.from(t.toString()).toString("base64"):Buffer.from(JSON.stringify(t)).toString("base64"),e+`\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${o}`)}(o.code,o.map)},t.createMark=h,t.verifyFileContent=m},6982:e=>{e.exports=require("crypto")},7085:function(e,t,o){var r=this&&this.__createBinding||(Object.create?function(e,t,o,r){void 0===r&&(r=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,i)}:function(e,t,o,r){void 0===r&&(r=o),e[r]=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}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&r(t,e,o);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.plugin=t.getModuleRoot=t.writeFileAndFolder=t.LOG_CHUNKS_SIZE_BATCH=void 0;const a=o(8528),s=o(2030),u=o(6982),l=n(o(9896)),d=n(o(857)),c=n(o(6928)),f=o(2546),p=o(9929),g=o(5231),h=o(6932),m=o(4414);async function b(e,t,o,r,i){if(!(o&&r&&i&&r.test(e)))return;const n=c.join(i,e),a=c.dirname(n);try{await l.promises.access(a)}catch{await l.promises.mkdir(a,{recursive:!0})}await l.promises.writeFile(n,t,"utf8");const s=await o(n);return s?.contents&&(t=s.contents),t}async function y(e){let t=c.dirname(e);for(let e=0;e<30&&"/"!==t;e++){const e=c.join(t,"package.json");try{return await l.promises.access(e),t}catch{t=c.dirname(t)}}}t.LOG_CHUNKS_SIZE_BATCH=f.hudConfig.esbuildPluginLogsChunkSize,t.writeFileAndFolder=async function(e,t){const o=c.dirname(e);try{await l.promises.stat(o)}catch{await l.promises.mkdir(o,{recursive:!0})}await l.promises.writeFile(e,t)},t.getModuleRoot=y;const v="hud-esbuild-plugin";t.plugin=e=>({name:v,async setup(t){if("node"!==t.initialOptions.platform)return void(0,g.logToUser)(f.UserErrorLogs.EsbuildUnsupportedPlatform());if("win32"===d.platform())return void(0,g.logToUser)(f.UserErrorLogs.EsbuildUnsupportedWindows());const o=e?.hudKey??process.env.HUD_KEY;if(!o)return void(0,g.logToUser)(f.UserErrorLogs.EsbuildMissingKey());const r=e?.includeModules??(0,f.getModulesToTraceFromEnv)()??[],i=(0,s.createCheckers)(r);(0,g.logToUser)("started running");const n=t.initialOptions.write??!0;t.initialOptions.write=!1;const w="esm"===t.initialOptions?.format?a.Format.esm:a.Format.cjs,{callback:_,filter:S,tempDir:T}=await async function(e){const t=e.initialOptions;if(!t.plugins)return;const o=t.plugins.findIndex((e=>e.name===v)),r=t.plugins[o+1];if(!r||"datadog-esbuild"!==r.name)return;let i;(0,g.logToHud)("datadog-esbuild plugin detected");const n={...e,onLoad:(...e)=>{i=e},onStart:()=>{},onEnd:()=>{},onResolve:()=>{},onDispose:()=>{}};if(r.setup(n),!i)return void(0,g.logToHud)("datadog-esbuild plugin detected but failed receive onLoad callback");const a=c.join(d.tmpdir(),`hud-${(0,u.randomUUID)()}`);try{return await l.promises.access(a),void(0,g.logToUser)("temp dir already exists, try rerunning the build.")}catch(e){}return(0,g.logToHud)(`creating temp dir to be used by datadog plugin.\n\tPath: ${a}`),await l.promises.mkdir(a,{recursive:!0}),{filter:i[0].filter,callback:i[1],tempDir:a}}(t)??{},O=new Set(t.initialOptions.external||[]),F=new Map;t.onResolve({filter:/.*/},(async e=>{if(e.pluginData?.hud?.calledFromHud)return;if(O.has(e.path))return;if(!f.hudConfig.frameworksToPatch.get(e.path)?.enableEsbuild)return;const o={...e};delete o.path;const r=await t.resolve(e.path,{...o,pluginData:{...e.pluginData,hud:{calledFromHud:!0}}}),i=await y(r.path);i&&(F.set(i,e.path),(0,g.logToHud)(`mapping framework: ${i} => ${e.path}`))})),t.onLoad({filter:/.*\.(js|ts)$/},(async e=>{try{const t=_?async t=>await _({...e,path:t}):void 0;if((0,s.skip)(e.path,i)){const o=await(0,p.getFrameworkContentSuffix)(e.path,F);if(!o)return;let r=await l.promises.readFile(e.path,"utf8");return r=await b(e.path,r,t,S,T)??r,r+=o,{contents:r,loader:e.path.endsWith("ts")?"ts":"js",resolveDir:c.dirname(e.path)}}let o=await l.promises.readFile(e.path,"utf8");return o=(0,h.markFile)(e.path,o),o=await b(e.path,o,t,S,T)??o,o+=await(0,p.getFrameworkContentSuffix)(e.path,F)??"",{contents:o,loader:e.path.endsWith("ts")?"ts":"js",resolveDir:c.dirname(e.path)}}catch(t){return(0,g.logToHud)(`failed patching file "${e.path}", fallbacking to original loader. Error: ${t}`),void(0,g.logToUser)(`failed patching file "${e.path}", fallbacking to original loader`)}})),t.onEnd((async e=>{if(!e?.outputFiles)return;let t;try{t=await(0,h.verifyAndMarkFinalFiles)(e.outputFiles,n,w),(0,g.logToUser)("finished")}catch(e){throw(0,g.logToHud)(`failed validating. Error: ${e}`),(0,g.logToUser)(f.UserErrorLogs.EsbuildFailedBundling()),e}finally{if(t)try{await(0,m.uploadAllSourceMaps)(t,o)}catch(e){(0,g.logToHud)(`failed uploading source maps. Shouldnt get here since we catch all errors in verifyAndMarkFinalFiles, error: ${e}`)}try{if(T)try{await l.promises.access(T),(0,g.logToHud)("cleaning temp dir"),await l.promises.rm(T,{recursive:!0,force:!0})}catch{}}catch(e){(0,g.logToHud)(`failed cleaning temp dir. Error: ${e}`)}try{!process.env.HUD_SKIP_BUILD_LOG_EXPORT&&(0,g.getShouldSendLogs)()&&await(0,g.exportBuildLogs)(o)}catch(e){"true"===process.env.HUD_PLUGIN_VERBOSE&&"true"===process.env.HUD_DEBUG&&(0,g.logToUser)(`Failed exporting build logs. Error: ${e}`)}}}))}})},8528:e=>{e.exports=require("./dto")},8938:e=>{e.exports=require("axios")},9154:e=>{e.exports=require("vm")},9896:e=>{e.exports=require("fs")},9929:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFrameworkContentSuffix=void 0;const r=o(8528),i=o(2030),n=o(2546),a=o(7085),s=o(5231);t.getFrameworkContentSuffix=async function(e,t){const o=[...t.entries()].find((([t,o])=>e.startsWith(t)));if(!o)return;const[u,l]=o;let d=l+e.slice(u.length);(d.endsWith("index.js")||d.endsWith("index.ts"))&&(d=d.slice(0,d.length-9));const c=n.hudConfig.frameworksToPatch.get(d);if(!(c?.enableEsbuild&&c?.patcher&&c?.version))return;(0,s.logToHud)(`Patching framwork: ${d}`);const f=await(0,a.getModuleRoot)(e);if(!f)return void(0,s.logToHud)(`Failed to find package.json for ${d}`);const p=(0,i.extractModuleVersion)(f);if((0,s.logToHud)(`Patching framework ${d}, version: ${p}`),(0,i.getFrameworkPatcher)(c.patcher).isSupported(f,d,c.version,c.extraInfo))return`\n ;\n try {\n const { hudRITM, infoSafeLog: hudSafeLogger } = require("hud-sdk/instrument");\n if (globalThis.hudRunningMode === ${r.HudRunningMode.enabled}) {\n if (typeof hudRITM === "function") {\n if (typeof hudSafeLogger === "function") {\n hudSafeLogger("esbuild patching ${d}");\n }\n module.exports = hudRITM(module.exports, "${d}", "hud-esbuild-folder-should-not-exists");\n }\n }\n } catch (e) {\n try {\n const { errorSafeLog: hudSafeLogger } = require("hud-sdk/internal");\n if (typeof hudSafeLogger === "function") {\n hudSafeLogger(\`esbuild patching ${f} failed: \${e}\`);\n }\n } catch {}\n }\n `;(0,s.logToHud)(`Failed to patch ${d}, unsupported version: ${p}`)}}},t={};return function o(r){var i=t[r];if(void 0!==i)return i.exports;var n=t[r]={exports:{}};return e[r].call(n.exports,n,n.exports,o),n.exports}(7085)})()));
|
|
1
|
+
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var o=t();for(var r in o)("object"==typeof exports?exports:e)[r]=o[r]}}(global,()=>(()=>{"use strict";var e={857:e=>{e.exports=require("os")},870:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.limitedParallel=void 0,t.limitedParallel=async function(e,t,o,r=!1){const i=[],n=[];return await Promise.all(Array.from({length:t},async function(){for(;e.length>0;){const t=e.shift();try{const e=await o(t);i.push(e)}catch(e){if(n.push(e),r)throw e}}})),{results:i,errors:n}}},2030:e=>{e.exports=require("./instrument")},2305:e=>{e.exports=require("form-data")},2546:e=>{e.exports=require("./lib")},2784:e=>{e.exports=require("../native/_index")},3066:function(e,t,o){var r=this&&this.__createBinding||(Object.create?function(e,t,o,r){void 0===r&&(r=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,i)}:function(e,t,o,r){void 0===r&&(r=o),e[r]=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}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&r(t,e,o);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.requestRelentless=void 0;const a=o(2546),s=n(o(8938)),u=o(5231);t.requestRelentless=async function(e,t,o,r=3){for(let i=0;i<r;i++)try{return await s.default.post(e,t,o)}catch(t){if(t instanceof s.AxiosError&&401===t.response?.status)throw new a.HudClientUnauthorizedError(`Unauthorized request for ${e}`);(0,u.logToHud)(`Failed request to ${e}, attempt ${i+1} of ${r}. Error: ${t}`),await new Promise(e=>setTimeout(e,1))}throw new a.HudClientExceededMaxRetries(`Exceeded max retries for ${e}`)}},3903:e=>{e.exports=require("uuid")},4414:function(e,t,o){var r=this&&this.__createBinding||(Object.create?function(e,t,o,r){void 0===r&&(r=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,i)}:function(e,t,o,r){void 0===r&&(r=o),e[r]=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}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&r(t,e,o);return i(t,e),t},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.uploadAllSourceMaps=t.uploadSourceMap=void 0;const s=o(2546),u=a(o(2305)),l=n(o(9896)),d=o(5231),c=o(870),f=o(3066);async function p(e){const{buildId:t,filePath:o,hudKey:r}=e,i=new u.default;i.append("build_id",t),i.append("token",r);try{const e=await l.promises.readFile(o,"utf8"),t=JSON.parse(e);delete t.sourcesContent,i.append("sourcemap",JSON.stringify(t),{filename:"sourcemap",contentType:"application/json"})}catch(e){return(0,d.logToHud)(`failed parsing source map, skipping upload. Error: ${e}`),void(0,d.logToUser)(s.UserErrorLogs.EsbuildFailedParsingSourcemap())}try{await(0,f.requestRelentless)(`${s.hudConfig.sink.url}/${s.hudConfig.endpoints.sourceMap}`,i,{headers:{"Content-Type":"multipart/form-data"},timeout:s.hudConfig.esbuildUploadSourceMapTimeout})}catch(e){if(e instanceof Error&&e.message.includes("Unauthorized"))throw e;(0,d.logToHud)(`failed uploading source map. File: ${o}, Error: ${e}`),(0,d.logToUser)(s.UserErrorLogs.EsbuildFailedUploadingSourcemap(o))}}t.uploadSourceMap=p,t.uploadAllSourceMaps=async function(e,t){if(process.env.HUD_SKIP_SOURCEMAP_UPLOAD)(0,d.logToHud)("Skipping source map upload due to env var");else{(0,d.logToHud)(`Uploading source maps for ${e.length} files`);try{const o=[];for(const{buildId:r,filepath:i}of e){const e=`${i}.map`;try{await l.promises.access(e,l.constants.F_OK),o.push({buildId:r,filePath:e,hudKey:t})}catch{(0,d.logToHud)(`No source map found for file: ${i}`)}}await(0,c.limitedParallel)(o,10,p,!0),(0,d.logToHud)("Finished uploading source maps")}catch{return(0,d.logToUser)(s.UserErrorLogs.EsbuildFailedUploadingSourcemapUnauthorized()),void(0,d.setDontSendLogs)()}}}},5231:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getShouldSendLogs=t.setDontSendLogs=t.exportBuildLogs=t.logToHud=t.logToHudDebug=t.logToUser=void 0;const r=o(2546),i=o(6982),n=o(870),a=o(3066),s=r.hudConfig.esbuildPluginMessagePrefix,u=(0,i.randomUUID)(),l=[];let d=!0;function c(e,t=!0){"true"===process.env.HUD_PLUGIN_VERBOSE&&(t&&(e=(0,r.formatLogMessage)(`${s}${e}`)),console.log(e)),l.push({message:e,SessionID:u,timestamp:Date.now()})}async function f(e){await(0,a.requestRelentless)(r.hudConfig.pluginsLogEndpoint,{messages:e},{headers:{"x-hudx-plugin":"true","Content-Type":"application/json"}})}t.logToUser=function(e){let t="";t="string"==typeof e?(0,r.formatLogMessage)(`${s}${e}`):(0,r.formatLogMessage)(`${s}${e.message}`,e.errCode,e.moreInfo),console.log(t),c(t,!1)},t.logToHudDebug=function(e,t=!0){"true"===process.env.HUD_PLUGIN_DEBUG&&c(e,t)},t.logToHud=c,t.exportBuildLogs=async function(e){const t=[];for(let o=0;o<l.length;o+=r.hudConfig.esbuildPluginLogsBatchSize){const i=l.slice(o,o+r.hudConfig.esbuildPluginLogsBatchSize).map(t=>({...t,accessToken:e}));t.push(i)}await(0,n.limitedParallel)(t,10,f)},t.setDontSendLogs=function(){d=!1},t.getShouldSendLogs=function(){return d}},6928:e=>{e.exports=require("path")},6932:function(e,t,o){var r=this&&this.__createBinding||(Object.create?function(e,t,o,r){void 0===r&&(r=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,i)}:function(e,t,o,r){void 0===r&&(r=o),e[r]=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}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&r(t,e,o);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.verifyFileContent=t.createMark=t.markFile=t.markFileAsHudModified=t.verifyAndMarkFinalFiles=t.HudBuildError=void 0;const a=o(2030),s=o(2546),u=n(o(2784)),l=o(3903),d=n(o(9154)),c=o(7085),f=o(5231);class p extends Error{}function g(e,t){return`/*modifiedByHudESBuildPlugin-${t}*/${e}`}function h(e,t){const o=t?"Start":"End";return`;globalThis && (globalThis.${s.hudConfig.esbuildGlobalVar}="${o}:${e}");`}function m(e,t,o){try{(0,f.logToHud)(`Verifying file content: ${t}, with marks`),new d.Script(e),(0,f.logToHud)(`Editing in splits file content: ${t}`);const{transformedCode:r,editedChunksSizes:i}=(0,a.editInSplits)(e,t,o,!0,e=>!e.includes("node_modules"));if(!r)throw new p(`Failed verify file content, ${t}`);for(let e=0;e<i.length;e+=c.LOG_CHUNKS_SIZE_BATCH){const t=JSON.stringify(i.slice(e,e+c.LOG_CHUNKS_SIZE_BATCH));(0,f.logToHudDebug)(`Edited chunks sizes: ${t}`)}(0,f.logToHud)(`Verifying new file content: ${t}`),new d.Script(r),(0,f.logToHud)(`Verified new file content: ${t}`)}catch(e){throw(0,f.logToHud)(`Failed verify file content, ${t}, error: ${e}`),new p(`Failed verify file content, ${t}`)}}t.HudBuildError=p,t.verifyAndMarkFinalFiles=async function(e,t,o){const r=[];for(const i of e){if(!i.path.endsWith(".js")){t&&await(0,c.writeFileAndFolder)(i.path,i.contents);continue}if(!i.text.includes(s.hudConfig.esbuildGlobalVar)){t&&await(0,c.writeFileAndFolder)(i.path,i.contents);continue}const e=(0,l.v5)(i.contents,s.hudConfig.bundlerBuildUuidNamespace);r.push({filepath:i.path,buildId:e});const n=g(i.text,e);process.env.HUD_SKIP_FILE_VALIDATION||m(n,i.path,o),i.contents=new Uint8Array(Buffer.from(n,"utf8")),t&&await(0,c.writeFileAndFolder)(i.path,i.contents)}return r},t.markFileAsHudModified=g,t.markFile=function(e,t){const o=u.markFile(t,{data:{filename:e,format:"esm"},initialStatements:[h(e,!0)],suffixStatements:[h(e,!1)]});if(!o||!o.code||!o.map)throw new Error("Failed generating ast");return function(e,t){let o;return void 0===t?e:(o="string"==typeof t||t instanceof String?Buffer.from(t.toString()).toString("base64"):Buffer.from(JSON.stringify(t)).toString("base64"),e+`\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${o}`)}(o.code,o.map)},t.createMark=h,t.verifyFileContent=m},6982:e=>{e.exports=require("crypto")},7085:function(e,t,o){var r=this&&this.__createBinding||(Object.create?function(e,t,o,r){void 0===r&&(r=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,i)}:function(e,t,o,r){void 0===r&&(r=o),e[r]=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}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&r(t,e,o);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.plugin=t.getModuleRoot=t.writeFileAndFolder=t.LOG_CHUNKS_SIZE_BATCH=void 0;const a=o(8528),s=o(2030),u=o(6982),l=n(o(9896)),d=n(o(857)),c=n(o(6928)),f=o(2546),p=o(9929),g=o(5231),h=o(6932),m=o(4414);async function b(e,t,o,r,i){if(!(o&&r&&i&&r.test(e)))return;const n=c.join(i,e),a=c.dirname(n);try{await l.promises.access(a)}catch{await l.promises.mkdir(a,{recursive:!0})}await l.promises.writeFile(n,t,"utf8");const s=await o(n);return s?.contents&&(t=s.contents),t}async function y(e){let t=c.dirname(e);for(let e=0;e<30&&"/"!==t;e++){const e=c.join(t,"package.json");try{return await l.promises.access(e),t}catch{t=c.dirname(t)}}}t.LOG_CHUNKS_SIZE_BATCH=f.hudConfig.esbuildPluginLogsChunkSize,t.writeFileAndFolder=async function(e,t){const o=c.dirname(e);try{await l.promises.stat(o)}catch{await l.promises.mkdir(o,{recursive:!0})}await l.promises.writeFile(e,t)},t.getModuleRoot=y;const v="hud-esbuild-plugin";t.plugin=e=>({name:v,async setup(t){if("node"!==t.initialOptions.platform)return void(0,g.logToUser)(f.UserErrorLogs.EsbuildUnsupportedPlatform());if("win32"===d.platform())return void(0,g.logToUser)(f.UserErrorLogs.EsbuildUnsupportedWindows());const o=e?.hudKey??process.env.HUD_KEY;if(!o)return void(0,g.logToUser)(f.UserErrorLogs.EsbuildMissingKey());const r=e?.includeModules??(0,f.getModulesToTraceFromEnv)()??[],i=(0,s.createCheckers)(r);(0,g.logToUser)("started running");const n=t.initialOptions.write??!0;t.initialOptions.write=!1;const w="esm"===t.initialOptions?.format?a.Format.esm:a.Format.cjs,{callback:_,filter:S,tempDir:T}=await async function(e){const t=e.initialOptions;if(!t.plugins)return;const o=t.plugins.findIndex(e=>e.name===v),r=t.plugins[o+1];if(!r||"datadog-esbuild"!==r.name)return;let i;(0,g.logToHud)("datadog-esbuild plugin detected");const n={...e,onLoad:(...e)=>{i=e},onStart:()=>{},onEnd:()=>{},onResolve:()=>{},onDispose:()=>{}};if(r.setup(n),!i)return void(0,g.logToHud)("datadog-esbuild plugin detected but failed receive onLoad callback");const a=c.join(d.tmpdir(),`hud-${(0,u.randomUUID)()}`);try{return await l.promises.access(a),void(0,g.logToUser)("temp dir already exists, try rerunning the build.")}catch(e){}return(0,g.logToHud)(`creating temp dir to be used by datadog plugin.\n\tPath: ${a}`),await l.promises.mkdir(a,{recursive:!0}),{filter:i[0].filter,callback:i[1],tempDir:a}}(t)??{},O=new Set(t.initialOptions.external||[]),F=new Map;t.onResolve({filter:/.*/},async e=>{if(e.pluginData?.hud?.calledFromHud)return;if(O.has(e.path))return;if(!f.hudConfig.frameworksToPatch.get(e.path)?.enableEsbuild)return;const o={...e};delete o.path;const r=await t.resolve(e.path,{...o,pluginData:{...e.pluginData,hud:{calledFromHud:!0}}}),i=await y(r.path);i&&(F.set(i,e.path),(0,g.logToHud)(`mapping framework: ${i} => ${e.path}`))}),t.onLoad({filter:/.*\.(js|ts)$/},async e=>{try{const t=_?async t=>await _({...e,path:t}):void 0;if((0,s.skip)(e.path,i)){const o=await(0,p.getFrameworkContentSuffix)(e.path,F);if(!o)return;let r=await l.promises.readFile(e.path,"utf8");return r=await b(e.path,r,t,S,T)??r,r+=o,{contents:r,loader:e.path.endsWith("ts")?"ts":"js",resolveDir:c.dirname(e.path)}}let o=await l.promises.readFile(e.path,"utf8");return o=(0,h.markFile)(e.path,o),o=await b(e.path,o,t,S,T)??o,o+=await(0,p.getFrameworkContentSuffix)(e.path,F)??"",{contents:o,loader:e.path.endsWith("ts")?"ts":"js",resolveDir:c.dirname(e.path)}}catch(t){return(0,g.logToHud)(`failed patching file "${e.path}", fallbacking to original loader. Error: ${t}`),void(0,g.logToUser)(`failed patching file "${e.path}", fallbacking to original loader`)}}),t.onEnd(async e=>{if(!e?.outputFiles)return;let t;try{t=await(0,h.verifyAndMarkFinalFiles)(e.outputFiles,n,w),(0,g.logToUser)("finished")}catch(e){throw(0,g.logToHud)(`failed validating. Error: ${e}`),(0,g.logToUser)(f.UserErrorLogs.EsbuildFailedBundling()),e}finally{if(t)try{await(0,m.uploadAllSourceMaps)(t,o)}catch(e){(0,g.logToHud)(`failed uploading source maps. Shouldnt get here since we catch all errors in verifyAndMarkFinalFiles, error: ${e}`)}try{if(T)try{await l.promises.access(T),(0,g.logToHud)("cleaning temp dir"),await l.promises.rm(T,{recursive:!0,force:!0})}catch{}}catch(e){(0,g.logToHud)(`failed cleaning temp dir. Error: ${e}`)}try{!process.env.HUD_SKIP_BUILD_LOG_EXPORT&&(0,g.getShouldSendLogs)()&&await(0,g.exportBuildLogs)(o)}catch(e){"true"===process.env.HUD_PLUGIN_VERBOSE&&"true"===process.env.HUD_DEBUG&&(0,g.logToUser)(`Failed exporting build logs. Error: ${e}`)}}})}})},8528:e=>{e.exports=require("./dto")},8938:e=>{e.exports=require("axios")},9154:e=>{e.exports=require("vm")},9896:e=>{e.exports=require("fs")},9929:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFrameworkContentSuffix=void 0;const r=o(8528),i=o(2030),n=o(2546),a=o(7085),s=o(5231);t.getFrameworkContentSuffix=async function(e,t){const o=[...t.entries()].find(([t,o])=>e.startsWith(t));if(!o)return;const[u,l]=o;let d=l+e.slice(u.length);(d.endsWith("index.js")||d.endsWith("index.ts"))&&(d=d.slice(0,d.length-9));const c=n.hudConfig.frameworksToPatch.get(d);if(!(c?.enableEsbuild&&c?.patcher&&c?.version))return;(0,s.logToHud)(`Patching framwork: ${d}`);const f=await(0,a.getModuleRoot)(e);if(!f)return void(0,s.logToHud)(`Failed to find package.json for ${d}`);const p=(0,i.extractModuleVersion)(f);if((0,s.logToHud)(`Patching framework ${d}, version: ${p}`),(0,i.getFrameworkPatcher)(c.patcher).isSupported(f,d,c.version,c.extraInfo))return`\n ;\n try {\n const { hudRITM, infoSafeLog: hudSafeLogger } = require("hud-sdk/instrument");\n if (globalThis.hudRunningMode === ${r.HudRunningMode.enabled}) {\n if (typeof hudRITM === "function") {\n if (typeof hudSafeLogger === "function") {\n hudSafeLogger("esbuild patching ${d}");\n }\n module.exports = hudRITM(module.exports, "${d}", "hud-esbuild-folder-should-not-exists");\n }\n }\n } catch (e) {\n try {\n const { errorSafeLog: hudSafeLogger } = require("hud-sdk/internal");\n if (typeof hudSafeLogger === "function") {\n hudSafeLogger(\`esbuild patching ${f} failed: \${e}\`);\n }\n } catch {}\n }\n `;(0,s.logToHud)(`Failed to patch ${d}, unsupported version: ${p}`)}}},t={};return function o(r){var i=t[r];if(void 0!==i)return i.exports;var n=t[r]={exports:{}};return e[r].call(n.exports,n,n.exports,o),n.exports}(7085)})());
|
|
2
2
|
//# sourceMappingURL=esbuildPlugin.js.map
|
package/dist/cjs/globalstate.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var o=t();for(var n in o)("object"==typeof exports?exports:e)[n]=o[n]}}(global,(()=>(()=>{"use strict";var e={820:function(e,t,o){var n=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,i)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),i=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||n(t,e,o)};Object.defineProperty(t,"__esModule",{value:!0}),i(o(7764),t),i(o(4583),t),i(o(2314),t),i(o(1321),t),i(o(3764),t),i(o(2207),t),i(o(8714),t),i(o(2525),t),i(o(3973),t),i(o(1364),t),i(o(7398),t)},1321:function(e,t,o){var n=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,i)}: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}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&n(t,e,o);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.GraphQLDocumentMetadata=t.getDocumentsMetadata=void 0;const a=r(o(6982));t.getDocumentsMetadata=function(){const e=s;return s=[],e};let s=[];t.GraphQLDocumentMetadata=class{name;timeTook;hash;selectionNames;constructor(e,t){this.name=e.definitions[0]?.name?.value,this.hash=a.createHash("sha256").update(e.loc?.source?.body).digest("hex"),this.selectionNames=e.definitions.flatMap((e=>e.selectionSet.selections.map((e=>e.name.value)))),this.timeTook=t}save(){s.push(this)}}},1364:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateAndGetUserInput=t.saveInstrumentationIndicator=t.saveHudRunningFromSetup=t.forceHudEnable=t.detachHud=t.clearUserIndicatorsTimeouts=t.clearInstrumentationIndicator=t.clearMetricsIndicator=t.clearInitGuard=t.hookMessageChannel=t.resetGlobals=t.initGlobals=void 0;const n=o(8528),i=o(2546),r=o(8167);function a(){globalThis.hudProcessedFiles=[],globalThis.huddBinWidth=i.hudConfig.huddBinWidth,globalThis._hud_S=new Array(1e3).fill(""),globalThis._hud_SI={value:0},globalThis.hudLoadedModules=[],globalThis.hudPatched=new Set,globalThis.HudSourceMapCache=new Map,globalThis.hudExpressState=[]}function s(){clearTimeout(globalThis.hudInitGuard),globalThis.hudInitGuard=void 0}function l(){clearTimeout(globalThis.hudMetricsIndicator),globalThis.hudMetricsIndicator=void 0}function u(){clearTimeout(globalThis.hudInstrumentationIndicator),globalThis.hudInstrumentationIndicator=void 0}function d(e=!0,t=!1){if(i.app_logger.warn("Detaching hud"),t||e&&hudRunningMode!==n.HudRunningMode.detached){const e=(0,i.getFirstError)();i.customer_logger.log(i.UserErrorLogs.ShutdownGracefully(e))}globalThis.hudRunningMode=n.HudRunningMode.detached}t.initGlobals=function(){globalThis.hudGlobalInitGuard||(globalThis.hudGlobalInitGuard=!0,globalThis.hudRunMutex=!1,globalThis.hudRanOnRequire=!1,globalThis.hudRanOnImport=!1,globalThis.hudInitGuard=void 0,globalThis.hudInstrumentationIndicator=void 0,globalThis.hudMetricsIndicator=void 0,globalThis.hudDeclarationsFound=!1,globalThis.hudStartTime=new Date,globalThis.hudCalls={},globalThis.hudRunningMode=n.HudRunningMode.enabled,globalThis.hudExtensionId=void 0,globalThis._hud_F="",globalThis.hudShouldLinkFunction=!1,globalThis.hudExecutionFlowMaxLength=i.hudConfig.investigation.limits.executionFlowMaxLength,globalThis.hudExceptionMaxLength=i.hudConfig.investigation.limits.exceptionMaxLength,globalThis.hudEnableInvestigation=i.hudConfig.dynamicConfig.enableInvestigation,function(){globalThis.hudSampleTable=[];const e=[[10,1],[30,2],[100,3],[500,11],[1e3,23],[5e3,53]];let t=0;for(const[o,n]of e){for(let e=t;e<o;e++)globalThis.hudSampleTable.push(e%n===0);t=o}}(),a())},t.resetGlobals=a,t.hookMessageChannel=function(){const{port1:e,port2:t}=new r.MessageChannel;return e.on("message",(e=>{"HudModulePatch"===e.key?(globalThis.hudPatched.add(e.hudPatched),globalThis.hudProcessedFiles.push(e.hudProcessedFiles),globalThis.hudInstrumentationIndicator&&(u(),globalThis.hudDeclarationsFound=!0)):"HudRetrieveFileCache"===e.key&&globalThis.HudSourceMapCache.set(e.filename,e.content)})),e.unref(),globalThis.hudHookPort=e,t},t.clearInitGuard=s,t.clearMetricsIndicator=l,t.clearInstrumentationIndicator=u,t.clearUserIndicatorsTimeouts=function(){s(),l(),u()},t.detachHud=d,t.forceHudEnable=function(){globalThis.forceHudEnable=!0},t.saveHudRunningFromSetup=function(){globalThis.hudIsRunningFromSetup=!0},t.saveInstrumentationIndicator=function(e){globalThis.hudInstrumentationIndicator=e,globalThis.hudInstrumentationIndicator.unref()},t.validateAndGetUserInput=function(){return i.hudConfig.userConfig.key||i.hudConfig.userConfig.service?i.hudConfig.userConfig.key?(0,i.isValidParam)(i.hudConfig.userConfig.key.value)?i.hudConfig.userConfig.service?(0,i.isValidParam)(i.hudConfig.userConfig.service.value)?{apiKey:i.hudConfig.userConfig.key.value,service:i.hudConfig.userConfig.service.value}:(i.hudConfig.disableOnBadServiceName&&d(!1),void i.customer_logger.log(i.UserErrorLogs.HudServiceInvalid(i.hudConfig.userConfig.service.source))):(i.hudConfig.disableOnBadServiceName&&d(!1),void i.customer_logger.log(i.UserErrorLogs.HudServiceNotSet(globalThis.hudStartFromAutoInit))):(i.hudConfig.disableOnBadApiKey&&d(!1),void i.customer_logger.log(i.UserErrorLogs.HudApiKeyInvalid(i.hudConfig.userConfig.key.source))):(i.hudConfig.disableOnBadApiKey&&d(!1),void i.customer_logger.log(i.UserErrorLogs.HudApiKeyNotSet(globalThis.hudStartFromAutoInit))):((i.hudConfig.disableOnBadApiKey||i.hudConfig.disableOnBadServiceName)&&d(!1),void i.customer_logger.log(i.UserErrorLogs.BothApiKeyAndServiceNotSet(globalThis.hudStartFromAutoInit)))}},2207:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getResolverIdBySelectionName=t.storeResolverIdBySelectionName=void 0;const o=new Map;t.storeResolverIdBySelectionName=function(e,t){o.set(t,e)},t.getResolverIdBySelectionName=function(e){return o.get(e)}},2314:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.swapTempToConstFlowId=t.clearFlowIdMappings=t.linkTemporaryToConsistenFlowId=t.getFlowIdFromMappings=t.getLinkedConsistentFlowId=t.fullEndpointFlowIdMap=void 0;const n=o(2546),i=o(7930),r=o(8590);t.fullEndpointFlowIdMap=new Map;const a=new Map;function s(e,t){let o=l(e,!1);return o?o.flowId:(u(t),o=l(e,!0),o?(o.isPartial&&!t&&n.app_logger.warn("Found partial endpoint for flow id even though partial aren't allowd",{flowId:e,consistentFlowId:o.flowId}),o.flowId):void 0)}function l(e,o){let n=t.fullEndpointFlowIdMap.get(e);return n?{flowId:n,isPartial:!1}:o?(n=a.get(e),n?{flowId:n,isPartial:!0}:void 0):void 0}function u(e){const o=[];globalThis.hudExpressState.forEach((e=>{try{o.push(...(0,i.extractEndpointsFromRouter)("",e))}catch(e){n.app_logger.error("Failed to extract endpoints from express",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})),o.forEach((e=>{if(e.partial_path)return;const o=e.flow_id;let i=t.fullEndpointFlowIdMap.get(o);i||(i=(0,n.generateEndpointFlowId)(e.path,e.methods),t.fullEndpointFlowIdMap.set(o,i))})),(0,r.getPartialEndpointDeclarationsFromStorage)().forEach((o=>{const i=o.flow_id;let r=t.fullEndpointFlowIdMap.get(i);r||(r=a.get(i),r||(r=(0,n.generateEndpointFlowId)(o.partial_path,o.methods),e?a.set(i,r):t.fullEndpointFlowIdMap.set(i,r)))}))}t.getLinkedConsistentFlowId=s,t.getFlowIdFromMappings=l,t.linkTemporaryToConsistenFlowId=u,t.clearFlowIdMappings=function(){t.fullEndpointFlowIdMap.clear(),a.clear()},t.swapTempToConstFlowId=function(e){e.forEach((e=>{"express"===e.framework&&(e.flow_id=s(e.flow_id,!0)??e.flow_id)}))}},2433:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getKoaEndpointDeclarationsFromStorage=t.storeKoaEndpointDeclaration=void 0;let o=[];t.storeKoaEndpointDeclaration=function(e){o.push(e)},t.getKoaEndpointDeclarationsFromStorage=function(){const e=o;return o=[],e}},2525:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeSqsQueueDeclaration=t.getSqsQueues=void 0;let o=[];t.getSqsQueues=function(){const e=o;return o=[],e},t.storeSqsQueueDeclaration=function(e){o.push(e)}},2546:e=>{e.exports=require("./lib")},3764:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeResolverDeclaration=t.getResolversDeclarations=void 0;let o=[];t.getResolversDeclarations=function(){const e=o;return o=[],e},t.storeResolverDeclaration=function(e){o.push(e)}},3973:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeFlowMetric=t.getFlowMetrics=void 0;let o=[];t.getFlowMetrics=function(){const e=o;return o=[],e},t.storeFlowMetric=function(e){o.push(e)}},4583:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getExpressEndpointDeclarations=void 0;const n=o(2546),i=o(2314),r=o(7930),a=o(8590);t.getExpressEndpointDeclarations=function(){let e=[];globalThis.hudExpressState.forEach((t=>{try{e=e.concat((0,r.extractEndpointsFromRouter)("",t))}catch(e){n.app_logger.error("Failed to extract endpoints from express",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})),e=e.concat((0,a.getRouterlessEndpointDeclarationsFromStorage)());const t=new Set;e.forEach((e=>{e.partial_path||t.add(e.flow_id)}));const o=e.filter((e=>!e.partial_path||!t.has(e.flow_id)&&(n.app_logger.info("Partial endpoint without full endpoint",{endpoint:e}),!0)));return(0,i.swapTempToConstFlowId)(o),o}},6982:e=>{e.exports=require("crypto")},7398:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getInvestigationDedupingCache=t.resetInvestigationDedupingCache=t.increaseInvestigationDedupingCache=t.increaseGlobalInvestigationTracking=t.setGlobalInvestigationTracking=t.globalInvestigationTracking=t.storeClosedInvestigation=t.getClosedInvestigations=void 0;let o=[];t.getClosedInvestigations=function(){const e=o;return o=[],e},t.storeClosedInvestigation=function(e){o.push(e)},t.globalInvestigationTracking=0,t.setGlobalInvestigationTracking=function(e){t.globalInvestigationTracking=e},t.increaseGlobalInvestigationTracking=function(){t.globalInvestigationTracking++};const n=new Map;t.increaseInvestigationDedupingCache=function(e,t){const o=n.get(e)??new Map,i=(o.get(t)??0)+1;o.set(t,i),n.set(e,o)},t.resetInvestigationDedupingCache=function(){n.clear()},t.getInvestigationDedupingCache=function(e){return n.get(e)??new Map}},7764:function(e,t,o){var n=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,i)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),i=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||n(t,e,o)};Object.defineProperty(t,"__esModule",{value:!0}),i(o(8714),t),i(o(2433),t),i(o(1321),t),i(o(3764),t),i(o(2207),t),i(o(4583),t),i(o(8590),t)},7930:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractEndpointsFromRouter=void 0;const n=o(8528),i=o(2546);function r(e,t){const o=[];for(const[r,a]of Object.entries(e.route[i.hudConfig.express.layerStateSymbol]))o.push(new n.EndpointDeclaration(r,a.methods,"express",t,a.layerPath));return Array.from(o.values())}t.extractEndpointsFromRouter=function e(t,o){let n=[];const s="true"===process.env.HUD_LOG_EXPRESS;if(!o.stack)return i.app_logger.error("Router without stack - bad OTEL version",{router:o}),n;for(const l of o.stack)if("router"===l.name){if(!l[i.hudConfig.express.routeNamesSymbol]){i.app_logger.error("Router layer without routes",{layer:l});continue}const o=t+l[i.hudConfig.express.routeNamesSymbol];n=n.concat(e(o,l.handle))}else l.route&&l.route[i.hudConfig.express.layerStateSymbol]?n=n.concat(r(l,t)):s&&!a.has(l.name)&&(a.add(l.name),i.app_logger.warn("Found unknown layer name when extracting endpoints",{layer:l.name}));return n};const a=new Set(["query","expressInit","mounted_app"])},8167:e=>{e.exports=require("worker_threads")},8528:e=>{e.exports=require("./dto")},8590:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeExpressEndpointDeclaration=t.getPartialEndpointDeclarationsFromStorage=t.storePartialEndpointDeclaration=t.getRouterlessEndpointDeclarationsFromStorage=void 0;const n=o(2546),i=o(2314);let r=[];t.getRouterlessEndpointDeclarationsFromStorage=function(){const e=r;return r=[],e};let a=[];t.storePartialEndpointDeclaration=function(e){a.push(e)},t.getPartialEndpointDeclarationsFromStorage=function(){const e=a;return a=[],e},t.storeExpressEndpointDeclaration=function(e){if(!i.fullEndpointFlowIdMap.has(e.flow_id)){if(e.path){const t=(0,n.generateEndpointFlowId)(e.path,e.methods);i.fullEndpointFlowIdMap.set(e.flow_id,t)}r.push(e)}}},8714:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeKafkaJSTopicDeclaration=t.getKafkaJSTopics=void 0;let o=[];t.getKafkaJSTopics=function(){const e=o;return o=[],e},t.storeKafkaJSTopicDeclaration=function(e){o.push(e)}}},t={};return function o(n){var i=t[n];if(void 0!==i)return i.exports;var r=t[n]={exports:{}};return e[n].call(r.exports,r,r.exports,o),r.exports}(820)})()));
|
|
1
|
+
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var o=t();for(var n in o)("object"==typeof exports?exports:e)[n]=o[n]}}(global,()=>(()=>{"use strict";var e={820:function(e,t,o){var n=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,i)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),i=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||n(t,e,o)};Object.defineProperty(t,"__esModule",{value:!0}),i(o(7764),t),i(o(4583),t),i(o(2314),t),i(o(1321),t),i(o(3764),t),i(o(2207),t),i(o(8714),t),i(o(2525),t),i(o(3973),t),i(o(1364),t),i(o(7398),t)},1321:function(e,t,o){var n=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,i)}: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}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o in e)"default"!==o&&Object.prototype.hasOwnProperty.call(e,o)&&n(t,e,o);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.GraphQLDocumentMetadata=t.getDocumentsMetadata=void 0;const a=r(o(6982));t.getDocumentsMetadata=function(){const e=s;return s=[],e};let s=[];t.GraphQLDocumentMetadata=class{name;timeTook;hash;selectionNames;constructor(e,t){this.name=e.definitions[0]?.name?.value,this.hash=a.createHash("sha256").update(e.loc?.source?.body).digest("hex"),this.selectionNames=e.definitions.flatMap(e=>e.selectionSet.selections.map(e=>e.name.value)),this.timeTook=t}save(){s.push(this)}}},1364:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateAndGetUserInput=t.saveInstrumentationIndicator=t.saveHudRunningFromSetup=t.forceHudEnable=t.detachHud=t.clearUserIndicatorsTimeouts=t.clearInstrumentationIndicator=t.clearMetricsIndicator=t.clearInitGuard=t.hookMessageChannel=t.resetGlobals=t.initGlobals=void 0;const n=o(8528),i=o(2546),r=o(8167);function a(){globalThis.hudProcessedFiles=[],globalThis.huddBinWidth=i.hudConfig.huddBinWidth,globalThis._hud_S=new Array(1e3).fill(""),globalThis._hud_SI={value:0},globalThis.hudLoadedModules=[],globalThis.hudPatched=new Set,globalThis.HudSourceMapCache=new Map,globalThis.hudExpressState=[]}function s(){clearTimeout(globalThis.hudInitGuard),globalThis.hudInitGuard=void 0}function l(){clearTimeout(globalThis.hudMetricsIndicator),globalThis.hudMetricsIndicator=void 0}function u(){clearTimeout(globalThis.hudInstrumentationIndicator),globalThis.hudInstrumentationIndicator=void 0}function d(e=!0,t=!1){if(i.app_logger.warn("Detaching hud"),t||e&&hudRunningMode!==n.HudRunningMode.detached){const e=(0,i.getFirstError)();i.customer_logger.log(i.UserErrorLogs.ShutdownGracefully(e))}globalThis.hudRunningMode=n.HudRunningMode.detached}t.initGlobals=function(){globalThis.hudGlobalInitGuard||(globalThis.hudGlobalInitGuard=!0,globalThis.hudRunMutex=!1,globalThis.hudRanOnRequire=!1,globalThis.hudRanOnImport=!1,globalThis.hudInitGuard=void 0,globalThis.hudInstrumentationIndicator=void 0,globalThis.hudMetricsIndicator=void 0,globalThis.hudDeclarationsFound=!1,globalThis.hudStartTime=new Date,globalThis.hudCalls={},globalThis.hudRunningMode=n.HudRunningMode.enabled,globalThis.hudExtensionId=void 0,globalThis._hud_F="",globalThis.hudShouldLinkFunction=!1,globalThis.hudExecutionFlowMaxLength=i.hudConfig.investigation.limits.executionFlowMaxLength,globalThis.hudExceptionMaxLength=i.hudConfig.investigation.limits.exceptionMaxLength,globalThis.hudEnableInvestigation=i.hudConfig.dynamicConfig.enableInvestigation,function(){globalThis.hudSampleTable=[];const e=[[10,1],[30,2],[100,3],[500,11],[1e3,23],[5e3,53]];let t=0;for(const[o,n]of e){for(let e=t;e<o;e++)globalThis.hudSampleTable.push(e%n===0);t=o}}(),a())},t.resetGlobals=a,t.hookMessageChannel=function(){const{port1:e,port2:t}=new r.MessageChannel;return e.on("message",e=>{"HudModulePatch"===e.key?(globalThis.hudPatched.add(e.hudPatched),globalThis.hudProcessedFiles.push(e.hudProcessedFiles),globalThis.hudInstrumentationIndicator&&(u(),globalThis.hudDeclarationsFound=!0)):"HudRetrieveFileCache"===e.key&&globalThis.HudSourceMapCache.set(e.filename,e.content)}),e.unref(),globalThis.hudHookPort=e,t},t.clearInitGuard=s,t.clearMetricsIndicator=l,t.clearInstrumentationIndicator=u,t.clearUserIndicatorsTimeouts=function(){s(),l(),u()},t.detachHud=d,t.forceHudEnable=function(){globalThis.forceHudEnable=!0},t.saveHudRunningFromSetup=function(){globalThis.hudIsRunningFromSetup=!0},t.saveInstrumentationIndicator=function(e){globalThis.hudInstrumentationIndicator=e,globalThis.hudInstrumentationIndicator.unref()},t.validateAndGetUserInput=function(){return i.hudConfig.userConfig.key||i.hudConfig.userConfig.service?i.hudConfig.userConfig.key?(0,i.isValidParam)(i.hudConfig.userConfig.key.value)?i.hudConfig.userConfig.service?(0,i.isValidParam)(i.hudConfig.userConfig.service.value)?{apiKey:i.hudConfig.userConfig.key.value,service:i.hudConfig.userConfig.service.value}:(i.hudConfig.disableOnBadServiceName&&d(!1),void i.customer_logger.log(i.UserErrorLogs.HudServiceInvalid(i.hudConfig.userConfig.service.source))):(i.hudConfig.disableOnBadServiceName&&d(!1),void i.customer_logger.log(i.UserErrorLogs.HudServiceNotSet(globalThis.hudStartFromAutoInit))):(i.hudConfig.disableOnBadApiKey&&d(!1),void i.customer_logger.log(i.UserErrorLogs.HudApiKeyInvalid(i.hudConfig.userConfig.key.source))):(i.hudConfig.disableOnBadApiKey&&d(!1),void i.customer_logger.log(i.UserErrorLogs.HudApiKeyNotSet(globalThis.hudStartFromAutoInit))):((i.hudConfig.disableOnBadApiKey||i.hudConfig.disableOnBadServiceName)&&d(!1),void i.customer_logger.log(i.UserErrorLogs.BothApiKeyAndServiceNotSet(globalThis.hudStartFromAutoInit)))}},2207:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getResolverIdBySelectionName=t.storeResolverIdBySelectionName=void 0;const o=new Map;t.storeResolverIdBySelectionName=function(e,t){o.set(t,e)},t.getResolverIdBySelectionName=function(e){return o.get(e)}},2314:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.swapTempToConstFlowId=t.clearFlowIdMappings=t.linkTemporaryToConsistenFlowId=t.getFlowIdFromMappings=t.getLinkedConsistentFlowId=t.fullEndpointFlowIdMap=void 0;const n=o(2546),i=o(7930),r=o(8590);t.fullEndpointFlowIdMap=new Map;const a=new Map;function s(e,t){let o=l(e,!1);return o?o.flowId:(u(t),o=l(e,!0),o?(o.isPartial&&!t&&n.app_logger.warn("Found partial endpoint for flow id even though partial aren't allowd",{flowId:e,consistentFlowId:o.flowId}),o.flowId):void 0)}function l(e,o){let n=t.fullEndpointFlowIdMap.get(e);return n?{flowId:n,isPartial:!1}:o?(n=a.get(e),n?{flowId:n,isPartial:!0}:void 0):void 0}function u(e){const o=[];globalThis.hudExpressState.forEach(e=>{try{o.push(...(0,i.extractEndpointsFromRouter)("",e))}catch(e){n.app_logger.error("Failed to extract endpoints from express",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}),o.forEach(e=>{if(e.partial_path)return;const o=e.flow_id;let i=t.fullEndpointFlowIdMap.get(o);i||(i=(0,n.generateEndpointFlowId)(e.path,e.methods),t.fullEndpointFlowIdMap.set(o,i))}),(0,r.getPartialEndpointDeclarationsFromStorage)().forEach(o=>{const i=o.flow_id;let r=t.fullEndpointFlowIdMap.get(i);r||(r=a.get(i),r||(r=(0,n.generateEndpointFlowId)(o.partial_path,o.methods),e?a.set(i,r):t.fullEndpointFlowIdMap.set(i,r)))})}t.getLinkedConsistentFlowId=s,t.getFlowIdFromMappings=l,t.linkTemporaryToConsistenFlowId=u,t.clearFlowIdMappings=function(){t.fullEndpointFlowIdMap.clear(),a.clear()},t.swapTempToConstFlowId=function(e){e.forEach(e=>{"express"===e.framework&&(e.flow_id=s(e.flow_id,!0)??e.flow_id)})}},2433:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getKoaEndpointDeclarationsFromStorage=t.storeKoaEndpointDeclaration=void 0;let o=[];t.storeKoaEndpointDeclaration=function(e){o.push(e)},t.getKoaEndpointDeclarationsFromStorage=function(){const e=o;return o=[],e}},2525:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeSqsQueueDeclaration=t.getSqsQueues=void 0;let o=[];t.getSqsQueues=function(){const e=o;return o=[],e},t.storeSqsQueueDeclaration=function(e){o.push(e)}},2546:e=>{e.exports=require("./lib")},2987:e=>{e.exports=require("perf_hooks")},3764:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeResolverDeclaration=t.getResolversDeclarations=void 0;let o=[];t.getResolversDeclarations=function(){const e=o;return o=[],e},t.storeResolverDeclaration=function(e){o.push(e)}},3973:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeFlowMetric=t.getFlowMetrics=void 0;let o=[];t.getFlowMetrics=function(){const e=o;return o=[],e},t.storeFlowMetric=function(e){o.push(e)}},4583:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getExpressEndpointDeclarations=void 0;const n=o(2546),i=o(2314),r=o(7930),a=o(8590);t.getExpressEndpointDeclarations=function(){let e=[];globalThis.hudExpressState.forEach(t=>{try{e=e.concat((0,r.extractEndpointsFromRouter)("",t))}catch(e){n.app_logger.error("Failed to extract endpoints from express",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}),e=e.concat((0,a.getRouterlessEndpointDeclarationsFromStorage)());const t=new Set;e.forEach(e=>{e.partial_path||t.add(e.flow_id)});const o=e.filter(e=>!e.partial_path||!t.has(e.flow_id)&&(n.app_logger.info("Partial endpoint without full endpoint",{endpoint:e}),!0));return(0,i.swapTempToConstFlowId)(o),o}},6982:e=>{e.exports=require("crypto")},7398:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getLastMetrics=t.saveMachineMetric=t.getInvestigationDedupingCache=t.resetInvestigationDedupingCache=t.increaseInvestigationDedupingCache=t.increaseGlobalInvestigationTracking=t.setGlobalInvestigationTracking=t.globalInvestigationTracking=t.storeClosedInvestigation=t.getClosedInvestigations=void 0;const n=o(2546),i=o(2987);let r=[];t.getClosedInvestigations=function(){const e=r;return r=[],e},t.storeClosedInvestigation=function(e){r.push(e)},t.globalInvestigationTracking=0,t.setGlobalInvestigationTracking=function(e){t.globalInvestigationTracking=e},t.increaseGlobalInvestigationTracking=function(){t.globalInvestigationTracking++};const a=new Map;t.increaseInvestigationDedupingCache=function(e,t){const o=a.get(e)??new Map,n=(o.get(t)??0)+1;o.set(t,n),a.set(e,o)},t.resetInvestigationDedupingCache=function(){a.clear()},t.getInvestigationDedupingCache=function(e){return a.get(e)??new Map};const s=[];t.saveMachineMetric=function(){const e=process.cpuUsage(),t=i.performance.eventLoopUtilization();s.push({cpuUsage:e,elu:t,timestamp:Date.now()}),s.length>n.hudConfig.machineMetricsSavedLength&&s.shift()},t.getLastMetrics=function(){return s[0]}},7764:function(e,t,o){var n=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var i=Object.getOwnPropertyDescriptor(t,o);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,i)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),i=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||n(t,e,o)};Object.defineProperty(t,"__esModule",{value:!0}),i(o(8714),t),i(o(2433),t),i(o(1321),t),i(o(3764),t),i(o(2207),t),i(o(4583),t),i(o(8590),t)},7930:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extractEndpointsFromRouter=void 0;const n=o(8528),i=o(2546);function r(e,t){const o=[];for(const[r,a]of Object.entries(e.route[i.hudConfig.express.layerStateSymbol]))o.push(new n.EndpointDeclaration(r,a.methods,"express",t,a.layerPath));return Array.from(o.values())}t.extractEndpointsFromRouter=function e(t,o){let n=[];const s="true"===process.env.HUD_LOG_EXPRESS;if(!o.stack)return i.app_logger.error("Router without stack - bad OTEL version",{router:o}),n;for(const l of o.stack)if("router"===l.name){if(!l[i.hudConfig.express.routeNamesSymbol]){i.app_logger.error("Router layer without routes",{layer:l});continue}const o=t+l[i.hudConfig.express.routeNamesSymbol];n=n.concat(e(o,l.handle))}else l.route&&l.route[i.hudConfig.express.layerStateSymbol]?n=n.concat(r(l,t)):s&&!a.has(l.name)&&(a.add(l.name),i.app_logger.warn("Found unknown layer name when extracting endpoints",{layer:l.name}));return n};const a=new Set(["query","expressInit","mounted_app"])},8167:e=>{e.exports=require("worker_threads")},8528:e=>{e.exports=require("./dto")},8590:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeExpressEndpointDeclaration=t.getPartialEndpointDeclarationsFromStorage=t.storePartialEndpointDeclaration=t.getRouterlessEndpointDeclarationsFromStorage=void 0;const n=o(2546),i=o(2314);let r=[];t.getRouterlessEndpointDeclarationsFromStorage=function(){const e=r;return r=[],e};let a=[];t.storePartialEndpointDeclaration=function(e){a.push(e)},t.getPartialEndpointDeclarationsFromStorage=function(){const e=a;return a=[],e},t.storeExpressEndpointDeclaration=function(e){if(!i.fullEndpointFlowIdMap.has(e.flow_id)){if(e.path){const t=(0,n.generateEndpointFlowId)(e.path,e.methods);i.fullEndpointFlowIdMap.set(e.flow_id,t)}r.push(e)}}},8714:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeKafkaJSTopicDeclaration=t.getKafkaJSTopics=void 0;let o=[];t.getKafkaJSTopics=function(){const e=o;return o=[],e},t.storeKafkaJSTopicDeclaration=function(e){o.push(e)}}},t={};return function o(n){var i=t[n];if(void 0!==i)return i.exports;var r=t[n]={exports:{}};return e[n].call(r.exports,r,r.exports,o),r.exports}(820)})());
|
|
2
2
|
//# sourceMappingURL=globalstate.js.map
|