@lensmcp/cluster 1.26.2 → 1.26.3

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.
Files changed (63) hide show
  1. package/build-host.js +1 -1
  2. package/devserver-host.d.ts +5 -0
  3. package/devserver-host.js +1 -1
  4. package/executors/gateway/runtime/auth.js +1 -1
  5. package/executors/gateway/runtime/control.d.ts +25 -0
  6. package/executors/gateway/runtime/control.js +2 -2
  7. package/executors/gateway/runtime/discovery.js +1 -1
  8. package/executors/gateway/runtime/docker-sweep.d.ts +51 -0
  9. package/executors/gateway/runtime/docker-sweep.js +1 -0
  10. package/executors/gateway/runtime/edge.d.ts +2 -0
  11. package/executors/gateway/runtime/edge.js +1 -1
  12. package/executors/gateway/runtime/frontend-updates.d.ts +24 -0
  13. package/executors/gateway/runtime/frontend-updates.js +1 -0
  14. package/executors/gateway/runtime/handler.js +1 -1
  15. package/executors/gateway/runtime/legacy-dashboard-link.d.ts +10 -0
  16. package/executors/gateway/runtime/legacy-dashboard-link.js +1 -0
  17. package/executors/gateway/runtime/lens-children.d.ts +9 -0
  18. package/executors/gateway/runtime/lens-children.js +1 -1
  19. package/executors/gateway/runtime/lifecycle.d.ts +2 -0
  20. package/executors/gateway/runtime/lifecycle.js +4 -4
  21. package/executors/gateway/runtime/peer-hub.d.ts +54 -0
  22. package/executors/gateway/runtime/peer-hub.js +1 -0
  23. package/executors/gateway/runtime/proxy.js +1 -1
  24. package/executors/gateway/runtime/remote-instances.d.ts +167 -0
  25. package/executors/gateway/runtime/remote-instances.js +1 -0
  26. package/executors/gateway/runtime/run-routes.d.ts +186 -0
  27. package/executors/gateway/runtime/run-routes.js +1 -0
  28. package/executors/gateway/runtime/server.js +2 -2
  29. package/executors/gateway/runtime/service-updates.d.ts +44 -0
  30. package/executors/gateway/runtime/service-updates.js +1 -0
  31. package/executors/gateway/runtime/shared-build.d.ts +8 -1
  32. package/executors/gateway/runtime/shared-build.js +4 -4
  33. package/executors/gateway/runtime/types.d.ts +54 -0
  34. package/executors/gateway/runtime/update-wiring.d.ts +57 -0
  35. package/executors/gateway/runtime/update-wiring.js +2 -0
  36. package/executors/gateway/runtime/updates.d.ts +148 -0
  37. package/executors/gateway/runtime/updates.js +1 -0
  38. package/executors/gateway/runtime/upgrade.js +1 -1
  39. package/executors/serve/serve.impl.js +1 -1
  40. package/executors/serve/updates-gate.d.ts +147 -0
  41. package/executors/serve/updates-gate.js +2 -0
  42. package/main.devserver.js +10 -10
  43. package/package.json +5 -5
  44. package/program-id.d.ts +4 -0
  45. package/program-id.js +1 -0
  46. package/shared-build/host.d.ts +102 -2
  47. package/shared-build/host.js +3 -3
  48. package/shared-build/protocol.d.ts +59 -3
  49. package/shared-build/protocol.js +1 -1
  50. package/shared-build/shared-compilation.d.ts +21 -0
  51. package/shared-build/shared-compilation.js +3 -3
  52. package/static-checks-record.d.ts +391 -0
  53. package/static-checks-record.js +5 -0
  54. package/tsgo-check-plugin.d.ts +107 -43
  55. package/tsgo-check-plugin.js +4 -5
  56. package/tsgo-shim.d.ts +112 -0
  57. package/tsgo-shim.js +2 -0
  58. package/typecheck-bus.d.ts +36 -5
  59. package/typecheck-bus.js +4 -4
  60. package/typecheck-memory.d.ts +187 -0
  61. package/typecheck-memory.js +1 -0
  62. package/typecheck-queue.d.ts +41 -3
  63. package/typecheck-queue.js +1 -1
package/main.devserver.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var yt=Object.defineProperty;var u=(d,_)=>yt(d,"name",{value:_,configurable:!0});var gt=Object.defineProperty,a=u((d,_)=>gt(d,"name",{value:_,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0}),exports.redactInspectorUrls=exports.inspectorPortOf=exports.DEBUG_FIXED_PORTS_ENV=exports.mayDriveThePool=exports.isOwnerOnlyTransport=exports.gatewayManaged=void 0,exports.tell=tell,exports.usesFixedInspectorPorts=usesFixedInspectorPorts,exports.inspectorPortFor=inspectorPortFor;const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),node_child_process_1=require("node:child_process"),http=tslib_1.__importStar(require("node:http")),readline=tslib_1.__importStar(require("node:readline")),inspector=tslib_1.__importStar(require("node:inspector")),util=tslib_1.__importStar(require("node:util")),v8=tslib_1.__importStar(require("node:v8")),child_process_env_1=require("./child-process-env"),exit_reason_1=require("./exit-reason"),worker_supervisor_1=require("./worker-supervisor"),hot_swap_registries_1=require("./hot-swap-registries"),process_name_1=require("./process-name"),inspector_secret_1=require("./inspector-secret");Object.defineProperty(exports,"inspectorPortOf",{enumerable:!0,get:a(function(){return inspector_secret_1.inspectorPortOf},"get")}),Object.defineProperty(exports,"redactInspectorUrls",{enumerable:!0,get:a(function(){return inspector_secret_1.redactInspectorUrls},"get")});const devserver_transport_1=require("./devserver-transport");Object.defineProperty(exports,"gatewayManaged",{enumerable:!0,get:a(function(){return devserver_transport_1.gatewayManaged},"get")}),Object.defineProperty(exports,"isOwnerOnlyTransport",{enumerable:!0,get:a(function(){return devserver_transport_1.isOwnerOnlyTransport},"get")}),Object.defineProperty(exports,"mayDriveThePool",{enumerable:!0,get:a(function(){return devserver_transport_1.mayDriveThePool},"get")});const schema_first_instance_1=require("./schema-first-instance"),redis_disconnect_fix_1=require("./redis-disconnect-fix"),error_stack_release_1=require("./error-stack-release"),swap_recycle_1=require("./swap-recycle"),swap_mode_1=require("./swap-mode"),handoff_retire_1=require("./handoff-retire"),gc_notice_1=require("./gc-notice"),pod_sock_1=require("./pod-sock"),notice_generation_1=require("./notice-generation"),service_build_events_1=require("./service-build-events"),stdio_guard_1=require("./stdio-guard"),bundle_parent_1=require("./bundle-parent"),checkout_cache_1=require("./checkout-cache"),dev_devtool_1=require("./dev-devtool"),worker_retire_1=require("./worker-retire"),devserver_host_1=require("./devserver-host"),pod_memory_1=require("./pod-memory"),pod_memory_events_1=require("./pod-memory-events"),heap_snapshot_1=require("./heap-snapshot"),httpProxy=require("http-proxy"),{prettyFactory}=require("pino-pretty"),BUNDLE_PATH=process.env.BUNDLE_PATH?.trim()||"./main.js",SERVICE_NAME=process.env.SERVICE_NAME||"",SERVICE_PREFIX=process.env.SERVE_PREFIX?`/${process.env.SERVE_PREFIX}`:"",GATEWAY_MIDDLEWARE_PATH=process.env.GATEWAY_MIDDLEWARE||"",GATEWAY_CONFIG=(()=>{const d=process.env.GATEWAY_CONFIG;if(!d)return{};try{return JSON.parse(d)}catch{return{}}})();let gatewayMiddleware=null;if(GATEWAY_MIDDLEWARE_PATH)try{const d=require(GATEWAY_MIDDLEWARE_PATH);gatewayMiddleware=typeof d=="function"?d:typeof d.default=="function"?d.default:null,gatewayMiddleware||console.warn(`[gateway] ${GATEWAY_MIDDLEWARE_PATH} does not export a function, gateway disabled`)}catch(d){console.error(`[gateway] Failed to load middleware from ${GATEWAY_MIDDLEWARE_PATH}:`,d)}function applyGatewayMiddleware(d){if(gatewayMiddleware)try{gatewayMiddleware(d,GATEWAY_CONFIG)}catch(_){console.error("[gateway] Middleware error:",_)}}u(applyGatewayMiddleware,"applyGatewayMiddleware"),a(applyGatewayMiddleware,"applyGatewayMiddleware");const GATEWAY_ROUTES=(()=>{try{return JSON.parse(process.env.GATEWAY_ROUTES||"[]")}catch{return[]}})(),GATEWAY_HTTPS=process.env.GATEWAY_HTTPS==="1";function hostMatches(d,_){if(d.startsWith("*.")){const f=d.slice(1);return _.endsWith(f)||_===d.slice(2)}return _===d}u(hostMatches,"hostMatches"),a(hostMatches,"hostMatches");function matchGatewayRoute(d){if(GATEWAY_ROUTES.length===0)return;const _=(d.headers.host||"").split(":")[0],f=d.url||"/";for(const m of GATEWAY_ROUTES)if(!(m.host&&!hostMatches(m.host,_))&&!(m.prefix&&!f.startsWith(m.prefix)))return m}u(matchGatewayRoute,"matchGatewayRoute"),a(matchGatewayRoute,"matchGatewayRoute");const{specs:WORKER_SPECS,problems:WORKER_PROBLEMS}=(0,worker_supervisor_1.parseWorkerSpecs)(process.env.WORKERS),WORKER_NAMES=WORKER_SPECS.map(d=>d.name),LENSMCP_WS_KEY=process.env.LENSMCP_WS_KEY||"",SOCK_NS=process.env.LENSMCP_SOCK_NS||LENSMCP_WS_KEY,SOCK_DIR=SOCK_NS?path.join(os.tmpdir(),SOCK_NS,`${SERVICE_NAME||"lensmcp-cluster"}-devserver`):path.join(os.tmpdir(),`${SERVICE_NAME||"lensmcp-cluster"}-devserver`),SOCKET_ONLY=process.env.LENSMCP_SOCKET_ONLY==="1",POD_GENERATION=(()=>{const d=Number(process.env.LENSMCP_POD_GENERATION);return Number.isFinite(d)&&d>1?Math.floor(d):1})();function childSockPath(d){return path.join(SOCK_DIR,(0,pod_sock_1.podSockName)(d,POD_GENERATION))}u(childSockPath,"childSockPath"),a(childSockPath,"childSockPath");function sockOwnerPath(d){return`${d}.owner`}u(sockOwnerPath,"sockOwnerPath"),a(sockOwnerPath,"sockOwnerPath");function sockRetiringPath(d){return`${d}.retiring`}u(sockRetiringPath,"sockRetiringPath"),a(sockRetiringPath,"sockRetiringPath");function tell(d,_){if(!d.connected||typeof d.send!="function")return!1;try{return d.send(_,()=>{})}catch{return!1}}u(tell,"tell"),a(tell,"tell");function refusePoolCommand(d,_){console.warn(`[devserver] refused ${d.method} ${d.url} on the public port \u2014 under a gateway the pool is driven on the control socket only.`),_.writeHead(404,{"content-type":"application/json"}),_.end(JSON.stringify({error:"not found"}))}u(refusePoolCommand,"refusePoolCommand"),a(refusePoolCommand,"refusePoolCommand"),exports.DEBUG_FIXED_PORTS_ENV="LENSMCP_DEBUG_FIXED_PORTS";function usesFixedInspectorPorts(d=process.env){const _=(d[exports.DEBUG_FIXED_PORTS_ENV]??"").trim().toLowerCase();return _==="1"||_==="true"||_==="yes"||_==="on"}u(usesFixedInspectorPorts,"usesFixedInspectorPorts"),a(usesFixedInspectorPorts,"usesFixedInspectorPorts");function inspectorPortFor(d,_,f=process.env){if(!usesFixedInspectorPorts(f))return 0;const m=Math.trunc(d)+Math.trunc(_);return Number.isInteger(m)&&m>1024&&m<=65535?m:0}u(inspectorPortFor,"inspectorPortFor"),a(inspectorPortFor,"inspectorPortFor");function ensureOwnerOnlyDir(d){try{fs.mkdirSync(d,{recursive:!0,mode:448})}catch{}try{const _=fs.lstatSync(d);_.isDirectory()&&(_.mode&63)!==0&&fs.chmodSync(d,448)}catch{}}u(ensureOwnerOnlyDir,"ensureOwnerOnlyDir"),a(ensureOwnerOnlyDir,"ensureOwnerOnlyDir");function claimSock(d,_=process.pid){ensureOwnerOnlyDir(path.dirname(d));try{const f=sockOwnerPath(d);try{fs.unlinkSync(f)}catch{}fs.writeFileSync(f,String(_),{flag:"wx",mode:384})}catch{}try{fs.unlinkSync(d)}catch{}try{fs.unlinkSync(sockRetiringPath(d))}catch{}}u(claimSock,"claimSock"),a(claimSock,"claimSock");function sockOwnedByAnother(d,_=process.pid){try{const f=fs.readFileSync(sockOwnerPath(d),"utf8").trim();return!!f&&f!==String(_)}catch{return!1}}u(sockOwnedByAnother,"sockOwnedByAnother"),a(sockOwnedByAnother,"sockOwnedByAnother");function cleanupSock(d,_=process.pid){if(d){try{const f=fs.readFileSync(sockOwnerPath(d),"utf8").trim();if(f&&f!==String(_))return}catch{}try{fs.unlinkSync(d)}catch{}try{fs.unlinkSync(sockOwnerPath(d))}catch{}try{fs.unlinkSync(sockRetiringPath(d))}catch{}(0,gc_notice_1.clearGcNotice)(d)}}u(cleanupSock,"cleanupSock"),a(cleanupSock,"cleanupSock");function postRetiringNotice(d,_){if(!(!d||!_)){try{const f=fs.readFileSync(sockOwnerPath(d),"utf8").trim();if(f&&f!==String(_))return}catch{}try{fs.writeFileSync(sockRetiringPath(d),String(_),{flag:"w",mode:384})}catch{}}}u(postRetiringNotice,"postRetiringNotice"),a(postRetiringNotice,"postRetiringNotice");function serviceKeyFingerprint(){const d=process.env.LENSMCP_SERVICE_KEY;if(!d)return;const{createHash:_}=require("node:crypto");return _("sha256").update(d).digest("hex").slice(0,8)}u(serviceKeyFingerprint,"serviceKeyFingerprint"),a(serviceKeyFingerprint,"serviceKeyFingerprint");function rootModuleOf(d){let _;for(const f of d.getModules?.()?.values()??[])typeof f?.metatype!="function"||typeof f.distance!="number"||!Number.isFinite(f.distance)||(!_||f.distance<_.distance)&&(_=f);return _?.metatype}u(rootModuleOf,"rootModuleOf"),a(rootModuleOf,"rootModuleOf");let lastImportedModule;function takeImportedModule(){const d=lastImportedModule;return lastImportedModule=void 0,d}u(takeImportedModule,"takeImportedModule"),a(takeImportedModule,"takeImportedModule");async function importFresh(spec){process.env.DEVSERVER_MODE="1";const requested=path.isAbsolute(spec)?spec:path.join(__dirname,spec);let resolved=requested;try{resolved=fs.realpathSync(requested)}catch{}eval(`(() => {
1
+ "use strict";var St=Object.defineProperty;var u=(d,_)=>St(d,"name",{value:_,configurable:!0});var Et=Object.defineProperty,a=u((d,_)=>Et(d,"name",{value:_,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0}),exports.redactInspectorUrls=exports.inspectorPortOf=exports.DEBUG_FIXED_PORTS_ENV=exports.mayDriveThePool=exports.isOwnerOnlyTransport=exports.gatewayManaged=void 0,exports.tell=tell,exports.usesFixedInspectorPorts=usesFixedInspectorPorts,exports.inspectorPortFor=inspectorPortFor;const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),node_child_process_1=require("node:child_process"),http=tslib_1.__importStar(require("node:http")),readline=tslib_1.__importStar(require("node:readline")),inspector=tslib_1.__importStar(require("node:inspector")),util=tslib_1.__importStar(require("node:util")),v8=tslib_1.__importStar(require("node:v8")),child_process_env_1=require("./child-process-env"),exit_reason_1=require("./exit-reason"),worker_supervisor_1=require("./worker-supervisor"),hot_swap_registries_1=require("./hot-swap-registries"),process_name_1=require("./process-name"),inspector_secret_1=require("./inspector-secret");Object.defineProperty(exports,"inspectorPortOf",{enumerable:!0,get:a(function(){return inspector_secret_1.inspectorPortOf},"get")}),Object.defineProperty(exports,"redactInspectorUrls",{enumerable:!0,get:a(function(){return inspector_secret_1.redactInspectorUrls},"get")});const devserver_transport_1=require("./devserver-transport");Object.defineProperty(exports,"gatewayManaged",{enumerable:!0,get:a(function(){return devserver_transport_1.gatewayManaged},"get")}),Object.defineProperty(exports,"isOwnerOnlyTransport",{enumerable:!0,get:a(function(){return devserver_transport_1.isOwnerOnlyTransport},"get")}),Object.defineProperty(exports,"mayDriveThePool",{enumerable:!0,get:a(function(){return devserver_transport_1.mayDriveThePool},"get")});const schema_first_instance_1=require("./schema-first-instance"),redis_disconnect_fix_1=require("./redis-disconnect-fix"),error_stack_release_1=require("./error-stack-release"),swap_recycle_1=require("./swap-recycle"),swap_mode_1=require("./swap-mode"),handoff_retire_1=require("./handoff-retire"),gc_notice_1=require("./gc-notice"),pod_sock_1=require("./pod-sock"),notice_generation_1=require("./notice-generation"),service_build_events_1=require("./service-build-events"),stdio_guard_1=require("./stdio-guard"),bundle_parent_1=require("./bundle-parent"),checkout_cache_1=require("./checkout-cache"),dev_devtool_1=require("./dev-devtool"),worker_retire_1=require("./worker-retire"),devserver_host_1=require("./devserver-host"),pod_memory_1=require("./pod-memory"),pod_memory_events_1=require("./pod-memory-events"),heap_snapshot_1=require("./heap-snapshot"),httpProxy=require("http-proxy"),{prettyFactory}=require("pino-pretty"),BUNDLE_PATH=process.env.BUNDLE_PATH?.trim()||"./main.js",SERVICE_NAME=process.env.SERVICE_NAME||"",SERVICE_PREFIX=process.env.SERVE_PREFIX?`/${process.env.SERVE_PREFIX}`:"",GATEWAY_MIDDLEWARE_PATH=process.env.GATEWAY_MIDDLEWARE||"",GATEWAY_CONFIG=(()=>{const d=process.env.GATEWAY_CONFIG;if(!d)return{};try{return JSON.parse(d)}catch{return{}}})();let gatewayMiddleware=null;if(GATEWAY_MIDDLEWARE_PATH)try{const d=require(GATEWAY_MIDDLEWARE_PATH);gatewayMiddleware=typeof d=="function"?d:typeof d.default=="function"?d.default:null,gatewayMiddleware||console.warn(`[gateway] ${GATEWAY_MIDDLEWARE_PATH} does not export a function, gateway disabled`)}catch(d){console.error(`[gateway] Failed to load middleware from ${GATEWAY_MIDDLEWARE_PATH}:`,d)}function applyGatewayMiddleware(d){if(gatewayMiddleware)try{gatewayMiddleware(d,GATEWAY_CONFIG)}catch(_){console.error("[gateway] Middleware error:",_)}}u(applyGatewayMiddleware,"applyGatewayMiddleware"),a(applyGatewayMiddleware,"applyGatewayMiddleware");const GATEWAY_ROUTES=(()=>{try{return JSON.parse(process.env.GATEWAY_ROUTES||"[]")}catch{return[]}})(),GATEWAY_HTTPS=process.env.GATEWAY_HTTPS==="1";function hostMatches(d,_){if(d.startsWith("*.")){const f=d.slice(1);return _.endsWith(f)||_===d.slice(2)}return _===d}u(hostMatches,"hostMatches"),a(hostMatches,"hostMatches");function matchGatewayRoute(d){if(GATEWAY_ROUTES.length===0)return;const _=(d.headers.host||"").split(":")[0],f=d.url||"/";for(const y of GATEWAY_ROUTES)if(!(y.host&&!hostMatches(y.host,_))&&!(y.prefix&&!f.startsWith(y.prefix)))return y}u(matchGatewayRoute,"matchGatewayRoute"),a(matchGatewayRoute,"matchGatewayRoute");const{specs:WORKER_SPECS,problems:WORKER_PROBLEMS}=(0,worker_supervisor_1.parseWorkerSpecs)(process.env.WORKERS),WORKER_NAMES=WORKER_SPECS.map(d=>d.name),LENSMCP_WS_KEY=process.env.LENSMCP_WS_KEY||"",SOCK_NS=process.env.LENSMCP_SOCK_NS||LENSMCP_WS_KEY,SOCK_DIR=SOCK_NS?path.join(os.tmpdir(),SOCK_NS,`${SERVICE_NAME||"lensmcp-cluster"}-devserver`):path.join(os.tmpdir(),`${SERVICE_NAME||"lensmcp-cluster"}-devserver`),SOCKET_ONLY=process.env.LENSMCP_SOCKET_ONLY==="1",POD_GENERATION=(()=>{const d=Number(process.env.LENSMCP_POD_GENERATION);return Number.isFinite(d)&&d>1?Math.floor(d):1})();function childSockPath(d){return path.join(SOCK_DIR,(0,pod_sock_1.podSockName)(d,POD_GENERATION))}u(childSockPath,"childSockPath"),a(childSockPath,"childSockPath");function sockOwnerPath(d){return`${d}.owner`}u(sockOwnerPath,"sockOwnerPath"),a(sockOwnerPath,"sockOwnerPath");function sockRetiringPath(d){return`${d}.retiring`}u(sockRetiringPath,"sockRetiringPath"),a(sockRetiringPath,"sockRetiringPath");function tell(d,_){if(!d.connected||typeof d.send!="function")return!1;try{return d.send(_,()=>{})}catch{return!1}}u(tell,"tell"),a(tell,"tell");function refusePoolCommand(d,_){console.warn(`[devserver] refused ${d.method} ${d.url} on the public port \u2014 under a gateway the pool is driven on the control socket only.`),_.writeHead(404,{"content-type":"application/json"}),_.end(JSON.stringify({error:"not found"}))}u(refusePoolCommand,"refusePoolCommand"),a(refusePoolCommand,"refusePoolCommand"),exports.DEBUG_FIXED_PORTS_ENV="LENSMCP_DEBUG_FIXED_PORTS";function usesFixedInspectorPorts(d=process.env){const _=(d[exports.DEBUG_FIXED_PORTS_ENV]??"").trim().toLowerCase();return _==="1"||_==="true"||_==="yes"||_==="on"}u(usesFixedInspectorPorts,"usesFixedInspectorPorts"),a(usesFixedInspectorPorts,"usesFixedInspectorPorts");function inspectorPortFor(d,_,f=process.env){if(!usesFixedInspectorPorts(f))return 0;const y=Math.trunc(d)+Math.trunc(_);return Number.isInteger(y)&&y>1024&&y<=65535?y:0}u(inspectorPortFor,"inspectorPortFor"),a(inspectorPortFor,"inspectorPortFor");function ensureOwnerOnlyDir(d){try{fs.mkdirSync(d,{recursive:!0,mode:448})}catch{}try{const _=fs.lstatSync(d);_.isDirectory()&&(_.mode&63)!==0&&fs.chmodSync(d,448)}catch{}}u(ensureOwnerOnlyDir,"ensureOwnerOnlyDir"),a(ensureOwnerOnlyDir,"ensureOwnerOnlyDir");function claimSock(d,_=process.pid){ensureOwnerOnlyDir(path.dirname(d));try{const f=sockOwnerPath(d);try{fs.unlinkSync(f)}catch{}fs.writeFileSync(f,String(_),{flag:"wx",mode:384})}catch{}try{fs.unlinkSync(d)}catch{}try{fs.unlinkSync(sockRetiringPath(d))}catch{}}u(claimSock,"claimSock"),a(claimSock,"claimSock");function sockOwnedByAnother(d,_=process.pid){try{const f=fs.readFileSync(sockOwnerPath(d),"utf8").trim();return!!f&&f!==String(_)}catch{return!1}}u(sockOwnedByAnother,"sockOwnedByAnother"),a(sockOwnedByAnother,"sockOwnedByAnother");function cleanupSock(d,_=process.pid){if(d){try{const f=fs.readFileSync(sockOwnerPath(d),"utf8").trim();if(f&&f!==String(_))return}catch{}try{fs.unlinkSync(d)}catch{}try{fs.unlinkSync(sockOwnerPath(d))}catch{}try{fs.unlinkSync(sockRetiringPath(d))}catch{}(0,gc_notice_1.clearGcNotice)(d)}}u(cleanupSock,"cleanupSock"),a(cleanupSock,"cleanupSock");function postRetiringNotice(d,_){if(!(!d||!_)){try{const f=fs.readFileSync(sockOwnerPath(d),"utf8").trim();if(f&&f!==String(_))return}catch{}try{fs.writeFileSync(sockRetiringPath(d),String(_),{flag:"w",mode:384})}catch{}}}u(postRetiringNotice,"postRetiringNotice"),a(postRetiringNotice,"postRetiringNotice");function serviceKeyFingerprint(){const d=process.env.LENSMCP_SERVICE_KEY;if(!d)return;const{createHash:_}=require("node:crypto");return _("sha256").update(d).digest("hex").slice(0,8)}u(serviceKeyFingerprint,"serviceKeyFingerprint"),a(serviceKeyFingerprint,"serviceKeyFingerprint");function rootModuleOf(d){let _;for(const f of d.getModules?.()?.values()??[])typeof f?.metatype!="function"||typeof f.distance!="number"||!Number.isFinite(f.distance)||(!_||f.distance<_.distance)&&(_=f);return _?.metatype}u(rootModuleOf,"rootModuleOf"),a(rootModuleOf,"rootModuleOf");let lastImportedModule;function takeImportedModule(){const d=lastImportedModule;return lastImportedModule=void 0,d}u(takeImportedModule,"takeImportedModule"),a(takeImportedModule,"takeImportedModule");async function importFresh(spec){process.env.DEVSERVER_MODE="1";const requested=path.isAbsolute(spec)?spec:path.join(__dirname,spec);let resolved=requested;try{resolved=fs.realpathSync(requested)}catch{}eval(`(() => {
2
2
  const key = ${JSON.stringify(resolved)};
3
3
  const previous = require.cache[key];
4
4
  delete require.cache[key]; // delete from CJS cache
@@ -9,16 +9,16 @@
9
9
  const at = owner && Array.isArray(owner.children) ? owner.children.indexOf(previous) : -1;
10
10
  if (at >= 0) owner.children.splice(at, 1);
11
11
  }
12
- })()`),(0,bundle_parent_1.routeBundleRequires)(requested,resolved);const exports=eval(`require(${JSON.stringify(resolved)})`);try{const mod=eval("require.cache")[resolved];lastImportedModule=mod&&typeof mod=="object"?mod:void 0}catch{}return exports}u(importFresh,"importFresh"),a(importFresh,"importFresh");function debounce(d,_){let f=null;return(...m)=>{f&&clearTimeout(f),f=setTimeout(()=>d(...m),_)}}if(u(debounce,"debounce"),a(debounce,"debounce"),process.env.APP_RUNNER==="1"){(0,stdio_guard_1.guardBrokenStdio)();const d=a(f=>{if(!inspector.url())try{inspector.open(f,"127.0.0.1",!1)}catch(W){console.warn(`[child] inspector.open(${f}) failed (port taken by another devserver?) \u2014 falling back to a random port:`,W.message);try{inspector.open(0,"127.0.0.1",!1)}catch{}}const m=inspector.url();m&&tell(process,{type:"inspector-url",url:m})},"openInspector"),_=process.env.CHILD_DEBUG_PORT;if(_!==void 0&&_!==""){const f=Number(_);Number.isInteger(f)&&(f===0||f>1024)&&d(f)}try{require("@lensmcp/node-instrumentation/register")}catch{}(async()=>{let f=null,m=!1,W,re=!1;const Ve=(0,hot_swap_registries_1.registryPruningEnabled)(),ge=a((r,c)=>{const l=(0,hot_swap_registries_1.describePrune)(r,c);l&&console.log(l)},"logPrune");let j={app:null,handler:a((r,c)=>{c.statusCode=503,c.end("starting")},"handler"),inflight:0};const we=(()=>{const r=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(r)&&r>=0?r:15*6e4})(),I=a(r=>{const c=globalThis.__lensmcpActiveWork;if(typeof c!="function")return{count:0};try{const l=c(r);return{count:Number(l?.count??0),...l?.oldestStartedAt?{oldestStartedAt:l.oldestStartedAt}:{}}}catch{return{count:0}}},"activeWork"),$e=a(r=>{const c=globalThis.__lensmcpStopWorkIntake;if(typeof c=="function")try{return c(r)}catch{return}},"stopWorkIntake"),me=a(r=>{const c=globalThis.__lensmcpWorkIntakeReport;if(!(r===void 0||typeof c!="function"))try{return c(r)??void 0}catch{return}},"workIntakeReport"),be=(()=>{const r=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(r)&&r>=1?Math.floor(r):1})(),F=new Set,Z=(()=>{const r=Number(process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS);return process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS!==void 0&&process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS!==""&&Number.isFinite(r)&&r>=0?r:3e4})(),V=a(r=>{if(!r.abandoned?.size)return 0;const c=Date.now();for(const[l,h]of r.abandoned)(l.writableEnded||c-h>=Z)&&r.abandoned.delete(l);return r.abandoned.size},"abandonedRunning"),oe=a(r=>{let c=0;for(const l of r.open??[])l.headersSent||(c+=1);return{unanswered:c+V(r),streams:Math.max(0,r.inflight-c),work:I(r.workGen).count}},"owedBy"),ne=a((r,c,l=`${c}s`)=>`${r} ${r===1?c:l}`,"plural");async function We(){if(Z<=0)return;const r=Date.now();let c=!1;for(;!(F.size<be);){const l=F.values().next().value;if(!l||l.closed)break;const h=oe(l);if(h.unanswered===0&&h.work===0)break;const E=(l.drainingSince??r)+Z-Date.now();if(E<=0)break;c||(c=!0,console.log(`[child] swap held \u2014 the app replaced ${Math.round((Date.now()-(l.drainingSince??r))/100)/10}s ago is still `+[h.unanswered?`answering ${ne(h.unanswered,"request")}`:"",h.work?`running ${ne(h.work,"background job")}`:""].filter(Boolean).join(" and ")+`, and this pod keeps at most ${be} replaced app(s) alive (LENSMCP_SWAP_MAX_DRAINING). The new build is applied when it is done \u2014 in ${Math.ceil(E/1e3)}s at the latest (LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS).`)),await new Promise(v=>{setTimeout(v,Math.min(100,E)).unref?.()})}c&&console.log(`[child] swap resumed after ${Date.now()-r}ms`)}u(We,"He"),a(We,"holdForOwedWork");const M=(0,swap_recycle_1.swapRecyclePolicy)();let ye,se=0;const Je=(()=>{const r=Number(process.env.LENSMCP_POD_RETIRE_NOTICE_MS);return Number.isFinite(r)&&r>=0?r:3500})();let g=!1,b=!1;const S=(0,pod_memory_1.podMemoryPolicy)();let K=0;const x=new Set;let Ee=!1;const B=a(()=>{if(!Ee)return;let r=0;for(const c of x)c.deref()===void 0?x.delete(c):r+=1;return r},"liveContainers"),k=(0,pod_memory_1.createPodMemoryMonitor)({policy:S,state:a(()=>({gen:j.gen??0,swaps:se,...ye===void 0?{}:{baseline:ye},busy:m||re||J.size>0,lastBusyAt:D}),"state"),send:a(r=>{tell(process,r)},"send"),containers:B,counter:(0,pod_memory_1.createLiveObjectCounter)(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH)),onRetained:a(()=>Te(),"onRetained"),gc:a((r,c)=>(0,gc_notice_1.withGcNotice)(N,pod_memory_1.fullGc,Date.now,r,c),"gc")}),H=a(()=>((0,gc_notice_1.withGcNotice)(N,pod_memory_1.fullGc,Date.now,"live-heap")&&k.tracker.noteGc(),process.memoryUsage().heapUsed),"liveHeap"),q=(()=>{if(!(0,error_stack_release_1.errorFrameReleaseEnabled)())return null;try{const r=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH))+path.sep,c=`${path.sep}node_modules${path.sep}`,l=new Set(Object.keys(require.cache));return(0,error_stack_release_1.createErrorFrameReleaser)(require.cache,{skip:a(h=>l.has(h)||h.startsWith(r)&&!h.slice(r.length).includes(c)&&!h.slice(r.length).startsWith(`node_modules${path.sep}`),"skip")})}catch{return null}})();let ie=!1;function Oe(){if(!(!q||ie))try{const r=q();r.errors>0&&console.log(`[child] read the stack of ${r.errors} Error object(s) that libraries created while loading and keep for good \u2014 unread, each held the functions that were on its stack, this bundle's included`)}catch(r){console.error("[child] could not release library error frames:",r),ie=!0}}u(Oe,"De"),a(Oe,"releaseLibraryErrorFrames");const J=new Map;let D=Date.now();const Fe=a(()=>M.settleMs<=0||!m&&!re&&J.size===0&&Date.now()-D>=M.settleMs,"settled");let Y;function ae(r){if(!(!M.enabled||g||b)){if(M.settleMs<=0){X(r);return}Y&&clearTimeout(Y),Y=setTimeout(()=>{Y=void 0,Fe()?X(r):ae(r)},M.settleMs),Y.unref?.()}}u(ae,"_e"),a(ae,"recycleCheckWhenSettled");const ce=a(()=>{if(M.stuckCloseMs<=0)return 0;const r=Date.now();let c=0;for(const l of J.values())r-l>=M.stuckCloseMs&&(c+=1);return c},"stuckCloses");function X(r){if(!M.enabled||g||b||!process.send)return;const c=v8.getHeapStatistics().heap_size_limit,l=a(E=>{const v=k.oldestRetained();return{swaps:se,usedBytes:E,limitBytes:c,stuckCloses:ce(),settled:Fe(),...ye===void 0?{}:{baselineBytes:ye},...v?{retained:{generation:v.gen,ageMs:Date.now()-v.closedAt,gcs:v.gcs}}:{}}},"state");if(!(0,swap_recycle_1.recycleReason)(M,l(process.memoryUsage().heapUsed)))return;const h=(0,swap_recycle_1.recycleReason)(M,l(H()));h&&(g=!0,console.log(`[child] asking for a fresh pod ${r} \u2014 ${h}. This pod keeps serving until its successor is ready. Size the bound with LENSMCP_SWAP_RECYCLE_HEAP_FACTOR / _HEAP_RATIO / _MIN_MB / _RETAINED_MS, or turn it off with LENSMCP_SWAP_RECYCLE=0.`),tell(process,{type:"recycle-request",reason:h}))}u(X,"Q"),a(X,"considerRecycle");let le;function Te(){if(!M.enabled||M.retainedMs<=0||g||b)return;const r=k.oldestRetained();if(!r)return;const c=r.closedAt+M.retainedMs-Date.now();if(c<=0){X("with a closed generation still in memory");return}le||(le=setTimeout(()=>{le=void 0,k.measure("retention-check").catch(()=>{})},c),le.unref?.())}u(Te,"je"),a(Te,"retainedRecycleCheck");function ve(r,c){const l={};c&&(l.module=c),r&&(l.app=r);try{const h=r?.app;if(h&&typeof h=="object"&&(l.nestApp=h,h.container&&typeof h.container=="object")){l.container=h.container;const E=rootModuleOf(h.container);E&&(l.rootModule=E)}}catch{}return l}u(ve,"Ne"),a(ve,"generationTargets");async function de(r,c){if(r.closed||(r.closed=!0,F.delete(r),c&&console.error(`[child] ${c}`),!r.app))return;J.set(r,Date.now());const l=M.enabled&&M.stuckCloseMs>0?setTimeout(()=>{J.has(r)&&(console.error(`[child] a previous app has been closing for ${Math.round(M.stuckCloseMs/1e3)}s and its close() has not returned \u2014 one of its shutdown hooks is waiting on something that does not end (a queue worker, a connection, a stream). It stays in memory until this pod is replaced.`),X("with a previous app stuck in close()"))},M.stuckCloseMs):void 0;l?.unref?.();const h=r.app;try{await r.app.close()}catch(E){console.error("[child] error closing a previous app:",E)}finally{J.delete(r),D=Date.now(),l&&clearTimeout(l),r.app=null,r.abandoned=void 0,r.handler=(E,v)=>{v.statusCode=503,v.end("closed")},r.gen!==void 0&&k.closed(r.gen,se,ve(h,r.module)),r.module=void 0}if(r.superseded){try{ge((0,hot_swap_registries_1.pruneRegistries)(r.superseded,"serve"),"after closing the previous app")}catch(E){console.error("[child] could not release the previous app's class registrations:",E)}r.superseded=void 0}ae("after closing the previous app")}u(de,"me"),a(de,"closeGeneration");async function pe(r){const c=Date.now();r.drainingSince=c;const l=a(()=>({inflight:r.inflight+V(r),work:I(r.workGen).count}),"busy"),h=l();if(h.inflight>0||h.work>0){for(;F.size>=be;){const $=F.values().next().value;if(!$)break;const O=oe($),z=Math.round((Date.now()-($.drainingSince??c))/1e3);if(O.unanswered===0&&O.streams===0&&O.work===0){await de($);continue}await de($,`closing a still-draining generation early \u2014 ${F.size} were pending and the cap is ${be} (each holds a whole app: DI container, DB pool, queue workers). `+(O.unanswered>0||O.work>0?`It was replaced ${z}s ago and had still not answered ${ne(O.unanswered,"request")}`+(O.work?` or finished ${ne(O.work,"background job")}`:"")+` \u2014 those fail now (a queue job keeps its lock until the TTL lapses). Raise LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS (currently ${Z}ms) to wait longer for them. `:`It held only ${ne(O.streams,"open stream")}; their clients reconnect to the new app. `)+"Raise LENSMCP_SWAP_MAX_DRAINING if this pod legitimately needs more.")}F.add(r)}for(;we>0&&Date.now()-c<we;){if(r.closed)return;const $=l();if($.inflight===0&&$.work===0)break;await new Promise(O=>{setTimeout(O,250).unref?.()})}if(r.closed)return;const E=l(),v=me(r.workGen);E.inflight>0||E.work>0?console.error(`[child] swap drain expired after ${Date.now()-c}ms \u2014 closing the previous app with ${E.inflight} in-flight request(s) and ${E.work} background job(s) still running. `+(v?`Previous app still processing ${v.running} queue job(s); ${v.takenAfterStop} were taken after the swap. `:"")+`A queue job killed here keeps its lock until the TTL lapses. Raise LENSMCP_SWAP_DRAIN_MS (currently ${we}ms) if this is legitimate work.`):(Date.now()-c>250||v?.runningAtStop||v?.takenAfterStop)&&console.log(`[child] previous app drained in ${Date.now()-c}ms \u2014 closing it`+(v?` (it finished ${v.finishedAfterStop} queue job(s) after the swap; ${v.takenAfterStop} were taken after the swap)`:"")),await de(r)}u(pe,"ye"),a(pe,"drainThenClose");async function ue(){if(m)return re=!0,console.log("[child] Reload deferred \u2014 will re-swap after current swap completes"),f;m=!0,D=Date.now(),await We(),process.removeAllListeners("uncaughtException"),process.removeAllListeners("unhandledRejection"),process.on("uncaughtException",(P,ee)=>{console.error(`[child] uncaughtException (${ee}):`,P)}),process.on("unhandledRejection",P=>{const ee=P instanceof Error?P.stack||P.message:String(P);ee.includes("FronteggContextScope")||ee.includes("populateLoggerMetadata")||console.error("[child] unhandledRejection:",P)});let r;if(Ve)try{r=(0,hot_swap_registries_1.captureRegistries)()}catch{r=void 0}const c=global.__lensmcpBeginWorkGeneration,l=typeof c=="function"?c():void 0;try{try{await importFresh(BUNDLE_PATH)}catch(P){if(!(P instanceof SyntaxError))throw P;console.warn(`[child] bundle was unreadable mid-write (${P.message}) \u2014 retrying the swap once`),await new Promise(ee=>setTimeout(ee,400)),await importFresh(BUNDLE_PATH)}}catch(P){throw m=!1,D=Date.now(),P}if(typeof global.createChildApp!="function")throw m=!1,D=Date.now(),new Error(`Bundle '${BUNDLE_PATH}' does not export createChildApp() and the zero-touch bridge is not active. Either install @lensmcp/node-instrumentation (a plain NestFactory.create + app.listen main.ts then just works) or set global.createChildApp in main.ts when DEVSERVER_MODE === '1'.`);let h;if(r)try{h=(0,hot_swap_registries_1.supersededSince)(r),ge((0,hot_swap_registries_1.pruneRegistries)(h,"build"),"at the swap")}catch(P){console.error("[child] could not release superseded class registrations:",P)}let E;try{E=await global.createChildApp()}catch(P){throw m=!1,D=Date.now(),takeImportedModule(),P}const v=j;h?.size&&(v.app?v.superseded=h:ge((0,hot_swap_registries_1.pruneRegistries)(h,"serve"),"at the swap")),f=E;const $=takeImportedModule();j={app:E,handler:E.handler,inflight:0,gen:++K,...$?{module:$}:{},...l===void 0?{}:{workGen:l}};const O=ve(E,void 0).container;O&&(x.add(new WeakRef(O)),Ee=!0);const z=v.app&&l!==void 0?$e(l):void 0;return console.log("[child] Swapped to fresh app (previous draining in background)"+(z?.workers?`; its ${z.workers} queue worker(s) stopped taking new jobs, previous app still processing ${z.runningAtStop} job(s)`:"")),Oe(),v.app&&(se+=1,pe(v).catch(P=>console.error("[child] background close error:",P)),setTimeout(()=>X("30s after a hot swap"),3e4).unref?.(),k.swapped(v.gen,()=>v.closed===!0&&!J.has(v))),m=!1,D=Date.now(),re?(re=!1,ue()):E}u(ue,"Ee"),a(ue,"swapNow");const Pe=debounce(async()=>{try{console.log("[child] /webpack/reload"),await ue()}catch(r){console.error("[child] reload failed:",r)}},250),he=http.createServer((r,c)=>{if(r.method==="POST"&&r.url==="/webpack/reload"){c.writeHead(200,{"content-type":"application/json"}),c.end(JSON.stringify({ok:!0})),Pe();return}if(r.method==="GET"&&r.url==="/__lensmcp/alive"){const E=r.headers["x-internal-token"],v=process.env.LENSMCP_SERVICE_KEY;if(v&&E!==v){c.writeHead(404,{"content-type":"text/plain"}),c.end("not found");return}const $=I();c.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),c.end(JSON.stringify({ok:!0,pid:process.pid,swapping:m,inflight:j.inflight,oldestInflightAt:j.oldestAt,activeWork:$.count,oldestWorkAt:$.oldestStartedAt,keyFingerprint:serviceKeyFingerprint(),...W?{watcher:W}:{},...Number.isFinite(Number(process.env.LENSMCP_POD_GENERATION))&&process.env.LENSMCP_POD_GENERATION?{podGeneration:Number(process.env.LENSMCP_POD_GENERATION)}:{}}));return}const l=j;l.inflight+=1,(l.open??=new Set).add(c),l.oldestAt===void 0&&(l.oldestAt=Date.now());const h=k.request();c.on("close",()=>{l.inflight-=1,l.open?.delete(c),Z>0&&!l.closed&&!c.headersSent&&!c.writableEnded&&((l.abandoned??=new Map).set(c,Date.now()),l.abandoned.size>256&&V(l)),l.inflight===0&&(l.oldestAt=void 0),h()}),l.handler(r,c)});he.keepAliveTimeout=0;const N=process.env.CHILD_SOCK_PATH;process.on("disconnect",()=>{cleanupSock(N),process.exit(0)});try{const r=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH);if((0,schema_first_instance_1.schemaPrewarmEnabled)())try{const l=(0,schema_first_instance_1.prewarmZodFor)(r);l?.created&&console.log(`[child] zod${l.version?` ${l.version}`:""}: built ${l.created} throwaway schemas first, so none of the bundle's own is the first of its class`)}catch{}if((0,redis_disconnect_fix_1.redisDisconnectFixEnabled)())try{const l=(0,redis_disconnect_fix_1.finishStrandedDisconnectsFor)(r);l?.patched&&console.log(`[child] ioredis${l.versions.length?` ${l.versions.join(", ")}`:""}: a disconnect() between reconnect attempts now ends the client \u2014 it used to leave a queue worker's close() waiting for good`)}catch{}await ue(),ye=(await k.booted()).live,console.log(`[child] Using bundle: ${r}`),claimSock(N);let c=!1;he.on("error",l=>{if(c){console.error("[child] server error:",l);return}console.error(`[child] could not listen on ${N} (${l.code??l.message}) \u2014 exiting; the devserver starts another pod`),tell(process,{type:"boot-error",error:`could not listen on ${N}: ${String(l?.stack||l)}`}),cleanupSock(N),process.exitCode=1,setTimeout(()=>process.exit(1),100)}),he.listen(N,()=>{c=!0,console.log(`[child] Listening on ${N}`),tell(process,{type:"ready",socketPath:N})})}catch(r){console.error("[child] Startup error:",r),tell(process,{type:"boot-error",error:String(r?.stack||r)}),process.exitCode=1;return}process.on("message",async r=>{if(!(!r||typeof r!="object")){if(r.type==="debug-open"){const c=Number(r.port);d(Number.isInteger(c)&&c>1024?c:0);return}if(r.type==="watcher"){const c=r.testimony;c&&typeof c=="object"&&(W=c);return}if(r.type==="heap-snapshot"){Me(r);return}if(r.type==="recycle-declined"){g=!1;return}if(r.type==="retire"){U();return}if(r.type==="reload"){if(b)return;try{const c=Date.now();await ue(),tell(process,{type:"reloaded",socketPath:N,swap:{generation:K,swaps:se,swapMs:Date.now()-c,draining:F.size}})}catch(c){console.error("[child] reload error:",c),tell(process,{type:"reload-error",error:String(c?.stack||c)})}}}});let Se=!1;async function Me(r){const c=a(l=>{tell(process,{type:"heap-snapshot-result",id:r.id,...l})},"reply");if(Se)return c({ok:!1,refused:"a snapshot of this pod is already being written"});Se=!0;try{const l=H(),h=k.tracker.views().map(O=>O.gen),E=(0,heap_snapshot_1.heapSnapshotPolicy)();r.maxHeapBytes&&(E.maxHeapBytes=r.maxHeapBytes);const v=(0,heap_snapshot_1.heapSnapshotRefusal)(E,{live:l,...r.available?{available:r.available}:{}});if(v)return c({ok:!1,refused:v,live:l});console.log(`[child] writing a heap snapshot (${Math.round(l/1048576)} MB live) \u2014 the pod pauses while V8 serialises it`);const $=await(0,heap_snapshot_1.writeHeapSnapshot)(r.file);c({ok:!0,file:r.file,bytes:$.bytes,ms:$.ms,live:l,gen:j.gen??0,closedAlive:h})}catch(l){c({ok:!1,error:l?.message??String(l)})}finally{Se=!1}}u(Me,"Ye"),a(Me,"takeHeapSnapshot");async function U(r="a fresh pod has taken over"){if(b)return;b=!0,k.stop(),console.log(`[child] retiring \u2014 ${r}; ${path.basename(N,".sock")} (pid ${process.pid}) is finishing in-flight work, then exiting`);const c=$e(Number.POSITIVE_INFINITY);c?.workers&&console.log(`[child] its ${c.workers} queue worker(s) stopped taking new jobs, still processing ${c.runningAtStop} job(s)`);try{fs.writeFileSync(sockRetiringPath(N),String(process.pid),{flag:"w",mode:384})}catch{}await new Promise(h=>{setTimeout(h,Je).unref?.()}),cleanupSock(N),he.close();const l=Date.now();for(;Date.now()-l<we;){he.closeIdleConnections?.();let h=0;for(const E of F)h+=oe(E).unanswered;if(j.inflight+V(j)===0&&h===0&&I().count===0)break;await new Promise(E=>{setTimeout(E,250).unref?.()})}setTimeout(()=>process.exit(0),3e4).unref?.();try{await f?.close()}catch(h){console.error("[child] close error while retiring:",h)}process.exit(0)}u(U,"B"),a(U,"retire"),process.on("beforeExit",()=>{try{inspector?.close?.()}catch{}});const fe=a(async r=>{console.log(`[child ${r}] shutting down\u2026`);const c=f?.close().catch(h=>console.error("[child] close error:",h)),l=new Promise(h=>he.close(()=>h()));cleanupSock(N),setTimeout(()=>process.exit(0),700).unref(),await Promise.all([c,l]),process.exit(0)},"shutdown");["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(r=>{process.on(r,()=>{if(r==="SIGTERM"&&!b&&(0,handoff_retire_1.handoffRetireRequested)(SOCK_DIR,POD_GENERATION)){U("this generation was handed over to a newer one");return}inspector?.close?.(),fe(r)})})})()}else{let d=u(function(g){V.push(g),V.length>Z&&V.splice(0,V.length-Z),be?.write((0,inspector_secret_1.redactInspectorUrls)(g.replace(F,"")));for(const b of oe)try{const S=b.plain?g.replace(F,""):g;b.res.write(b.redact?(0,inspector_secret_1.redactInspectorUrls)(S):S)}catch{oe.delete(b)}},"ge");a(d,"emitLogLine");const _=12,f=process.env.LENSMCP_PROJECT||SERVICE_NAME||"service",m=(0,pod_memory_events_1.createPodMemoryPublisher)(process.env.LENSMCP_EVENT_FILE),W=a(g=>({project:f,service:SERVICE_NAME||f,pod:g.id,pid:g.proc.pid??0,podGeneration:POD_GENERATION}),"podIdentity"),re=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[31m"],Ve="\x1B[0m",ge=Math.max(1,Number(process.env.CHILD_COUNT||1)),j=LENSMCP_WS_KEY||path.basename(process.cwd()),we=a(g=>(0,process_name_1.namedExecPath)((0,process_name_1.processName)(j,SERVICE_NAME||"service",g)),"execPathFor");let I=(()=>{const g=Number(process.env.LENSMCP_DEBUG_PORT||"");return Number.isInteger(g)&&g>1024?g:0})();const $e=20;I&&(console.warn("[parent] DEBUGGER ENABLED \u2014 pods and workers open a Node inspector. Node's inspector has NO authentication: the ws:// URL's UUID is the whole credential, and any account on this host that obtains it can run code as you. Do not enable this on a shared machine. (issues/closed/codex-security-06)"),console.warn(usesFixedInspectorPorts()?`[parent] ${exports.DEBUG_FIXED_PORTS_ENV} is set \u2014 inspectors bind PREDICTABLE ports (${I}+slot, workers ${I}+${$e}+i). Any account on this host can connect to 127.0.0.1:${I} and read the session UUID from /json/list. Unset it to use ephemeral ports.`:`[parent] Inspectors bind an EPHEMERAL loopback port; attach via the printed "Debugger listening" URL, or \`lensmcp debug <service>\` (control socket). Set ${exports.DEBUG_FIXED_PORTS_ENV}=1 for fixed ports if your IDE needs a pre-configured attach port \u2014 any account on this host can then reach them.`));const me=process.env.LENSMCP_LOG_FILE||"",be=me?(()=>{try{fs.mkdirSync(path.dirname(me),{recursive:!0});const g=fs.createWriteStream(me,{flags:"a",mode:384});try{fs.chmodSync(me,384)}catch{}return g}catch(g){return console.warn(`[parent] cannot open log file ${me}:`,g.message),null}})():null,F=/\x1b\[[0-9;]*m/g,Z=2e3,V=[],oe=new Set,ne=(0,devserver_transport_1.gatewayManaged)();for(const g of["log","info","warn","error"]){const b=console[g].bind(console),S=g==="log"||g==="info"?process.stdout:process.stderr;console[g]=(...K)=>{b(...K.map(x=>typeof x=="string"?(0,inspector_secret_1.forStream)(S,ne,x):x)),d(K.map(x=>typeof x=="string"?x:util.inspect(x)).join(" ")+`
13
- `)}}const We=a(g=>re[(g-1)%re.length],"colorFor"),M=a(g=>{if(ge===1)return"";const b=`[child#${g}] `;return`${We(g)}${b}${Ve}`},"tagFor"),ye=a(g=>g.startsWith("{")&&g.endsWith("}"),"isJsonLog"),se=a((g,b,S)=>{const K=prettyFactory({sync:!0,colorize:!0,crlf:!0,messageKey:"message",errorLikeObjectKeys:["err","error"],errorProps:"type,message,stack",ignore:["logContext","context","hostname","req","res","err.driverError","module","cloudEnvironment","frontegg-application-id","frontegg-tenant-id","frontegg-trace-id","frontegg-vendor-id","host","service","version","err","error"].join(","),messageFormat:"{if module}[{module}] {end}{if context}[{context}] {end}{if logContext}[{logContext}] {end}{message}",customPrettifiers:{stack:a(B=>`
14
- `+String(B),"stack")}}),x=a((B,k)=>{const H=B==="stdout"?process.stdout:process.stderr;try{S?.(k)}catch{}const q=ye(k)?K(k):`${k}
15
- `;H.write((0,inspector_secret_1.forStream)(H,ne,`${b}${q}`)),d(`${b}${q}`)},"write"),Ee=a((B,k)=>{if(!B)return;const H=readline.createInterface({input:B});H.on("line",q=>x(k,q)),H.on("close",()=>{})},"attach");Ee(g.stdout,"stdout"),Ee(g.stderr,"stderr")},"wireProcLogging"),Je=a(g=>se(g.proc,M(g.id),b=>g.tail.push(b)),"wireChildLogging");(async()=>{ensureOwnerOnlyDir(SOCK_DIR);const g=httpProxy.createProxyServer({});let b=Number(process.env.PORT)||0;b||(b=9090);const S=[],K=new Set;function x(){let e=0;for(;K.has(e);)e++;return K.add(e),e}u(x,"D"),a(x,"allocDebugSlot");let Ee=1,B=0,k=!1,H=ge,q=[],ie=0;const Oe=(0,swap_mode_1.swapMode)(),J=(()=>{const e=Number(process.env.LENSMCP_POD_BOOT_GRACE_MS);return Number.isFinite(e)&&e>=0?e:12e4})(),D=a(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"childExited"),Fe=a(e=>e.booting&&!D(e)&&Date.now()-e.spawnedAt<J,"stillBooting");function Y(){return S.filter(e=>e.healthy&&typeof e.socketPath=="string")}u(Y,"q"),a(Y,"healthyChildren");let ae,ce=0,X;const le={project:f,service:SERVICE_NAME||f,podGeneration:POD_GENERATION};function Te(e){const t=(0,service_build_events_1.buildAccountOf)(e.building);t&&t.startedAt!==ce&&(ce=t.startedAt,m.publish((0,service_build_events_1.buildServiceBuildEvent)(le,"started",t,{root:process.cwd()})));const s=(0,service_build_events_1.buildAccountOf)(e.failed);s&&(ce=0,m.publish((0,service_build_events_1.buildServiceBuildEvent)(le,"failed",s,{root:process.cwd()})));const n=(0,service_build_events_1.buildAccountOf)(e.unchanged);n&&n.startedAt===ce&&(ce=0,m.publish((0,service_build_events_1.buildServiceBuildEvent)(le,"unchanged",n,{root:process.cwd()})))}u(Te,"je"),a(Te,"recordBuildProgress");function ve(e){if(!e||typeof e!="object")return;const t=e;if(t.schemaVersion===1){Te(t),"failed"in t&&delete t.failed,"unchanged"in t&&delete t.unchanged,ae=t;for(const s of S)tell(s.proc,{type:"watcher",testimony:t})}}u(ve,"Ne"),a(ve,"recordWatcherTestimony");function de(e,t=256*1024){return new Promise(s=>{let n="",i=!1;e.on("data",o=>{i||(n+=o,n.length>t&&(i=!0))}),e.on("end",()=>{if(i||!n)return s(void 0);try{s(JSON.parse(n))}catch{s(void 0)}}),e.on("error",()=>s(void 0))})}u(de,"me"),a(de,"readJsonBody");function pe(){const e=Y();if(e.length===0)return null;const t=B%e.length;return B=(B+1)%e.length,e[t]}u(pe,"ye"),a(pe,"pickChild");function ue(e,t){const s=`Child#${e.id}`,n=SERVICE_NAME||f,i=Date.now();if(t.type==="pod-memory"){const o=t.report;if(!o||typeof o.live!="number")return;e.memory.latest=o,e.memory.history.push(o),e.memory.history.length>12&&e.memory.history.splice(0,e.memory.history.length-12),console.log(`[parent] ${(0,pod_memory_1.describePodMemory)(s,o)}`),m.publish((0,pod_memory_events_1.buildPodMemoryEvent)(W(e),o))}else if(t.type==="pod-memory-retained"){const o=t.retained;if(!o||typeof o.gen!="number")return;e.memory.retained.set(o.gen,{...o,at:i}),console.warn(`[parent] ${(0,pod_memory_1.describeRetained)(s,n,o)}`),m.publish((0,pod_memory_events_1.buildPodRetainedEvent)(W(e),o,i))}else{const o=t.released;if(!o||typeof o.gen!="number")return;e.memory.retained.delete(o.gen),console.log(`[parent] ${(0,pod_memory_1.describeReleased)(s,n,o)}`),m.publish((0,pod_memory_events_1.buildPodReleasedEvent)(W(e),o,i))}}u(ue,"Ee"),a(ue,"recordPodMemory");const Pe=new Map;let he=0;async function N(){const e=Ee++,t=childSockPath(e);cleanupSock(t);const s=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&s.unshift("--require","@swc-node/register"),s.push(...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const n=I?x():-1,i=(0,node_child_process_1.fork)(__filename,{env:(0,child_process_env_1.childProcessEnv)({...process.env,APP_RUNNER:"1",CHILD_SOCK_PATH:t,...n>=0&&{CHILD_DEBUG_PORT:String(inspectorPortFor(I,n))}}),stdio:["inherit","pipe","pipe","ipc"],execArgv:s,execPath:we("pod")}),o={id:e,proc:i,healthy:!1,lastError:null,debugSlot:n,tail:new exit_reason_1.TailBuffer,booting:!0,spawnedAt:Date.now(),bootReloadSeq:ie,memory:{history:[],retained:new Map}};return i.on("error",y=>console.error(`[parent] Child#${e}: ${y.message}`)),i.on("message",y=>{if(!y||typeof y!="object")return;const p=y;if(p.type==="ready")o.socketPath=String(p.socketPath),o.healthy=!0,o.booting=!1,console.log(`[parent] Child#${o.id} ready on socket ${o.socketPath}`),ae&&tell(i,{type:"watcher",testimony:ae}),ie!==o.bootReloadSeq&&(Oe==="process"?P():tell(i,{type:"reload"}));else if(p.type==="recycle-request")v(o,String(p.reason||"it has outgrown its bound"));else if(p.type==="inspector-url")o.inspectorUrl=String(p.url),console.log(`[parent] Child#${o.id} Debugger listening on ${p.url}`);else if(p.type==="reloaded"){if(U.has(o)){console.log(`[parent] Child#${o.id} finished a swap it began before it was retired \u2014 not serving it: a fresh pod has taken over`);return}o.socketPath=String(p.socketPath),o.healthy=!0,console.log(`[parent] Child#${o.id} hot-swapped on socket ${o.socketPath}`);const w=p.swap;w&&typeof w.generation=="number"&&typeof w.swaps=="number"&&m.publish((0,service_build_events_1.buildServiceSwapEvent)(W(o),{generation:w.generation,swaps:w.swaps,swapMs:typeof w.swapMs=="number"?w.swapMs:0,draining:typeof w.draining=="number"?w.draining:0},X,{root:process.cwd()}))}else p.type==="reload-error"?(o.lastError=String(p.error||"unknown reload error"),console.error(`[parent] Child#${o.id} reload error: ${o.lastError}`),o.healthy=!1):p.type==="boot-error"?(o.lastError=String(p.error||"unknown boot error"),console.error(`[parent] Child#${o.id} boot error: ${o.lastError}`),o.healthy=!1,o.booting=!1):p.type==="pod-memory"||p.type==="pod-memory-retained"||p.type==="pod-memory-released"?ue(o,p):p.type==="heap-snapshot-result"&&Pe.get(Number(p.id))?.(p)}),i.on("exit",(y,p)=>{o.booting=!1;for(const A of o.memory.retained.values()){const C={gen:A.gen,closedAt:A.closedAt,ageMs:Date.now()-A.closedAt,reason:"pod-exited"};console.log(`[parent] ${(0,pod_memory_1.describeReleased)(`Child#${o.id}`,SERVICE_NAME||f,C)}`),m.publish((0,pod_memory_events_1.buildPodReleasedEvent)(W(o),C,Date.now()))}o.memory.retained.clear(),o.memory.latest&&m.publish((0,pod_memory_events_1.buildPodExitedEvent)(W(o),{code:y,signal:p},Date.now())),o.debugSlot>=0&&(K.delete(o.debugSlot),o.debugSlot=-1);const w=p==="SIGINT"||p==="SIGTERM"||y===0;if(w?console.log(`[parent] Child#${o.id} exited cleanly (code=${y}, signal=${p??"none"})`):(console.error((0,exit_reason_1.crashReport)(`[parent] Child#${o.id} crashed (code=${y}, signal=${p??"none"}, pid=${o.proc.pid}, ${o.healthy?"was serving":"was not ready"})`,y,p,o.tail.snapshot())),o.lastError||(o.lastError=`Child exited abnormally (code=${y}, signal=${p??"none"})`)),o.healthy=!1,cleanupSock(o.socketPath,o.proc.pid),o.socketPath=void 0,!w&&!k){const A=S.indexOf(o);A>=0&&S.splice(A,1);const C=Date.now();if(q=q.filter(T=>C-T<3e4),q.length>=5){console.error(`[parent] crash-loop detected (${q.length} respawns/30s) \u2014 pausing auto-respawn; POST /webpack/reload to retry`);return}q.push(C),setTimeout(()=>{const T=S.filter(Q=>Q.proc.killed===!1).length;!k&&T<H&&(console.log(`[parent] respawning a crashed pod (${T}/${H} live)`),N().catch(()=>{}))},1500).unref?.()}}),S.push(o),Je(o),o}u(N,"T"),a(N,"spawnChild");async function Se(e){H=Math.max(H,e);const t=S.filter(n=>n.proc.killed===!1),s=e-t.length;for(let n=0;n<s;n++)await N()}u(Se,"be"),a(Se,"ensurePoolSize");async function Me(){const e=S.filter(t=>(!t.healthy||typeof t.socketPath!="string")&&!Fe(t));await Promise.all(e.map(async t=>{try{t.proc.kill("SIGTERM")}catch{}cleanupSock(t.socketPath,t.proc.pid),t.socketPath=void 0;const s=S.indexOf(t);s>=0&&S.splice(s,1),await N()}))}u(Me,"Ye"),a(Me,"respawnUnhealthy");const U=new Set;let fe=!1,r=0;const c=3e4,l=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return(Number.isFinite(e)&&e>=0?e:15*6e4)+6e4})();async function h(e,t={}){const s=Date.now(),n=await N(),i=Date.now()+J;for(;!n.healthy&&!n.lastError&&!D(n)&&Date.now()<i;){if(t.superseded?.()){const o=S.indexOf(n);o>=0&&S.splice(o,1);try{n.proc.kill("SIGTERM")}catch{}return{why:`a newer build landed while Child#${n.id} booted`,superseded:!0}}await new Promise(o=>{setTimeout(o,100).unref?.()})}if(k)return{why:"shutting down"};if(!n.healthy){const o=S.indexOf(n);o>=0&&S.splice(o,1);try{n.proc.kill("SIGTERM")}catch{}return{why:`its successor Child#${n.id} did not come up (${n.lastError??"no answer in time"})`}}return E(e),{fresh:n,readyMs:Date.now()-s}}u(h,"_"),a(h,"replacePod");function E(e){const t=S.indexOf(e);if(t>=0&&S.splice(t,1),e.healthy=!1,D(e))return;U.add(e),postRetiringNotice(e.socketPath,e.proc.pid);const s=setTimeout(()=>{if(!D(e)){console.error(`[parent] Child#${e.id} was still running ${l}ms after it was retired \u2014 killing it`);try{e.proc.kill("SIGKILL")}catch{}}},l);if(s.unref?.(),e.proc.once("exit",()=>{clearTimeout(s),U.delete(e)}),!tell(e.proc,{type:"retire"}))try{e.proc.kill("SIGTERM")}catch{}}u(E,"y"),a(E,"retirePod");async function v(e,t){const s=a(i=>{console.log(`[parent] Child#${e.id} asked for a fresh pod (${t}) \u2014 not now: ${i}`),tell(e.proc,{type:"recycle-declined"})},"decline");if(k||!S.includes(e))return;if(fe)return s("another pod is already being replaced");const n=Date.now()-r;if(n<c)return s(`a pod was replaced ${Math.round(n/1e3)}s ago`);fe=!0,console.log(`[parent] Child#${e.id} asked for a fresh pod \u2014 ${t}. Starting one; Child#${e.id} keeps serving until it is ready.`);try{const i=await h(e);if("why"in i){i.why!=="shutting down"&&s(i.why);return}r=Date.now(),console.log(`[parent] Child#${i.fresh.id} took over from Child#${e.id} (pid ${e.proc.pid} \u2192 ${i.fresh.proc.pid})`)}catch(i){s(`could not start a successor: ${i?.message??String(i)}`)}finally{fe=!1}}u(v,"m"),a(v,"recyclePod");let $,O=!1,z=0;function P(){if($){O=!0;return}$=(async()=>{do{O=!1;const e=ie;for(;fe&&!k;)await new Promise(s=>{setTimeout(s,100).unref?.()});let t=!1;for(const s of Y().filter(n=>n.bootReloadSeq<e)){if(k)break;if(!(!S.includes(s)||!s.healthy)){fe=!0;try{ee(),console.log(`[parent] A new build \u2014 starting a fresh pod for it; Child#${s.id} keeps serving the previous build until it is ready.`);const n=await h(s,{superseded:a(()=>ie!==e&&(0,swap_mode_1.abandonSuperseded)(z),"superseded")});if("why"in n){if(n.superseded){z+=1,console.log(`[parent] ${n.why} \u2014 abandoned; one fresh pod for the newest build instead (${z} in a row). Child#${s.id} keeps serving.`),t=!0;break}n.why!=="shutting down"&&console.error(`[parent] Child#${s.id} keeps serving the previous build \u2014 ${n.why}`);continue}z=0,console.log(`[parent] Child#${n.fresh.id} took over from Child#${s.id} with the new build (pid ${s.proc.pid} \u2192 ${n.fresh.proc.pid}, ready in ${(n.readyMs/1e3).toFixed(1)}s while Child#${s.id} served)`),m.publish((0,service_build_events_1.buildServiceSwapEvent)(W(n.fresh),{generation:1,swaps:0,swapMs:n.readyMs,draining:U.size,handoff:{fromPid:s.proc.pid??0}},X,{root:process.cwd()}))}catch(n){console.error(`[parent] Child#${s.id} keeps serving the previous build \u2014 could not start a successor: ${n?.message??String(n)}`)}finally{fe=!1}}}t&&(O=!0)}while(O&&!k)})().finally(()=>{$=void 0})}u(P,"N"),a(P,"handoffForReload");function ee(){const e=(0,swap_mode_1.maxRetiring)(),t=[...U].filter(s=>!D(s));for(;t.length>=e;){const s=t.shift();console.error(`[parent] Child#${s.id} (pid ${s.proc.pid}) was still finishing its work when a newer build replaced its successor too \u2014 stopping it (LENSMCP_SWAP_MAX_RETIRING=${e})`);try{s.proc.kill("SIGTERM")}catch{}}}u(ee,"J"),a(ee,"capRetiring");const G=[],He=new Map,qe=a(e=>{let t=He.get(e);return t||He.set(e,t={crashes:0,restarts:0}),t},"watchOf"),Xe=(0,worker_supervisor_1.workerBackoff)(),Ae=a((e,t)=>({project:f,service:SERVICE_NAME||f,worker:e,pid:t,podGeneration:POD_GENERATION}),"workerWho"),tt=[path.join(__dirname,"worker-guard.js"),path.join(__dirname,"worker-guard.ts")].find(e=>fs.existsSync(e));for(const e of WORKER_PROBLEMS)console.error(`[parent] ${e}`);function ze(e,t){const s=e.name,n=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH)),i=path.join(n,`${s}.js`),o=qe(s);if(!fs.existsSync(i))return console.error(`[parent] Worker "${s}" bundle not found: ${i}`),o.missing=i,m.publish((0,worker_supervisor_1.buildWorkerExitedEvent)(Ae(s,0),{ranMs:0,reason:`its bundle was not built (${path.basename(i)} is not in ${n})`})),null;o.missing=void 0;const y=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&y.unshift("--require","@swc-node/register"),tt&&y.push("--require",tt);try{y.push("--require",require.resolve("@lensmcp/node-instrumentation/register"))}catch{}const p=inspectorPortFor(I||9229,$e+Math.max(0,WORKER_NAMES.indexOf(s)));y.push(I?`--inspect=127.0.0.1:${p}`:`--inspect-port=127.0.0.1:${p}`,...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const w=(0,node_child_process_1.fork)(i,{env:(0,worker_supervisor_1.workerEnv)(process.env,e),stdio:["inherit","pipe","pipe","ipc"],execArgv:y,execPath:we(`w-${s}`)}),A={name:s,spec:e,proc:w,debugPort:p,startedAt:Date.now(),tail:new exit_reason_1.TailBuffer,stopping:!1};G.push(A),w.on("error",T=>console.error(`[parent] Worker "${s}": ${T.message}`)),se(w,`\x1B[35m[worker:${s}] \x1B[0m`,T=>{A.tail.push(T);const Q=/Debugger listening on (wss?:\/\/\S+)/.exec(T);Q&&(A.inspectorUrl=Q[1])});const C=setTimeout(()=>{if(!(Re(A)||A.stopping)){if(o.crashes>0){const T=Date.now()-A.startedAt;console.log(`[parent] Worker "${s}" (pid=${w.pid}) is up again \u2014 ${(0,worker_supervisor_1.spanOf)(T)} without a crash, after ${o.crashes} in a row`),m.publish((0,worker_supervisor_1.buildWorkerUpEvent)(Ae(s,w.pid??0),{ranMs:T,afterCrashes:o.crashes}))}o.crashes=0}},Xe.stableMs);return C.unref?.(),w.on("exit",(T,Q)=>{clearTimeout(C);const ke=G.indexOf(A);ke>=0&&G.splice(ke,1),rt(A,T,Q)}),console.log(`[parent] Worker "${s}" started (pid=${w.pid}, PORT=${(0,worker_supervisor_1.workerEnv)(process.env,e).PORT}${t==="respawn"?`, restart ${o.restarts}`:""})`),m.publish((0,worker_supervisor_1.buildWorkerStartedEvent)(Ae(s,w.pid??0),{why:t,port:e.port,restarts:o.restarts})),A}u(ze,"Ze"),a(ze,"spawnWorkerProcess");function rt(e,t,s){const{name:n}=e,i=e.proc.pid??0,o=Date.now()-e.startedAt,y=(0,worker_supervisor_1.workerExitVerdict)(t,s,e.stopping||k);if(y.kind==="stopped")return;const p=qe(n);if(y.kind==="exited"){p.lastEnd={at:Date.now(),pid:i,code:t,signal:s,ranMs:o,verdict:"exited"},console.warn(`[parent] Worker "${n}" (pid=${i}) exited on its own (code 0) after ${(0,worker_supervisor_1.spanOf)(o)} \u2014 not started again until the next build: a worker that ends is taken to have finished its work`),m.publish((0,worker_supervisor_1.buildWorkerExitedEvent)(Ae(n,i),{ranMs:o}));return}p.crashes+=1,p.lastEnd={at:Date.now(),pid:i,code:t,signal:s,ranMs:o,verdict:"crashed"};const w=(0,worker_supervisor_1.respawnDelay)(p.crashes,Xe),A=p.crashes>=worker_supervisor_1.CRASH_LOOP_AFTER;console.error((0,exit_reason_1.crashReport)(`[parent] Worker "${n}" crashed (code=${t}, signal=${s??"none"}, pid=${i}, after ${(0,worker_supervisor_1.spanOf)(o)})${y.external?" \u2014 stopped by a signal from outside its devserver":""}; starting it again in ${(0,worker_supervisor_1.spanOf)(w)}${A?` \u2014 ${p.crashes} crashes in a row: it is crash-looping (the wait doubles, up to ${(0,worker_supervisor_1.spanOf)(Xe.maxMs)})`:""}`,t,s,e.tail.snapshot())),m.publish((0,worker_supervisor_1.buildWorkerCrashedEvent)(Ae(n,i),{code:t,signal:s,ranMs:o,crashes:p.crashes,restarts:p.restarts,nextInMs:w,external:y.external,lines:e.tail.snapshot()})),clearTimeout(p.pending),p.nextAt=Date.now()+w,p.pending=setTimeout(()=>{p.pending=void 0,p.nextAt=void 0,!(k||G.some(C=>C.name===n))&&(p.restarts+=1,Ue(e.spec,"respawn"))},w),p.pending.unref?.()}u(rt,"ct"),a(rt,"workerEnded");function Ue(e,t){const s=qe(e.name);s.waiting=void 0;const n=e.port>0?[...te].find(o=>o.name===e.name&&!Re(o)):void 0;if(!n){ze(e,t);return}console.log(`[parent] Worker "${e.name}" starts once its predecessor (pid=${n.proc.pid}) has finished its work \u2014 it holds port ${e.port}`);const i=a(()=>{s.waiting===i&&(s.waiting=void 0),!k&&!G.some(o=>o.name===e.name)&&ze(e,t)},"go");s.waiting=i,n.proc.once("exit",i)}u(Ue,"Ve"),a(Ue,"startWorker");const ot=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(e)&&e>=0?e:15*6e4})(),nt=(()=>{const e=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(e)&&e>=1?Math.floor(e):1})(),te=new Set,Re=a(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"workerExited");function Be(e,t){if(te.delete(e),!Re(e)){console.error(`[parent] Worker "${e.name}" (pid=${e.proc.pid}) ${t} \u2014 killing it. A worker that returns from its SIGTERM handler but leaves a handle open (a Redis client handed to BullMQ is not closed by worker.close()) never exits on its own: close what it opened, or call process.exit().`);try{e.proc.kill("SIGKILL")}catch{}}}u(Be,"qe"),a(Be,"killDrainingWorker");function Qe(e){e.stopping=!0,tell(e.proc,{type:worker_retire_1.RETIRE_MESSAGE});try{e.proc.kill("SIGTERM")}catch{}if(Re(e))return;const t=[...te].filter(n=>n.name===e.name);for(;t.length>=nt;)Be(t.shift(),`was still running when a later reload replaced its successor (cap ${nt})`);te.add(e);const s=setTimeout(()=>Be(e,`was still running ${ot}ms after SIGTERM`),ot);s.unref?.(),e.proc.once("exit",()=>{clearTimeout(s),te.delete(e)})}u(Qe,"rt"),a(Qe,"retireWorker");function je(){for(const e of He.values())clearTimeout(e.pending),e.pending=void 0,e.nextAt=void 0,e.waiting=void 0}u(je,"Je"),a(je,"cancelWorkerStarts");function st(){for(const e of[...G])Qe(e);G.length=0,je();for(const e of WORKER_SPECS)qe(e.name).crashes=0,Ue(e,"reload")}u(st,"lt"),a(st,"restartWorkers");function it(){const e=Date.now();return{workers:WORKER_SPECS.map(t=>{const s=G.find(o=>o.name===t.name),n=He.get(t.name),i=s?"running":n?.pending?(n.crashes??0)>=worker_supervisor_1.CRASH_LOOP_AFTER?"crash-looping":"restarting":n?.waiting?"waiting":n?.missing?"missing":n?.lastEnd?.verdict==="exited"?"exited":"stopped";return{name:t.name,state:i,port:t.port,env:Object.keys(t.env),...s?{pid:s.proc.pid,upMs:e-s.startedAt}:{},crashes:n?.crashes??0,restarts:n?.restarts??0,...n?.nextAt?{nextInMs:Math.max(0,n.nextAt-e)}:{},...n?.lastEnd?{lastEnd:n.lastEnd}:{},...n?.missing?{missing:n.missing}:{}}}),draining:[...te].filter(t=>!Re(t)).map(t=>({name:t.name,pid:t.proc.pid}))}}u(it,"dt"),a(it,"workersView");const ht=debounce(async()=>{ie+=1;const e=Y();if(e.length>0)if(Oe==="process")P();else{console.log(`[parent] Forwarding reload to ${e.length} child(ren)`);for(const t of e)tell(t.proc,{type:"reload"})}await Me(),WORKER_NAMES.length>0&&st()},200),at=a((e,t)=>{const s=(0,notice_generation_1.noticeGeneration)(e.headers);return s===void 0||s===POD_GENERATION?!1:(e.resume(),t.writeHead(409,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!1,generation:POD_GENERATION,sentFor:s})),e.url==="/webpack/reload"&&console.log(`[parent] a build of generation g${s} reached generation g${POD_GENERATION} \u2014 not reloaded: it is not this generation's build`),!0)},"refusedForAnotherGeneration"),Ce=a(async(e,t)=>{if(e.method==="POST"&&e.url==="/webpack/reload"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);if(at(e,t))return;t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0})),de(e).then(i=>{const o=i;X=(0,service_build_events_1.buildAccountOf)(o?.build),ce=0,ve(o?.watcher)}),ht();return}if(e.method==="POST"&&e.url==="/webpack/watching"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);if(at(e,t))return;const i=await de(e);ve(i),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,relayed:ae!==void 0}));return}if(e.method==="POST"&&e.url==="/webpack/scale"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);let i="";e.on("data",o=>{i+=o}),e.on("end",async()=>{let o=0;try{o=Number(JSON.parse(i||"{}").pods)||0}catch{}o=Math.max(1,Math.min(o,16)),await Se(o),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,pods:o}))});return}if(e.method==="GET"&&e.url?.startsWith("/webpack/logs")){const i=new URL(e.url,"http://localhost").searchParams,o=Math.min(Math.max(Number(i.get("tail")??"100")||0,0),Z),y=i.get("follow")!=="0",p=i.get("plain")==="1",w=!(0,devserver_transport_1.isOwnerOnlyTransport)(e);t.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-cache"});const A=o===0?"":V.slice(-o).join(""),C=p?A.replace(F,""):A;if(t.write(w?(0,inspector_secret_1.redactInspectorUrls)(C):C),!y){t.end();return}const T={res:t,plain:p,redact:w};oe.add(T),e.on("close",()=>oe.delete(T));return}if(e.method==="POST"&&e.url?.startsWith("/webpack/debug")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const i=Number(new URL(e.url,"http://localhost").searchParams.get("port")||"");Number.isInteger(i)&&i>1024&&(I=i),I||(I=9229);const o=S.filter(p=>p.proc.exitCode===null&&p.proc.signalCode===null);for(const p of o)p.debugSlot<0&&(p.debugSlot=x()),tell(p.proc,{type:"debug-open",port:inspectorPortFor(I,p.debugSlot)});for(const p of G)try{p.proc.kill("SIGUSR1")}catch{}const y=Date.now()+2e3;for(;Date.now()<y&&o.some(p=>!p.inspectorUrl);)await new Promise(p=>setTimeout(p,50));t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,basePort:I,fixedPorts:usesFixedInspectorPorts(),pods:o.map(p=>({id:p.id,inspectorUrl:p.inspectorUrl??null})),workers:G.map(p=>({name:p.name,port:p.debugPort||(0,inspector_secret_1.inspectorPortOf)(p.inspectorUrl),inspectorUrl:p.inspectorUrl??null}))},null,2)+`
16
- `);return}if(e.method==="GET"&&e.url==="/webpack/workers"){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(it(),null,2)+`
17
- `);return}if(e.method==="GET"&&e.url==="/webpack/memory"){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const i=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),o=[...S,...U].map(y=>({id:y.id,pid:y.proc.pid??0,podGeneration:POD_GENERATION,healthy:y.healthy,retiring:U.has(y),latest:y.memory.latest??null,history:y.memory.history,retained:[...y.memory.retained.values()]}));t.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),t.end(JSON.stringify({ok:!0,service:SERVICE_NAME,project:f,bundle:{path:i},pods:o},null,2)+`
18
- `);return}if(e.method==="POST"&&e.url?.startsWith("/webpack/heap")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const i=a((L,Le)=>{t.writeHead(L,{"content-type":"application/json"}),t.end(JSON.stringify(Le,null,2)+`
19
- `)},"reply"),o=new URL(e.url,"http://localhost").searchParams,y=Number(o.get("pod")||""),p=o.has("maxMb")?Number(o.get("maxMb")):void 0;if(p!==void 0&&!(Number.isFinite(p)&&p>0)){i(400,{ok:!1,error:"maxMb takes a positive number of MB"});return}const w=Number.isInteger(y)&&y>0?S.find(L=>L.id===y):Y()[0];if(!w||D(w)){i(404,{ok:!1,error:y?`no pod #${y} \u2014 running: ${S.map(L=>`#${L.id}`).join(", ")||"none"}`:"no pod is serving"});return}if(Pe.size>0){i(409,{ok:!1,refused:"a heap snapshot is already being written for this service"});return}const A=(0,heap_snapshot_1.heapSnapshotPolicy)(),C=(0,heap_snapshot_1.heapSnapshotDir)();let T;try{(0,heap_snapshot_1.ensureHeapDir)(C);const L=(0,heap_snapshot_1.pruneHeapSnapshots)(C,A);L.length&&console.log(`[parent] removed ${L.length} older heap snapshot(s) from ${C}`),T=path.join(C,(0,heap_snapshot_1.heapSnapshotFileName)(SERVICE_NAME||f,w.id,w.proc.pid??0,w.memory.latest?.gen??0,Date.now()))}catch(L){i(500,{ok:!1,error:`cannot prepare ${C}: ${L.message}`});return}const Q=++he,ke=(0,heap_snapshot_1.availableSystemMemory)();let Ge;const R=await new Promise(L=>{const Le=setTimeout(()=>L(void 0),6e5);Le.unref?.(),Pe.set(Q,mt=>{clearTimeout(Le),L(mt)}),Ge=a(()=>{clearTimeout(Le),L(void 0)},"onExit"),w.proc.once("exit",Ge);const wt={type:"heap-snapshot",id:Q,file:T,...ke?{available:ke}:{},...p!==void 0?{maxHeapBytes:Math.floor(p*1048576)}:{}};tell(w.proc,wt)||Ge()}).finally(()=>{Pe.delete(Q),Ge&&w.proc.off("exit",Ge)});if(!R){i(504,{ok:!1,pod:w.id,error:"the pod did not finish the snapshot (it exited, or took longer than 10 minutes)"});return}R.ok?console.log(`[parent] Child#${w.id} wrote a ${Math.round((R.bytes??0)/1048576)} MB heap snapshot in ${R.ms} ms \u2192 ${R.file}`):console.warn(`[parent] Child#${w.id} heap snapshot not taken: ${R.refused??R.error}`),i(R.ok?200:R.refused?409:500,{ok:R.ok,pod:w.id,pid:w.proc.pid??0,service:SERVICE_NAME,bundle:path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),...ke?{available:ke}:{},...R.file?{file:R.file,bytes:R.bytes,ms:R.ms}:{},...R.live!==void 0?{live:R.live}:{},...R.gen!==void 0?{gen:R.gen,closedAlive:R.closedAlive??[]}:{},...R.refused?{refused:R.refused}:{},...R.error?{error:R.error}:{}});return}const s=matchGatewayRoute(e);if(s?.prependPrefix&&!e.url?.startsWith(s.prependPrefix)&&(e.url=s.prependPrefix+(e.url??"/")),s?.target){applyGatewayMiddleware(e),g.web(e,t,{target:s.target,autoRewrite:typeof s.target=="string",changeOrigin:!0},i=>{console.error(`[parent] proxy error to ${s.target}:`,i),t.statusCode=502,t.setHeader("content-type","text/plain; charset=utf-8"),t.end(`Upstream error from ${s.target}.`)});return}if(SERVICE_PREFIX){if(!e.url?.startsWith(SERVICE_PREFIX)){t.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),t.end(`Not found. This service is mounted at ${SERVICE_PREFIX}/`);return}e.url=e.url.slice(SERVICE_PREFIX.length)||"/"}applyGatewayMiddleware(e);const n=pe();if(!n){t.statusCode=503,t.setHeader("content-type","text/plain; charset=utf-8");const i=S.map(o=>`#${o.id}: ${o.lastError??"no error recorded"}`).join(`
12
+ })()`),(0,bundle_parent_1.routeBundleRequires)(requested,resolved);const exports=eval(`require(${JSON.stringify(resolved)})`);try{const mod=eval("require.cache")[resolved];lastImportedModule=mod&&typeof mod=="object"?mod:void 0}catch{}return exports}u(importFresh,"importFresh"),a(importFresh,"importFresh");function debounce(d,_){let f=null;return(...y)=>{f&&clearTimeout(f),f=setTimeout(()=>d(...y),_)}}if(u(debounce,"debounce"),a(debounce,"debounce"),process.env.APP_RUNNER==="1"){(0,stdio_guard_1.guardBrokenStdio)();const d=a(f=>{if(!inspector.url())try{inspector.open(f,"127.0.0.1",!1)}catch(W){console.warn(`[child] inspector.open(${f}) failed (port taken by another devserver?) \u2014 falling back to a random port:`,W.message);try{inspector.open(0,"127.0.0.1",!1)}catch{}}const y=inspector.url();y&&tell(process,{type:"inspector-url",url:y})},"openInspector"),_=process.env.CHILD_DEBUG_PORT;if(_!==void 0&&_!==""){const f=Number(_);Number.isInteger(f)&&(f===0||f>1024)&&d(f)}try{require("@lensmcp/node-instrumentation/register")}catch{}(async()=>{let f=null,y=!1,W,re=!1;const Je=(0,hot_swap_registries_1.registryPruningEnabled)(),ge=a((r,c)=>{const l=(0,hot_swap_registries_1.describePrune)(r,c);l&&console.log(l)},"logPrune");let j={app:null,handler:a((r,c)=>{c.statusCode=503,c.end("starting")},"handler"),inflight:0};const we=(()=>{const r=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(r)&&r>=0?r:15*6e4})(),I=a(r=>{const c=globalThis.__lensmcpActiveWork;if(typeof c!="function")return{count:0};try{const l=c(r);return{count:Number(l?.count??0),...l?.oldestStartedAt?{oldestStartedAt:l.oldestStartedAt}:{}}}catch{return{count:0}}},"activeWork"),Ne=a(r=>{const c=globalThis.__lensmcpStopWorkIntake;if(typeof c=="function")try{return c(r)}catch{return}},"stopWorkIntake"),me=a(r=>{const c=globalThis.__lensmcpWorkIntakeReport;if(!(r===void 0||typeof c!="function"))try{return c(r)??void 0}catch{return}},"workIntakeReport"),be=(()=>{const r=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(r)&&r>=1?Math.floor(r):1})(),F=new Set,Z=(()=>{const r=Number(process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS);return process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS!==void 0&&process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS!==""&&Number.isFinite(r)&&r>=0?r:3e4})(),V=a(r=>{if(!r.abandoned?.size)return 0;const c=Date.now();for(const[l,h]of r.abandoned)(l.writableEnded||c-h>=Z)&&r.abandoned.delete(l);return r.abandoned.size},"abandonedRunning"),oe=a(r=>{let c=0;for(const l of r.open??[])l.headersSent||(c+=1);return{unanswered:c+V(r),streams:Math.max(0,r.inflight-c),work:I(r.workGen).count}},"owedBy"),ne=a((r,c,l=`${c}s`)=>`${r} ${r===1?c:l}`,"plural");async function Fe(){if(Z<=0)return;const r=Date.now();let c=!1;for(;!(F.size<be);){const l=F.values().next().value;if(!l||l.closed)break;const h=oe(l);if(h.unanswered===0&&h.work===0)break;const E=(l.drainingSince??r)+Z-Date.now();if(E<=0)break;c||(c=!0,console.log(`[child] swap held \u2014 the app replaced ${Math.round((Date.now()-(l.drainingSince??r))/100)/10}s ago is still `+[h.unanswered?`answering ${ne(h.unanswered,"request")}`:"",h.work?`running ${ne(h.work,"background job")}`:""].filter(Boolean).join(" and ")+`, and this pod keeps at most ${be} replaced app(s) alive (LENSMCP_SWAP_MAX_DRAINING). The new build is applied when it is done \u2014 in ${Math.ceil(E/1e3)}s at the latest (LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS).`)),await new Promise(v=>{setTimeout(v,Math.min(100,E)).unref?.()})}c&&console.log(`[child] swap resumed after ${Date.now()-r}ms`)}u(Fe,"Be"),a(Fe,"holdForOwedWork");const M=(0,swap_recycle_1.swapRecyclePolicy)();let ye,se=0;const Xe=(()=>{const r=Number(process.env.LENSMCP_POD_RETIRE_NOTICE_MS);return Number.isFinite(r)&&r>=0?r:3500})();let g=!1,b=!1;const S=(0,pod_memory_1.podMemoryPolicy)();let K=0;const x=new Set;let Ee=!1;const B=a(()=>{if(!Ee)return;let r=0;for(const c of x)c.deref()===void 0?x.delete(c):r+=1;return r},"liveContainers"),k=(0,pod_memory_1.createPodMemoryMonitor)({policy:S,state:a(()=>({gen:j.gen??0,swaps:se,...ye===void 0?{}:{baseline:ye},busy:y||re||J.size>0,lastBusyAt:D}),"state"),send:a(r=>{tell(process,r)},"send"),containers:B,counter:(0,pod_memory_1.createLiveObjectCounter)(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH)),onRetained:a(()=>Oe(),"onRetained"),gc:a((r,c)=>(0,gc_notice_1.withGcNotice)($,pod_memory_1.fullGc,Date.now,r,c),"gc")}),H=a(()=>((0,gc_notice_1.withGcNotice)($,pod_memory_1.fullGc,Date.now,"live-heap")&&k.tracker.noteGc(),process.memoryUsage().heapUsed),"liveHeap"),U=(()=>{if(!(0,error_stack_release_1.errorFrameReleaseEnabled)())return null;try{const r=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH))+path.sep,c=`${path.sep}node_modules${path.sep}`,l=new Set(Object.keys(require.cache));return(0,error_stack_release_1.createErrorFrameReleaser)(require.cache,{skip:a(h=>l.has(h)||h.startsWith(r)&&!h.slice(r.length).includes(c)&&!h.slice(r.length).startsWith(`node_modules${path.sep}`),"skip")})}catch{return null}})();let ie=!1;function Te(){if(!(!U||ie))try{const r=U();r.errors>0&&console.log(`[child] read the stack of ${r.errors} Error object(s) that libraries created while loading and keep for good \u2014 unread, each held the functions that were on its stack, this bundle's included`)}catch(r){console.error("[child] could not release library error frames:",r),ie=!0}}u(Te,"xe"),a(Te,"releaseLibraryErrorFrames");const J=new Map;let D=Date.now();const He=a(()=>M.settleMs<=0||!y&&!re&&J.size===0&&Date.now()-D>=M.settleMs,"settled");let Y;function ae(r){if(!(!M.enabled||g||b)){if(M.settleMs<=0){X(r);return}Y&&clearTimeout(Y),Y=setTimeout(()=>{Y=void 0,He()?X(r):ae(r)},M.settleMs),Y.unref?.()}}u(ae,"_e"),a(ae,"recycleCheckWhenSettled");const ce=a(()=>{if(M.stuckCloseMs<=0)return 0;const r=Date.now();let c=0;for(const l of J.values())r-l>=M.stuckCloseMs&&(c+=1);return c},"stuckCloses");function X(r){if(!M.enabled||g||b||!process.send)return;const c=v8.getHeapStatistics().heap_size_limit,l=a(E=>{const v=k.oldestRetained();return{swaps:se,usedBytes:E,limitBytes:c,stuckCloses:ce(),settled:He(),...ye===void 0?{}:{baselineBytes:ye},...v?{retained:{generation:v.gen,ageMs:Date.now()-v.closedAt,gcs:v.gcs}}:{}}},"state");if(!(0,swap_recycle_1.recycleReason)(M,l(process.memoryUsage().heapUsed)))return;const h=(0,swap_recycle_1.recycleReason)(M,l(H()));h&&(g=!0,console.log(`[child] asking for a fresh pod ${r} \u2014 ${h}. This pod keeps serving until its successor is ready. Size the bound with LENSMCP_SWAP_RECYCLE_HEAP_FACTOR / _HEAP_RATIO / _MIN_MB / _RETAINED_MS, or turn it off with LENSMCP_SWAP_RECYCLE=0.`),tell(process,{type:"recycle-request",reason:h}))}u(X,"Q"),a(X,"considerRecycle");let le;function Oe(){if(!M.enabled||M.retainedMs<=0||g||b)return;const r=k.oldestRetained();if(!r)return;const c=r.closedAt+M.retainedMs-Date.now();if(c<=0){X("with a closed generation still in memory");return}le||(le=setTimeout(()=>{le=void 0,k.measure("retention-check").catch(()=>{})},c),le.unref?.())}u(Oe,"Ye"),a(Oe,"retainedRecycleCheck");function ve(r,c){const l={};c&&(l.module=c),r&&(l.app=r);try{const h=r?.app;if(h&&typeof h=="object"&&(l.nestApp=h,h.container&&typeof h.container=="object")){l.container=h.container;const E=rootModuleOf(h.container);E&&(l.rootModule=E)}}catch{}return l}u(ve,"Ne"),a(ve,"generationTargets");async function de(r,c){if(r.closed||(r.closed=!0,F.delete(r),c&&console.error(`[child] ${c}`),!r.app))return;J.set(r,Date.now());const l=M.enabled&&M.stuckCloseMs>0?setTimeout(()=>{J.has(r)&&(console.error(`[child] a previous app has been closing for ${Math.round(M.stuckCloseMs/1e3)}s and its close() has not returned \u2014 one of its shutdown hooks is waiting on something that does not end (a queue worker, a connection, a stream). It stays in memory until this pod is replaced.`),X("with a previous app stuck in close()"))},M.stuckCloseMs):void 0;l?.unref?.();const h=r.app;try{await r.app.close()}catch(E){console.error("[child] error closing a previous app:",E)}finally{J.delete(r),D=Date.now(),l&&clearTimeout(l),r.app=null,r.abandoned=void 0,r.handler=(E,v)=>{v.statusCode=503,v.end("closed")},r.gen!==void 0&&k.closed(r.gen,se,ve(h,r.module)),r.module=void 0}if(r.superseded){try{ge((0,hot_swap_registries_1.pruneRegistries)(r.superseded,"serve"),"after closing the previous app")}catch(E){console.error("[child] could not release the previous app's class registrations:",E)}r.superseded=void 0}ae("after closing the previous app")}u(de,"me"),a(de,"closeGeneration");async function pe(r){const c=Date.now();r.drainingSince=c;const l=a(()=>({inflight:r.inflight+V(r),work:I(r.workGen).count}),"busy"),h=l();if(h.inflight>0||h.work>0){for(;F.size>=be;){const N=F.values().next().value;if(!N)break;const T=oe(N),z=Math.round((Date.now()-(N.drainingSince??c))/1e3);if(T.unanswered===0&&T.streams===0&&T.work===0){await de(N);continue}await de(N,`closing a still-draining generation early \u2014 ${F.size} were pending and the cap is ${be} (each holds a whole app: DI container, DB pool, queue workers). `+(T.unanswered>0||T.work>0?`It was replaced ${z}s ago and had still not answered ${ne(T.unanswered,"request")}`+(T.work?` or finished ${ne(T.work,"background job")}`:"")+` \u2014 those fail now (a queue job keeps its lock until the TTL lapses). Raise LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS (currently ${Z}ms) to wait longer for them. `:`It held only ${ne(T.streams,"open stream")}; their clients reconnect to the new app. `)+"Raise LENSMCP_SWAP_MAX_DRAINING if this pod legitimately needs more.")}F.add(r)}for(;we>0&&Date.now()-c<we;){if(r.closed)return;const N=l();if(N.inflight===0&&N.work===0)break;await new Promise(T=>{setTimeout(T,250).unref?.()})}if(r.closed)return;const E=l(),v=me(r.workGen);E.inflight>0||E.work>0?console.error(`[child] swap drain expired after ${Date.now()-c}ms \u2014 closing the previous app with ${E.inflight} in-flight request(s) and ${E.work} background job(s) still running. `+(v?`Previous app still processing ${v.running} queue job(s); ${v.takenAfterStop} were taken after the swap. `:"")+`A queue job killed here keeps its lock until the TTL lapses. Raise LENSMCP_SWAP_DRAIN_MS (currently ${we}ms) if this is legitimate work.`):(Date.now()-c>250||v?.runningAtStop||v?.takenAfterStop)&&console.log(`[child] previous app drained in ${Date.now()-c}ms \u2014 closing it`+(v?` (it finished ${v.finishedAfterStop} queue job(s) after the swap; ${v.takenAfterStop} were taken after the swap)`:"")),await de(r)}u(pe,"ye"),a(pe,"drainThenClose");async function ue(){if(y)return re=!0,console.log("[child] Reload deferred \u2014 will re-swap after current swap completes"),f;y=!0,D=Date.now(),await Fe(),process.removeAllListeners("uncaughtException"),process.removeAllListeners("unhandledRejection"),process.on("uncaughtException",(P,ee)=>{console.error(`[child] uncaughtException (${ee}):`,P)}),process.on("unhandledRejection",P=>{const ee=P instanceof Error?P.stack||P.message:String(P);ee.includes("FronteggContextScope")||ee.includes("populateLoggerMetadata")||console.error("[child] unhandledRejection:",P)});let r;if(Je)try{r=(0,hot_swap_registries_1.captureRegistries)()}catch{r=void 0}const c=global.__lensmcpBeginWorkGeneration,l=typeof c=="function"?c():void 0;try{try{await importFresh(BUNDLE_PATH)}catch(P){if(!(P instanceof SyntaxError))throw P;console.warn(`[child] bundle was unreadable mid-write (${P.message}) \u2014 retrying the swap once`),await new Promise(ee=>setTimeout(ee,400)),await importFresh(BUNDLE_PATH)}}catch(P){throw y=!1,D=Date.now(),P}if(typeof global.createChildApp!="function")throw y=!1,D=Date.now(),new Error(`Bundle '${BUNDLE_PATH}' does not export createChildApp() and the zero-touch bridge is not active. Either install @lensmcp/node-instrumentation (a plain NestFactory.create + app.listen main.ts then just works) or set global.createChildApp in main.ts when DEVSERVER_MODE === '1'.`);let h;if(r)try{h=(0,hot_swap_registries_1.supersededSince)(r),ge((0,hot_swap_registries_1.pruneRegistries)(h,"build"),"at the swap")}catch(P){console.error("[child] could not release superseded class registrations:",P)}let E;try{E=await global.createChildApp()}catch(P){throw y=!1,D=Date.now(),takeImportedModule(),P}const v=j;h?.size&&(v.app?v.superseded=h:ge((0,hot_swap_registries_1.pruneRegistries)(h,"serve"),"at the swap")),f=E;const N=takeImportedModule();j={app:E,handler:E.handler,inflight:0,gen:++K,...N?{module:N}:{},...l===void 0?{}:{workGen:l}};const T=ve(E,void 0).container;T&&(x.add(new WeakRef(T)),Ee=!0);const z=v.app&&l!==void 0?Ne(l):void 0;return console.log("[child] Swapped to fresh app (previous draining in background)"+(z?.workers?`; its ${z.workers} queue worker(s) stopped taking new jobs, previous app still processing ${z.runningAtStop} job(s)`:"")),Te(),v.app&&(se+=1,pe(v).catch(P=>console.error("[child] background close error:",P)),setTimeout(()=>X("30s after a hot swap"),3e4).unref?.(),k.swapped(v.gen,()=>v.closed===!0&&!J.has(v))),y=!1,D=Date.now(),re?(re=!1,ue()):E}u(ue,"Ee"),a(ue,"swapNow");const Pe=debounce(async()=>{try{console.log("[child] /webpack/reload"),await ue()}catch(r){console.error("[child] reload failed:",r)}},250),he=http.createServer((r,c)=>{if(r.method==="POST"&&r.url==="/webpack/reload"){c.writeHead(200,{"content-type":"application/json"}),c.end(JSON.stringify({ok:!0})),Pe();return}if(r.method==="GET"&&r.url==="/__lensmcp/alive"){const E=r.headers["x-internal-token"],v=process.env.LENSMCP_SERVICE_KEY;if(v&&E!==v){c.writeHead(404,{"content-type":"text/plain"}),c.end("not found");return}const N=I();c.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),c.end(JSON.stringify({ok:!0,pid:process.pid,swapping:y,inflight:j.inflight,oldestInflightAt:j.oldestAt,activeWork:N.count,oldestWorkAt:N.oldestStartedAt,keyFingerprint:serviceKeyFingerprint(),...W?{watcher:W}:{},...Number.isFinite(Number(process.env.LENSMCP_POD_GENERATION))&&process.env.LENSMCP_POD_GENERATION?{podGeneration:Number(process.env.LENSMCP_POD_GENERATION)}:{}}));return}const l=j;l.inflight+=1,(l.open??=new Set).add(c),l.oldestAt===void 0&&(l.oldestAt=Date.now());const h=k.request();c.on("close",()=>{l.inflight-=1,l.open?.delete(c),Z>0&&!l.closed&&!c.headersSent&&!c.writableEnded&&((l.abandoned??=new Map).set(c,Date.now()),l.abandoned.size>256&&V(l)),l.inflight===0&&(l.oldestAt=void 0),h()}),l.handler(r,c)});he.keepAliveTimeout=0;const $=process.env.CHILD_SOCK_PATH;process.on("disconnect",()=>{cleanupSock($),process.exit(0)});try{const r=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH);if((0,schema_first_instance_1.schemaPrewarmEnabled)())try{const l=(0,schema_first_instance_1.prewarmZodFor)(r);l?.created&&console.log(`[child] zod${l.version?` ${l.version}`:""}: built ${l.created} throwaway schemas first, so none of the bundle's own is the first of its class`)}catch{}if((0,redis_disconnect_fix_1.redisDisconnectFixEnabled)())try{const l=(0,redis_disconnect_fix_1.finishStrandedDisconnectsFor)(r);l?.patched&&console.log(`[child] ioredis${l.versions.length?` ${l.versions.join(", ")}`:""}: a disconnect() between reconnect attempts now ends the client \u2014 it used to leave a queue worker's close() waiting for good`)}catch{}await ue(),ye=(await k.booted()).live,console.log(`[child] Using bundle: ${r}`),claimSock($);let c=!1;he.on("error",l=>{if(c){console.error("[child] server error:",l);return}console.error(`[child] could not listen on ${$} (${l.code??l.message}) \u2014 exiting; the devserver starts another pod`),tell(process,{type:"boot-error",error:`could not listen on ${$}: ${String(l?.stack||l)}`}),cleanupSock($),process.exitCode=1,setTimeout(()=>process.exit(1),100)}),he.listen($,()=>{c=!0,console.log(`[child] Listening on ${$}`),tell(process,{type:"ready",socketPath:$})})}catch(r){console.error("[child] Startup error:",r),tell(process,{type:"boot-error",error:String(r?.stack||r)}),process.exitCode=1;return}process.on("message",async r=>{if(!(!r||typeof r!="object")){if(r.type==="debug-open"){const c=Number(r.port);d(Number.isInteger(c)&&c>1024?c:0);return}if(r.type==="watcher"){const c=r.testimony;c&&typeof c=="object"&&(W=c);return}if(r.type==="heap-snapshot"){Me(r);return}if(r.type==="recycle-declined"){g=!1;return}if(r.type==="retire"){q();return}if(r.type==="reload"){if(b)return;try{const c=Date.now();await ue(),tell(process,{type:"reloaded",socketPath:$,swap:{generation:K,swaps:se,swapMs:Date.now()-c,draining:F.size}})}catch(c){console.error("[child] reload error:",c),tell(process,{type:"reload-error",error:String(c?.stack||c)})}}}});let Se=!1;async function Me(r){const c=a(l=>{tell(process,{type:"heap-snapshot-result",id:r.id,...l})},"reply");if(Se)return c({ok:!1,refused:"a snapshot of this pod is already being written"});Se=!0;try{const l=H(),h=k.tracker.views().map(T=>T.gen),E=(0,heap_snapshot_1.heapSnapshotPolicy)();r.maxHeapBytes&&(E.maxHeapBytes=r.maxHeapBytes);const v=(0,heap_snapshot_1.heapSnapshotRefusal)(E,{live:l,...r.available?{available:r.available}:{}});if(v)return c({ok:!1,refused:v,live:l});console.log(`[child] writing a heap snapshot (${Math.round(l/1048576)} MB live) \u2014 the pod pauses while V8 serialises it`);const N=await(0,heap_snapshot_1.writeHeapSnapshot)(r.file);c({ok:!0,file:r.file,bytes:N.bytes,ms:N.ms,live:l,gen:j.gen??0,closedAlive:h})}catch(l){c({ok:!1,error:l?.message??String(l)})}finally{Se=!1}}u(Me,"Ke"),a(Me,"takeHeapSnapshot");async function q(r="a fresh pod has taken over"){if(b)return;b=!0,k.stop(),console.log(`[child] retiring \u2014 ${r}; ${path.basename($,".sock")} (pid ${process.pid}) is finishing in-flight work, then exiting`);const c=Ne(Number.POSITIVE_INFINITY);c?.workers&&console.log(`[child] its ${c.workers} queue worker(s) stopped taking new jobs, still processing ${c.runningAtStop} job(s)`);try{fs.writeFileSync(sockRetiringPath($),String(process.pid),{flag:"w",mode:384})}catch{}await new Promise(h=>{setTimeout(h,Xe).unref?.()}),cleanupSock($),he.close();const l=Date.now();for(;Date.now()-l<we;){he.closeIdleConnections?.();let h=0;for(const E of F)h+=oe(E).unanswered;if(j.inflight+V(j)===0&&h===0&&I().count===0)break;await new Promise(E=>{setTimeout(E,250).unref?.()})}setTimeout(()=>process.exit(0),3e4).unref?.();try{await f?.close()}catch(h){console.error("[child] close error while retiring:",h)}process.exit(0)}u(q,"B"),a(q,"retire"),process.on("beforeExit",()=>{try{inspector?.close?.()}catch{}});const fe=a(async r=>{console.log(`[child ${r}] shutting down\u2026`);const c=f?.close().catch(h=>console.error("[child] close error:",h)),l=new Promise(h=>he.close(()=>h()));cleanupSock($),setTimeout(()=>process.exit(0),700).unref(),await Promise.all([c,l]),process.exit(0)},"shutdown");["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(r=>{process.on(r,()=>{if(r==="SIGTERM"&&!b&&(0,handoff_retire_1.handoffRetireRequested)(SOCK_DIR,POD_GENERATION)){q("this generation was handed over to a newer one");return}inspector?.close?.(),fe(r)})})})()}else{let d=u(function(g){V.push(g),V.length>Z&&V.splice(0,V.length-Z),be?.write((0,inspector_secret_1.redactInspectorUrls)(g.replace(F,"")));for(const b of oe)try{const S=b.plain?g.replace(F,""):g;b.res.write(b.redact?(0,inspector_secret_1.redactInspectorUrls)(S):S)}catch{oe.delete(b)}},"ge");a(d,"emitLogLine");const _=12,f=process.env.LENSMCP_PROJECT||SERVICE_NAME||"service",y=(0,pod_memory_events_1.createPodMemoryPublisher)(process.env.LENSMCP_EVENT_FILE),W=a(g=>({project:f,service:SERVICE_NAME||f,pod:g.id,pid:g.proc.pid??0,podGeneration:POD_GENERATION}),"podIdentity"),re=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[31m"],Je="\x1B[0m",ge=Math.max(1,Number(process.env.CHILD_COUNT||1)),j=LENSMCP_WS_KEY||path.basename(process.cwd()),we=a(g=>(0,process_name_1.namedExecPath)((0,process_name_1.processName)(j,SERVICE_NAME||"service",g)),"execPathFor");let I=(()=>{const g=Number(process.env.LENSMCP_DEBUG_PORT||"");return Number.isInteger(g)&&g>1024?g:0})();const Ne=20;I&&(console.warn("[parent] DEBUGGER ENABLED \u2014 pods and workers open a Node inspector. Node's inspector has NO authentication: the ws:// URL's UUID is the whole credential, and any account on this host that obtains it can run code as you. Do not enable this on a shared machine. (issues/closed/codex-security-06)"),console.warn(usesFixedInspectorPorts()?`[parent] ${exports.DEBUG_FIXED_PORTS_ENV} is set \u2014 inspectors bind PREDICTABLE ports (${I}+slot, workers ${I}+${Ne}+i). Any account on this host can connect to 127.0.0.1:${I} and read the session UUID from /json/list. Unset it to use ephemeral ports.`:`[parent] Inspectors bind an EPHEMERAL loopback port; attach via the printed "Debugger listening" URL, or \`lensmcp debug <service>\` (control socket). Set ${exports.DEBUG_FIXED_PORTS_ENV}=1 for fixed ports if your IDE needs a pre-configured attach port \u2014 any account on this host can then reach them.`));const me=process.env.LENSMCP_LOG_FILE||"",be=me?(()=>{try{fs.mkdirSync(path.dirname(me),{recursive:!0});const g=fs.createWriteStream(me,{flags:"a",mode:384});try{fs.chmodSync(me,384)}catch{}return g}catch(g){return console.warn(`[parent] cannot open log file ${me}:`,g.message),null}})():null,F=/\x1b\[[0-9;]*m/g,Z=2e3,V=[],oe=new Set,ne=(0,devserver_transport_1.gatewayManaged)();for(const g of["log","info","warn","error"]){const b=console[g].bind(console),S=g==="log"||g==="info"?process.stdout:process.stderr;console[g]=(...K)=>{b(...K.map(x=>typeof x=="string"?(0,inspector_secret_1.forStream)(S,ne,x):x)),d(K.map(x=>typeof x=="string"?x:util.inspect(x)).join(" ")+`
13
+ `)}}const Fe=a(g=>re[(g-1)%re.length],"colorFor"),M=a(g=>{if(ge===1)return"";const b=`[child#${g}] `;return`${Fe(g)}${b}${Je}`},"tagFor"),ye=a(g=>g.startsWith("{")&&g.endsWith("}"),"isJsonLog"),se=a((g,b,S)=>{const K=prettyFactory({sync:!0,colorize:!0,crlf:!0,messageKey:"message",errorLikeObjectKeys:["err","error"],errorProps:"type,message,stack",ignore:["logContext","context","hostname","req","res","err.driverError","module","cloudEnvironment","frontegg-application-id","frontegg-tenant-id","frontegg-trace-id","frontegg-vendor-id","host","service","version","err","error"].join(","),messageFormat:"{if module}[{module}] {end}{if context}[{context}] {end}{if logContext}[{logContext}] {end}{message}",customPrettifiers:{stack:a(B=>`
14
+ `+String(B),"stack")}}),x=a((B,k)=>{const H=B==="stdout"?process.stdout:process.stderr;try{S?.(k)}catch{}const U=ye(k)?K(k):`${k}
15
+ `;H.write((0,inspector_secret_1.forStream)(H,ne,`${b}${U}`)),d(`${b}${U}`)},"write"),Ee=a((B,k)=>{if(!B)return;const H=readline.createInterface({input:B});H.on("line",U=>x(k,U)),H.on("close",()=>{})},"attach");Ee(g.stdout,"stdout"),Ee(g.stderr,"stderr")},"wireProcLogging"),Xe=a(g=>se(g.proc,M(g.id),b=>g.tail.push(b)),"wireChildLogging");(async()=>{ensureOwnerOnlyDir(SOCK_DIR);const g=httpProxy.createProxyServer({});let b=Number(process.env.PORT)||0;b||(b=9090);const S=[],K=new Set;function x(){let e=0;for(;K.has(e);)e++;return K.add(e),e}u(x,"D"),a(x,"allocDebugSlot");let Ee=1,B=0,k=!1,H=ge,U=[],ie=0;const Te=(0,swap_mode_1.swapMode)(),J=(()=>{const e=Number(process.env.LENSMCP_POD_BOOT_GRACE_MS);return Number.isFinite(e)&&e>=0?e:12e4})(),D=a(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"childExited"),He=a(e=>e.booting&&!D(e)&&Date.now()-e.spawnedAt<J,"stillBooting");function Y(){return S.filter(e=>e.healthy&&typeof e.socketPath=="string")}u(Y,"q"),a(Y,"healthyChildren");let ae,ce=0,X;const le={project:f,service:SERVICE_NAME||f,podGeneration:POD_GENERATION};function Oe(e){const t=(0,service_build_events_1.buildAccountOf)(e.building);t&&t.startedAt!==ce&&(ce=t.startedAt,y.publish((0,service_build_events_1.buildServiceBuildEvent)(le,"started",t,{root:process.cwd()})));const s=(0,service_build_events_1.buildAccountOf)(e.failed);s&&(ce=0,y.publish((0,service_build_events_1.buildServiceBuildEvent)(le,"failed",s,{root:process.cwd()})));const n=(0,service_build_events_1.buildAccountOf)(e.unchanged);n&&n.startedAt===ce&&(ce=0,y.publish((0,service_build_events_1.buildServiceBuildEvent)(le,"unchanged",n,{root:process.cwd()})))}u(Oe,"Ye"),a(Oe,"recordBuildProgress");function ve(e){if(!e||typeof e!="object")return;const t=e;if(t.schemaVersion===1){Oe(t),"failed"in t&&delete t.failed,"unchanged"in t&&delete t.unchanged,ae=t;for(const s of S)tell(s.proc,{type:"watcher",testimony:t})}}u(ve,"Ne"),a(ve,"recordWatcherTestimony");function de(e,t=256*1024){return new Promise(s=>{let n="",i=!1;e.on("data",o=>{i||(n+=o,n.length>t&&(i=!0))}),e.on("end",()=>{if(i||!n)return s(void 0);try{s(JSON.parse(n))}catch{s(void 0)}}),e.on("error",()=>s(void 0))})}u(de,"me"),a(de,"readJsonBody");function pe(){const e=Y();if(e.length===0)return null;const t=B%e.length;return B=(B+1)%e.length,e[t]}u(pe,"ye"),a(pe,"pickChild");function ue(e,t){const s=`Child#${e.id}`,n=SERVICE_NAME||f,i=Date.now();if(t.type==="pod-memory"){const o=t.report;if(!o||typeof o.live!="number")return;e.memory.latest=o,e.memory.history.push(o),e.memory.history.length>12&&e.memory.history.splice(0,e.memory.history.length-12),console.log(`[parent] ${(0,pod_memory_1.describePodMemory)(s,o)}`),y.publish((0,pod_memory_events_1.buildPodMemoryEvent)(W(e),o))}else if(t.type==="pod-memory-retained"){const o=t.retained;if(!o||typeof o.gen!="number")return;e.memory.retained.set(o.gen,{...o,at:i}),console.warn(`[parent] ${(0,pod_memory_1.describeRetained)(s,n,o)}`),y.publish((0,pod_memory_events_1.buildPodRetainedEvent)(W(e),o,i))}else{const o=t.released;if(!o||typeof o.gen!="number")return;e.memory.retained.delete(o.gen),console.log(`[parent] ${(0,pod_memory_1.describeReleased)(s,n,o)}`),y.publish((0,pod_memory_events_1.buildPodReleasedEvent)(W(e),o,i))}}u(ue,"Ee"),a(ue,"recordPodMemory");const Pe=new Map;let he=0;async function $(){const e=Ee++,t=childSockPath(e);cleanupSock(t);const s=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&s.unshift("--require","@swc-node/register"),s.push(...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const n=I?x():-1,i=(0,node_child_process_1.fork)(__filename,{env:(0,child_process_env_1.childProcessEnv)({...process.env,APP_RUNNER:"1",CHILD_SOCK_PATH:t,...n>=0&&{CHILD_DEBUG_PORT:String(inspectorPortFor(I,n))}}),stdio:["inherit","pipe","pipe","ipc"],execArgv:s,execPath:we("pod")}),o={id:e,proc:i,healthy:!1,lastError:null,debugSlot:n,tail:new exit_reason_1.TailBuffer,booting:!0,spawnedAt:Date.now(),bootReloadSeq:ie,memory:{history:[],retained:new Map}};return i.on("error",m=>console.error(`[parent] Child#${e}: ${m.message}`)),i.on("message",m=>{if(!m||typeof m!="object")return;const p=m;if(p.type==="ready")o.socketPath=String(p.socketPath),o.healthy=!0,o.booting=!1,console.log(`[parent] Child#${o.id} ready on socket ${o.socketPath}`),ae&&tell(i,{type:"watcher",testimony:ae}),ie!==o.bootReloadSeq&&(Te==="process"?P():tell(i,{type:"reload"}));else if(p.type==="recycle-request")v(o,String(p.reason||"it has outgrown its bound"));else if(p.type==="inspector-url")o.inspectorUrl=String(p.url),console.log(`[parent] Child#${o.id} Debugger listening on ${p.url}`);else if(p.type==="reloaded"){if(q.has(o)){console.log(`[parent] Child#${o.id} finished a swap it began before it was retired \u2014 not serving it: a fresh pod has taken over`);return}o.socketPath=String(p.socketPath),o.healthy=!0,console.log(`[parent] Child#${o.id} hot-swapped on socket ${o.socketPath}`);const w=p.swap;w&&typeof w.generation=="number"&&typeof w.swaps=="number"&&y.publish((0,service_build_events_1.buildServiceSwapEvent)(W(o),{generation:w.generation,swaps:w.swaps,swapMs:typeof w.swapMs=="number"?w.swapMs:0,draining:typeof w.draining=="number"?w.draining:0},X,{root:process.cwd()}))}else p.type==="reload-error"?(o.lastError=String(p.error||"unknown reload error"),console.error(`[parent] Child#${o.id} reload error: ${o.lastError}`),o.healthy=!1):p.type==="boot-error"?(o.lastError=String(p.error||"unknown boot error"),console.error(`[parent] Child#${o.id} boot error: ${o.lastError}`),o.healthy=!1,o.booting=!1):p.type==="pod-memory"||p.type==="pod-memory-retained"||p.type==="pod-memory-released"?ue(o,p):p.type==="heap-snapshot-result"&&Pe.get(Number(p.id))?.(p)}),i.on("exit",(m,p)=>{o.booting=!1;for(const A of o.memory.retained.values()){const C={gen:A.gen,closedAt:A.closedAt,ageMs:Date.now()-A.closedAt,reason:"pod-exited"};console.log(`[parent] ${(0,pod_memory_1.describeReleased)(`Child#${o.id}`,SERVICE_NAME||f,C)}`),y.publish((0,pod_memory_events_1.buildPodReleasedEvent)(W(o),C,Date.now()))}o.memory.retained.clear(),o.memory.latest&&y.publish((0,pod_memory_events_1.buildPodExitedEvent)(W(o),{code:m,signal:p},Date.now())),o.debugSlot>=0&&(K.delete(o.debugSlot),o.debugSlot=-1);const w=p==="SIGINT"||p==="SIGTERM"||m===0;if(w?console.log(`[parent] Child#${o.id} exited cleanly (code=${m}, signal=${p??"none"})`):(console.error((0,exit_reason_1.crashReport)(`[parent] Child#${o.id} crashed (code=${m}, signal=${p??"none"}, pid=${o.proc.pid}, ${o.healthy?"was serving":"was not ready"})`,m,p,o.tail.snapshot())),o.lastError||(o.lastError=`Child exited abnormally (code=${m}, signal=${p??"none"})`)),o.healthy=!1,cleanupSock(o.socketPath,o.proc.pid),o.socketPath=void 0,!w&&!k){const A=S.indexOf(o);A>=0&&S.splice(A,1);const C=Date.now();if(U=U.filter(O=>C-O<3e4),U.length>=5){console.error(`[parent] crash-loop detected (${U.length} respawns/30s) \u2014 pausing auto-respawn; POST /webpack/reload to retry`);return}U.push(C),setTimeout(()=>{const O=S.filter(Q=>Q.proc.killed===!1).length;!k&&O<H&&(console.log(`[parent] respawning a crashed pod (${O}/${H} live)`),$().catch(()=>{}))},1500).unref?.()}}),S.push(o),Xe(o),o}u($,"T"),a($,"spawnChild");async function Se(e){H=Math.max(H,e);const t=S.filter(n=>n.proc.killed===!1),s=e-t.length;for(let n=0;n<s;n++)await $()}u(Se,"be"),a(Se,"ensurePoolSize");async function Me(){const e=S.filter(t=>(!t.healthy||typeof t.socketPath!="string")&&!He(t));await Promise.all(e.map(async t=>{try{t.proc.kill("SIGTERM")}catch{}cleanupSock(t.socketPath,t.proc.pid),t.socketPath=void 0;const s=S.indexOf(t);s>=0&&S.splice(s,1),await $()}))}u(Me,"Ke"),a(Me,"respawnUnhealthy");const q=new Set;let fe=!1,r=0;const c=3e4,l=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return(Number.isFinite(e)&&e>=0?e:15*6e4)+6e4})();async function h(e,t={}){const s=Date.now(),n=await $(),i=Date.now()+J;for(;!n.healthy&&!n.lastError&&!D(n)&&Date.now()<i;){if(t.superseded?.()){const o=S.indexOf(n);o>=0&&S.splice(o,1);try{n.proc.kill("SIGTERM")}catch{}return{why:`a newer build landed while Child#${n.id} booted`,superseded:!0}}await new Promise(o=>{setTimeout(o,100).unref?.()})}if(k)return{why:"shutting down"};if(!n.healthy){const o=S.indexOf(n);o>=0&&S.splice(o,1);try{n.proc.kill("SIGTERM")}catch{}return{why:`its successor Child#${n.id} did not come up (${n.lastError??"no answer in time"})`}}return E(e),{fresh:n,readyMs:Date.now()-s}}u(h,"_"),a(h,"replacePod");function E(e){const t=S.indexOf(e);if(t>=0&&S.splice(t,1),e.healthy=!1,D(e))return;q.add(e),postRetiringNotice(e.socketPath,e.proc.pid);const s=setTimeout(()=>{if(!D(e)){console.error(`[parent] Child#${e.id} was still running ${l}ms after it was retired \u2014 killing it`);try{e.proc.kill("SIGKILL")}catch{}}},l);if(s.unref?.(),e.proc.once("exit",()=>{clearTimeout(s),q.delete(e)}),!tell(e.proc,{type:"retire"}))try{e.proc.kill("SIGTERM")}catch{}}u(E,"y"),a(E,"retirePod");async function v(e,t){const s=a(i=>{console.log(`[parent] Child#${e.id} asked for a fresh pod (${t}) \u2014 not now: ${i}`),tell(e.proc,{type:"recycle-declined"})},"decline");if(k||!S.includes(e))return;if(fe)return s("another pod is already being replaced");const n=Date.now()-r;if(n<c)return s(`a pod was replaced ${Math.round(n/1e3)}s ago`);fe=!0,console.log(`[parent] Child#${e.id} asked for a fresh pod \u2014 ${t}. Starting one; Child#${e.id} keeps serving until it is ready.`);try{const i=await h(e);if("why"in i){i.why!=="shutting down"&&s(i.why);return}r=Date.now(),console.log(`[parent] Child#${i.fresh.id} took over from Child#${e.id} (pid ${e.proc.pid} \u2192 ${i.fresh.proc.pid})`)}catch(i){s(`could not start a successor: ${i?.message??String(i)}`)}finally{fe=!1}}u(v,"m"),a(v,"recyclePod");let N,T=!1,z=0;function P(){if(N){T=!0;return}N=(async()=>{do{T=!1;const e=ie;for(;fe&&!k;)await new Promise(s=>{setTimeout(s,100).unref?.()});let t=!1;for(const s of Y().filter(n=>n.bootReloadSeq<e)){if(k)break;if(!(!S.includes(s)||!s.healthy)){fe=!0;try{ee(),console.log(`[parent] A new build \u2014 starting a fresh pod for it; Child#${s.id} keeps serving the previous build until it is ready.`);const n=await h(s,{superseded:a(()=>ie!==e&&(0,swap_mode_1.abandonSuperseded)(z),"superseded")});if("why"in n){if(n.superseded){z+=1,console.log(`[parent] ${n.why} \u2014 abandoned; one fresh pod for the newest build instead (${z} in a row). Child#${s.id} keeps serving.`),t=!0;break}n.why!=="shutting down"&&console.error(`[parent] Child#${s.id} keeps serving the previous build \u2014 ${n.why}`);continue}z=0,console.log(`[parent] Child#${n.fresh.id} took over from Child#${s.id} with the new build (pid ${s.proc.pid} \u2192 ${n.fresh.proc.pid}, ready in ${(n.readyMs/1e3).toFixed(1)}s while Child#${s.id} served)`),y.publish((0,service_build_events_1.buildServiceSwapEvent)(W(n.fresh),{generation:1,swaps:0,swapMs:n.readyMs,draining:q.size,handoff:{fromPid:s.proc.pid??0}},X,{root:process.cwd()}))}catch(n){console.error(`[parent] Child#${s.id} keeps serving the previous build \u2014 could not start a successor: ${n?.message??String(n)}`)}finally{fe=!1}}}t&&(T=!0)}while(T&&!k)})().finally(()=>{N=void 0})}u(P,"N"),a(P,"handoffForReload");function ee(){const e=(0,swap_mode_1.maxRetiring)(),t=[...q].filter(s=>!D(s));for(;t.length>=e;){const s=t.shift();console.error(`[parent] Child#${s.id} (pid ${s.proc.pid}) was still finishing its work when a newer build replaced its successor too \u2014 stopping it (LENSMCP_SWAP_MAX_RETIRING=${e})`);try{s.proc.kill("SIGTERM")}catch{}}}u(ee,"J"),a(ee,"capRetiring");const G=[],Ue=new Map,qe=a(e=>{let t=Ue.get(e);return t||Ue.set(e,t={crashes:0,restarts:0}),t},"watchOf"),ze=(0,worker_supervisor_1.workerBackoff)(),Ae=a((e,t)=>({project:f,service:SERVICE_NAME||f,worker:e,pid:t,podGeneration:POD_GENERATION}),"workerWho"),ot=[path.join(__dirname,"worker-guard.js"),path.join(__dirname,"worker-guard.ts")].find(e=>fs.existsSync(e));for(const e of WORKER_PROBLEMS)console.error(`[parent] ${e}`);function Qe(e,t){const s=e.name,n=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH)),i=path.join(n,`${s}.js`),o=qe(s);if(!fs.existsSync(i))return console.error(`[parent] Worker "${s}" bundle not found: ${i}`),o.missing=i,y.publish((0,worker_supervisor_1.buildWorkerExitedEvent)(Ae(s,0),{ranMs:0,reason:`its bundle was not built (${path.basename(i)} is not in ${n})`})),null;o.missing=void 0;const m=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&m.unshift("--require","@swc-node/register"),ot&&m.push("--require",ot);try{m.push("--require",require.resolve("@lensmcp/node-instrumentation/register"))}catch{}const p=inspectorPortFor(I||9229,Ne+Math.max(0,WORKER_NAMES.indexOf(s)));m.push(I?`--inspect=127.0.0.1:${p}`:`--inspect-port=127.0.0.1:${p}`,...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const w=(0,node_child_process_1.fork)(i,{env:(0,worker_supervisor_1.workerEnv)(process.env,e),stdio:["inherit","pipe","pipe","ipc"],execArgv:m,execPath:we(`w-${s}`)}),A={name:s,spec:e,proc:w,debugPort:p,startedAt:Date.now(),tail:new exit_reason_1.TailBuffer,stopping:!1};G.push(A),w.on("error",O=>console.error(`[parent] Worker "${s}": ${O.message}`)),se(w,`\x1B[35m[worker:${s}] \x1B[0m`,O=>{A.tail.push(O);const Q=/Debugger listening on (wss?:\/\/\S+)/.exec(O);Q&&(A.inspectorUrl=Q[1])});const C=setTimeout(()=>{if(!(Re(A)||A.stopping)){if(o.crashes>0){const O=Date.now()-A.startedAt;console.log(`[parent] Worker "${s}" (pid=${w.pid}) is up again \u2014 ${(0,worker_supervisor_1.spanOf)(O)} without a crash, after ${o.crashes} in a row`),y.publish((0,worker_supervisor_1.buildWorkerUpEvent)(Ae(s,w.pid??0),{ranMs:O,afterCrashes:o.crashes}))}o.crashes=0}},ze.stableMs);return C.unref?.(),w.on("exit",(O,Q)=>{clearTimeout(C);const ke=G.indexOf(A);ke>=0&&G.splice(ke,1),nt(A,O,Q)}),console.log(`[parent] Worker "${s}" started (pid=${w.pid}, PORT=${(0,worker_supervisor_1.workerEnv)(process.env,e).PORT}${t==="respawn"?`, restart ${o.restarts}`:""})`),y.publish((0,worker_supervisor_1.buildWorkerStartedEvent)(Ae(s,w.pid??0),{why:t,port:e.port,restarts:o.restarts})),A}u(Qe,"et"),a(Qe,"spawnWorkerProcess");function nt(e,t,s){const{name:n}=e,i=e.proc.pid??0,o=Date.now()-e.startedAt,m=(0,worker_supervisor_1.workerExitVerdict)(t,s,e.stopping||k);if(m.kind==="stopped")return;const p=qe(n);if(m.kind==="exited"){p.lastEnd={at:Date.now(),pid:i,code:t,signal:s,ranMs:o,verdict:"exited"},console.warn(`[parent] Worker "${n}" (pid=${i}) exited on its own (code 0) after ${(0,worker_supervisor_1.spanOf)(o)} \u2014 not started again until the next build: a worker that ends is taken to have finished its work`),y.publish((0,worker_supervisor_1.buildWorkerExitedEvent)(Ae(n,i),{ranMs:o}));return}p.crashes+=1,p.lastEnd={at:Date.now(),pid:i,code:t,signal:s,ranMs:o,verdict:"crashed"};const w=(0,worker_supervisor_1.respawnDelay)(p.crashes,ze),A=p.crashes>=worker_supervisor_1.CRASH_LOOP_AFTER;console.error((0,exit_reason_1.crashReport)(`[parent] Worker "${n}" crashed (code=${t}, signal=${s??"none"}, pid=${i}, after ${(0,worker_supervisor_1.spanOf)(o)})${m.external?" \u2014 stopped by a signal from outside its devserver":""}; starting it again in ${(0,worker_supervisor_1.spanOf)(w)}${A?` \u2014 ${p.crashes} crashes in a row: it is crash-looping (the wait doubles, up to ${(0,worker_supervisor_1.spanOf)(ze.maxMs)})`:""}`,t,s,e.tail.snapshot())),y.publish((0,worker_supervisor_1.buildWorkerCrashedEvent)(Ae(n,i),{code:t,signal:s,ranMs:o,crashes:p.crashes,restarts:p.restarts,nextInMs:w,external:m.external,lines:e.tail.snapshot()})),clearTimeout(p.pending),p.nextAt=Date.now()+w,p.pending=setTimeout(()=>{p.pending=void 0,p.nextAt=void 0,!(k||G.some(C=>C.name===n))&&(p.restarts+=1,Be(e.spec,"respawn"))},w),p.pending.unref?.()}u(nt,"dt"),a(nt,"workerEnded");function Be(e,t){const s=qe(e.name);s.waiting=void 0;const n=e.port>0?[...te].find(o=>o.name===e.name&&!Re(o)):void 0;if(!n){Qe(e,t);return}console.log(`[parent] Worker "${e.name}" starts once its predecessor (pid=${n.proc.pid}) has finished its work \u2014 it holds port ${e.port}`);const i=a(()=>{s.waiting===i&&(s.waiting=void 0),!k&&!G.some(o=>o.name===e.name)&&Qe(e,t)},"go");s.waiting=i,n.proc.once("exit",i)}u(Be,"qe"),a(Be,"startWorker");const st=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(e)&&e>=0?e:15*6e4})(),it=(()=>{const e=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(e)&&e>=1?Math.floor(e):1})(),te=new Set,Re=a(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"workerExited");function je(e,t){if(te.delete(e),!Re(e)){console.error(`[parent] Worker "${e.name}" (pid=${e.proc.pid}) ${t} \u2014 killing it. A worker that returns from its SIGTERM handler but leaves a handle open (a Redis client handed to BullMQ is not closed by worker.close()) never exits on its own: close what it opened, or call process.exit().`);try{e.proc.kill("SIGKILL")}catch{}}}u(je,"Je"),a(je,"killDrainingWorker");function Ze(e){e.stopping=!0,tell(e.proc,{type:worker_retire_1.RETIRE_MESSAGE});try{e.proc.kill("SIGTERM")}catch{}if(Re(e))return;const t=[...te].filter(n=>n.name===e.name);for(;t.length>=it;)je(t.shift(),`was still running when a later reload replaced its successor (cap ${it})`);te.add(e);const s=setTimeout(()=>je(e,`was still running ${st}ms after SIGTERM`),st);s.unref?.(),e.proc.once("exit",()=>{clearTimeout(s),te.delete(e)})}u(Ze,"ot"),a(Ze,"retireWorker");function Ke(){for(const e of Ue.values())clearTimeout(e.pending),e.pending=void 0,e.nextAt=void 0,e.waiting=void 0}u(Ke,"Xe"),a(Ke,"cancelWorkerStarts");function at(){for(const e of[...G])Ze(e);G.length=0,Ke();for(const e of WORKER_SPECS)qe(e.name).crashes=0,Be(e,"reload")}u(at,"pt"),a(at,"restartWorkers");function ct(){const e=Date.now();return{workers:WORKER_SPECS.map(t=>{const s=G.find(o=>o.name===t.name),n=Ue.get(t.name),i=s?"running":n?.pending?(n.crashes??0)>=worker_supervisor_1.CRASH_LOOP_AFTER?"crash-looping":"restarting":n?.waiting?"waiting":n?.missing?"missing":n?.lastEnd?.verdict==="exited"?"exited":"stopped";return{name:t.name,state:i,port:t.port,env:Object.keys(t.env),...s?{pid:s.proc.pid,upMs:e-s.startedAt}:{},crashes:n?.crashes??0,restarts:n?.restarts??0,...n?.nextAt?{nextInMs:Math.max(0,n.nextAt-e)}:{},...n?.lastEnd?{lastEnd:n.lastEnd}:{},...n?.missing?{missing:n.missing}:{}}}),draining:[...te].filter(t=>!Re(t)).map(t=>({name:t.name,pid:t.proc.pid}))}}u(ct,"ut"),a(ct,"workersView");const _t=debounce(async()=>{ie+=1;const e=Y();if(e.length>0)if(Te==="process")P();else{console.log(`[parent] Forwarding reload to ${e.length} child(ren)`);for(const t of e)tell(t.proc,{type:"reload"})}await Me(),WORKER_NAMES.length>0&&at()},200),lt=a((e,t)=>{const s=(0,notice_generation_1.noticeGeneration)(e.headers);return s===void 0||s===POD_GENERATION?!1:(e.resume(),t.writeHead(409,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!1,generation:POD_GENERATION,sentFor:s})),e.url==="/webpack/reload"&&console.log(`[parent] a build of generation g${s} reached generation g${POD_GENERATION} \u2014 not reloaded: it is not this generation's build`),!0)},"refusedForAnotherGeneration"),Ce=a(async(e,t)=>{if(e.method==="POST"&&e.url==="/webpack/reload"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);if(lt(e,t))return;t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0})),de(e).then(i=>{const o=i;X=(0,service_build_events_1.buildAccountOf)(o?.build),ce=0,ve(o?.watcher)}),_t();return}if(e.method==="POST"&&e.url==="/webpack/watching"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);if(lt(e,t))return;const i=await de(e);ve(i),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,relayed:ae!==void 0}));return}if(e.method==="POST"&&e.url==="/webpack/scale"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);let i="";e.on("data",o=>{i+=o}),e.on("end",async()=>{let o=0;try{o=Number(JSON.parse(i||"{}").pods)||0}catch{}o=Math.max(1,Math.min(o,16)),await Se(o),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,pods:o}))});return}if(e.method==="GET"&&e.url?.startsWith("/webpack/logs")){const i=new URL(e.url,"http://localhost").searchParams,o=Math.min(Math.max(Number(i.get("tail")??"100")||0,0),Z),m=i.get("follow")!=="0",p=i.get("plain")==="1",w=!(0,devserver_transport_1.isOwnerOnlyTransport)(e);t.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-cache"});const A=o===0?"":V.slice(-o).join(""),C=p?A.replace(F,""):A;if(t.write(w?(0,inspector_secret_1.redactInspectorUrls)(C):C),!m){t.end();return}const O={res:t,plain:p,redact:w};oe.add(O),e.on("close",()=>oe.delete(O));return}if(e.method==="POST"&&e.url?.startsWith("/webpack/debug")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const i=Number(new URL(e.url,"http://localhost").searchParams.get("port")||"");Number.isInteger(i)&&i>1024&&(I=i),I||(I=9229);const o=S.filter(p=>p.proc.exitCode===null&&p.proc.signalCode===null);for(const p of o)p.debugSlot<0&&(p.debugSlot=x()),tell(p.proc,{type:"debug-open",port:inspectorPortFor(I,p.debugSlot)});for(const p of G)try{p.proc.kill("SIGUSR1")}catch{}const m=Date.now()+2e3;for(;Date.now()<m&&o.some(p=>!p.inspectorUrl);)await new Promise(p=>setTimeout(p,50));t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,basePort:I,fixedPorts:usesFixedInspectorPorts(),pods:o.map(p=>({id:p.id,inspectorUrl:p.inspectorUrl??null})),workers:G.map(p=>({name:p.name,port:p.debugPort||(0,inspector_secret_1.inspectorPortOf)(p.inspectorUrl),inspectorUrl:p.inspectorUrl??null}))},null,2)+`
16
+ `);return}if(e.method==="GET"&&e.url==="/webpack/workers"){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(ct(),null,2)+`
17
+ `);return}if(e.method==="GET"&&e.url==="/webpack/memory"){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const i=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),o=[...S,...q].map(m=>({id:m.id,pid:m.proc.pid??0,podGeneration:POD_GENERATION,healthy:m.healthy,retiring:q.has(m),latest:m.memory.latest??null,history:m.memory.history,retained:[...m.memory.retained.values()]}));t.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),t.end(JSON.stringify({ok:!0,service:SERVICE_NAME,project:f,bundle:{path:i},pods:o},null,2)+`
18
+ `);return}if(e.method==="POST"&&e.url?.startsWith("/webpack/heap")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const i=a((L,We)=>{t.writeHead(L,{"content-type":"application/json"}),t.end(JSON.stringify(We,null,2)+`
19
+ `)},"reply"),o=new URL(e.url,"http://localhost").searchParams,m=Number(o.get("pod")||""),p=o.has("maxMb")?Number(o.get("maxMb")):void 0;if(p!==void 0&&!(Number.isFinite(p)&&p>0)){i(400,{ok:!1,error:"maxMb takes a positive number of MB"});return}const w=Number.isInteger(m)&&m>0?S.find(L=>L.id===m):Y()[0];if(!w||D(w)){i(404,{ok:!1,error:m?`no pod #${m} \u2014 running: ${S.map(L=>`#${L.id}`).join(", ")||"none"}`:"no pod is serving"});return}if(Pe.size>0){i(409,{ok:!1,refused:"a heap snapshot is already being written for this service"});return}const A=(0,heap_snapshot_1.heapSnapshotPolicy)(),C=(0,heap_snapshot_1.heapSnapshotDir)();let O;try{(0,heap_snapshot_1.ensureHeapDir)(C);const L=(0,heap_snapshot_1.pruneHeapSnapshots)(C,A);L.length&&console.log(`[parent] removed ${L.length} older heap snapshot(s) from ${C}`),O=path.join(C,(0,heap_snapshot_1.heapSnapshotFileName)(SERVICE_NAME||f,w.id,w.proc.pid??0,w.memory.latest?.gen??0,Date.now()))}catch(L){i(500,{ok:!1,error:`cannot prepare ${C}: ${L.message}`});return}const Q=++he,ke=(0,heap_snapshot_1.availableSystemMemory)();let Le;const R=await new Promise(L=>{const We=setTimeout(()=>L(void 0),6e5);We.unref?.(),Pe.set(Q,vt=>{clearTimeout(We),L(vt)}),Le=a(()=>{clearTimeout(We),L(void 0)},"onExit"),w.proc.once("exit",Le);const yt={type:"heap-snapshot",id:Q,file:O,...ke?{available:ke}:{},...p!==void 0?{maxHeapBytes:Math.floor(p*1048576)}:{}};tell(w.proc,yt)||Le()}).finally(()=>{Pe.delete(Q),Le&&w.proc.off("exit",Le)});if(!R){i(504,{ok:!1,pod:w.id,error:"the pod did not finish the snapshot (it exited, or took longer than 10 minutes)"});return}R.ok?console.log(`[parent] Child#${w.id} wrote a ${Math.round((R.bytes??0)/1048576)} MB heap snapshot in ${R.ms} ms \u2192 ${R.file}`):console.warn(`[parent] Child#${w.id} heap snapshot not taken: ${R.refused??R.error}`),i(R.ok?200:R.refused?409:500,{ok:R.ok,pod:w.id,pid:w.proc.pid??0,service:SERVICE_NAME,bundle:path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),...ke?{available:ke}:{},...R.file?{file:R.file,bytes:R.bytes,ms:R.ms}:{},...R.live!==void 0?{live:R.live}:{},...R.gen!==void 0?{gen:R.gen,closedAlive:R.closedAlive??[]}:{},...R.refused?{refused:R.refused}:{},...R.error?{error:R.error}:{}});return}const s=matchGatewayRoute(e);if(s?.prependPrefix&&!e.url?.startsWith(s.prependPrefix)&&(e.url=s.prependPrefix+(e.url??"/")),s?.target){applyGatewayMiddleware(e),g.web(e,t,{target:s.target,autoRewrite:typeof s.target=="string",changeOrigin:!0},i=>{console.error(`[parent] proxy error to ${s.target}:`,i),t.statusCode=502,t.setHeader("content-type","text/plain; charset=utf-8"),t.end(`Upstream error from ${s.target}.`)});return}if(SERVICE_PREFIX){if(!e.url?.startsWith(SERVICE_PREFIX)){t.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),t.end(`Not found. This service is mounted at ${SERVICE_PREFIX}/`);return}e.url=e.url.slice(SERVICE_PREFIX.length)||"/"}applyGatewayMiddleware(e);const n=pe();if(!n){t.statusCode=503,t.setHeader("content-type","text/plain; charset=utf-8");const i=S.map(o=>`#${o.id}: ${o.lastError??"no error recorded"}`).join(`
20
20
  `);t.end(`No healthy children available. POST /webpack/reload to recover.
21
21
 
22
22
  Last errors:
23
23
  ${i}`);return}g.web(e,t,{target:{socketPath:n.socketPath},headers:{"x-proxy-child-id":String(n.id)}},i=>{console.error(`[parent] proxy error to Child#${n.id}:`,i),n.healthy=!1,n.lastError=String(i?.stack||i),t.statusCode=502,t.setHeader("content-type","text/plain; charset=utf-8"),t.end(`Upstream error from Child#${n.id}. Try /webpack/reload.
24
- ${n.lastError}`)})},"requestHandler");let _e,Ie,Ze;const xe=[];if(GATEWAY_HTTPS){const e=require("./basic-ssl"),t=GATEWAY_ROUTES.map(n=>n.host).filter(n=>!!n),s=(0,checkout_cache_1.checkoutCacheDir)(process.cwd(),"davnx-webpack");Ie=e.getCertificateSync(s,SERVICE_NAME||"lensmcp.dev",t),Ze=e.caCertPath(),_e=require("node:https").createServer({key:Ie,cert:Ie},Ce)}else _e=http.createServer(Ce);const ct=a((e,t,s)=>{const n=matchGatewayRoute(e);if(n?.prependPrefix&&!e.url?.startsWith(n.prependPrefix)&&(e.url=n.prependPrefix+(e.url??"/")),n?.target){g.ws(e,t,s,{target:n.target,changeOrigin:!0},()=>t.destroy());return}const i=pe();if(!i){t.destroy();return}g.ws(e,t,s,{target:{socketPath:i.socketPath}},()=>t.destroy())},"upgradeHandler");_e.on("upgrade",ct);const lt=2e3;let dt=!1;_e.on("error",e=>{if(e.code==="EADDRINUSE"){dt||(dt=!0,console.warn(`[parent] public port ${b} already in use \u2014 continuing on the unix-socket pool only (gateway routing is unaffected) and retrying the bind every ${lt/1e3}s. Give this service a distinct cluster.port if this is not a rolling handoff.`)),setTimeout(()=>{!k&&!_e.listening&&_e.listen(b)},lt).unref?.();return}console.error("[parent] public server error:",e)}),await Se(ge);for(const e of WORKER_SPECS)Ue(e,"boot");SOCKET_ONLY?console.log(`[parent] socket-only: no TCP listener (port ${b} is not bound \u2014 the gateway reaches this service through its socket pool)`):_e.listen(b,()=>{const e=GATEWAY_HTTPS?"https":"http";console.log(`[parent] Listening on ${e}://localhost:${b}`),SERVICE_PREFIX&&console.log(`[parent] Service prefix: "${SERVICE_PREFIX}" (enforced \u2014 requests without it will get 404)`),gatewayMiddleware&&console.log(`[parent] Gateway middleware: ACTIVE (${GATEWAY_MIDDLEWARE_PATH})`),GATEWAY_ROUTES.length>0&&console.log(`[parent] Gateway routes: ${GATEWAY_ROUTES.map(t=>`${t.host??"*"}${t.prefix??"/"}\u2192${t.target??"children"}`).join(" ")}`),Ze&&(console.log("[parent] HTTPS dev CA (trust ONCE, then rotations/new hostnames stay green):"),console.log(`[parent] sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${Ze}`)),console.log(`POST ${e}://localhost:${b}/webpack/reload to trigger rolling swap/respawn`)});const Ke=Number(process.env.INTERNAL_PORT||0);if(Ke>0&&!SOCKET_ONLY){const e=a((s,n)=>{const i=pe();if(!i){n.statusCode=503,n.setHeader("content-type","text/plain; charset=utf-8"),n.end("No healthy children available.");return}g.web(s,n,{target:{socketPath:i.socketPath}},o=>{i.healthy=!1,i.lastError=String(o?.stack||o),n.statusCode=502,n.end(`Upstream error from Child#${i.id}.`)})},"internalHandler"),t=http.createServer(e);t.on("upgrade",(s,n,i)=>{const o=pe();if(!o){n.destroy();return}g.ws(s,n,i,{target:{socketPath:o.socketPath}},()=>n.destroy())}),t.on("error",s=>{console.warn(`[parent] internal port ${Ke} unavailable (${s.code}).`)}),t.listen(Ke,()=>{console.log(`[parent] Internal (service-to-service, no gateway middleware) on http://localhost:${Ke}`)}),xe.push(t)}const ft=SOCKET_ONLY?[]:(()=>{try{return JSON.parse(process.env.GATEWAY_EXTRA_PORTS||"[]")}catch{return[]}})();for(const e of ft){if(!Number.isInteger(e)||e===Number(b))continue;const t=GATEWAY_HTTPS?require("node:https").createServer({key:Ie,cert:Ie},Ce):http.createServer(Ce);t.on("upgrade",ct),t.on("error",s=>{console.warn(`[parent] extra port ${e} unavailable (${s.code}) \u2014 main port still up.`)}),t.listen(e,()=>{console.log(`[parent] Also listening on ${GATEWAY_HTTPS?"https":"http"}://localhost:${e}`)}),xe.push(t)}const Ne=path.join(SOCK_DIR,"parent.sock");claimSock(Ne),(0,handoff_retire_1.clearHandoffRetire)(SOCK_DIR,POD_GENERATION);const De=http.createServer(Ce);De.on("error",e=>{console.warn(`[parent] control socket unavailable (${e.code}) \u2014 lensmcp logs/debug attach disabled.`)}),De.listen(Ne),xe.push(De);function pt(){k=!0;const e=[...S,...U];console.log(`[SIGTERM] [parent] generation g${POD_GENERATION} was handed over to a newer one \u2014 ${e.length} pod(s) finish their in-flight work, then it exits`);const t=sockOwnedByAnother(Ne);cleanupSock(Ne);for(const i of xe)if(!(i===De&&t))try{i.close()}catch{}try{_e.close()}catch{}je();for(const i of[...G])Qe(i);G.length=0;for(const i of S)if(!tell(i.proc,{type:"retire"}))try{i.proc.kill("SIGTERM")}catch{}const s=setTimeout(()=>{for(const i of e)if(!D(i)){console.error(`[parent] Child#${i.id} was still running ${l}ms after its generation was retired \u2014 killing it`);try{i.proc.kill("SIGKILL")}catch{}}},l);s.unref?.();const n=a(()=>{if(!(e.some(i=>!D(i))||[...te].some(i=>!Re(i)))){clearTimeout(s);for(const i of e)i.socketPath&&cleanupSock(i.socketPath,i.proc.pid);(0,handoff_retire_1.clearHandoffRetire)(SOCK_DIR,POD_GENERATION);try{fs.rmdirSync(SOCK_DIR)}catch{}console.log(`[parent] generation g${POD_GENERATION} retired`),process.exit(0)}},"finish");for(const i of e)i.proc.once("exit",n);for(const i of te)i.proc.once("exit",n);n()}u(pt,"ht"),a(pt,"retireGeneration");const ut=a(async e=>{k=!0,console.log(`[${e}] [parent] shutting down\u2026`);const t=sockOwnedByAnother(Ne);cleanupSock(Ne);for(const n of xe)if(!(n===De&&t))try{n.close()}catch{}je();for(const n of G){n.stopping=!0;try{n.proc.kill("SIGTERM")}catch{}}for(const n of WORKER_SPECS){const i=G.find(o=>o.name===n.name)?.proc.pid??0;m.publish((0,worker_supervisor_1.buildWorkerStoppedEvent)(Ae(n.name,i),{reason:`its devserver stopped (${e})`}))}for(const n of[...te])Be(n,"was still draining when its devserver shut down");for(const n of U)try{n.proc.kill("SIGTERM")}catch{}for(const n of S){try{n.proc.kill("SIGTERM")}catch{}n.socketPath&&cleanupSock(n.socketPath,n.proc.pid)}try{fs.rmdirSync(SOCK_DIR)}catch{}const s=(0,devserver_host_1.devserverStopExitCode)(e);setTimeout(()=>process.exit(s),700).unref()},"shutdown");let et=0;const _t=2e3;["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(e=>process.on(e,()=>{if(e==="SIGTERM"){if(!k&&(0,handoff_retire_1.handoffRetireRequested)(SOCK_DIR,POD_GENERATION)){et=Date.now(),pt();return}if(et>0&&Date.now()-et<_t)return}ut(e)}));const Ye=Number(process.env.LENSMCP_GATEWAY_PID??0);if(Number.isInteger(Ye)&&Ye>0){const e=setInterval(()=>{try{process.kill(Ye,0)}catch(t){if(t.code==="EPERM")return;clearInterval(e),console.error(`[parent] gateway (pid ${Ye}) is gone \u2014 shutting the pod down to avoid an orphan tree.`),ut("gateway-gone")}},5e3);e.unref()}})()}
24
+ ${n.lastError}`)})},"requestHandler");let _e,Ie,et;const xe=[];if(GATEWAY_HTTPS){const e=require("./basic-ssl"),t=GATEWAY_ROUTES.map(n=>n.host).filter(n=>!!n),s=(0,checkout_cache_1.checkoutCacheDir)(process.cwd(),"davnx-webpack");Ie=e.getCertificateSync(s,SERVICE_NAME||"lensmcp.dev",t),et=e.caCertPath(),_e=require("node:https").createServer({key:Ie,cert:Ie},Ce)}else _e=http.createServer(Ce);const dt=a((e,t,s)=>{const n=matchGatewayRoute(e);if(n?.prependPrefix&&!e.url?.startsWith(n.prependPrefix)&&(e.url=n.prependPrefix+(e.url??"/")),n?.target){g.ws(e,t,s,{target:n.target,changeOrigin:!0},()=>t.destroy());return}const i=pe();if(!i){t.destroy();return}g.ws(e,t,s,{target:{socketPath:i.socketPath}},()=>t.destroy())},"upgradeHandler");_e.on("upgrade",dt);const Ye=2e3;let pt=!1;_e.on("error",e=>{if(e.code==="EADDRINUSE"){pt||(pt=!0,console.warn(`[parent] public port ${b} already in use \u2014 continuing on the unix-socket pool only (gateway routing is unaffected) and retrying the bind every ${Ye/1e3}s. Give this service a distinct cluster.port if this is not a rolling handoff.`)),setTimeout(()=>{!k&&!_e.listening&&_e.listen(b)},Ye).unref?.();return}console.error("[parent] public server error:",e)});const ut=(()=>{const e=process.env.LENSMCP_PORT_CLASH_FAULT_MS,t=Number(e);return e!==void 0&&e!==""&&Number.isFinite(t)&&t>=0?t:12e4})(),gt=a(e=>e>=6e4?`${Math.round(e/6e3)/10} min`:`${Math.round(e/100)/10}s`,"spokenMs");function tt(e,t,s,n,i,o){let m=0,p=!1;e.on("error",w=>{if(w.code!=="EADDRINUSE"){i(w);return}k||(m===0&&(m=Date.now(),console.warn(`[parent] ${s} ${t} is held \u2014 by the generation before this one during a rolling handoff, or by another process \u2014 retrying the bind every ${Ye/1e3}s`)),!p&&Date.now()-m>=ut&&(p=!0,console.warn(`[parent] ${s} ${t} still unavailable (EADDRINUSE) after ${gt(ut)} \u2014 another process holds it; ${n}, not this service`)),setTimeout(()=>{!k&&!e.listening&&e.listen(t)},Ye).unref?.())}),e.listen(t,o)}u(tt,"ct"),a(tt,"listenRetrying"),await Se(ge);for(const e of WORKER_SPECS)Be(e,"boot");SOCKET_ONLY?console.log(`[parent] socket-only: no TCP listener (port ${b} is not bound \u2014 the gateway reaches this service through its socket pool)`):_e.listen(b,()=>{const e=GATEWAY_HTTPS?"https":"http";console.log(`[parent] Listening on ${e}://localhost:${b}`),SERVICE_PREFIX&&console.log(`[parent] Service prefix: "${SERVICE_PREFIX}" (enforced \u2014 requests without it will get 404)`),gatewayMiddleware&&console.log(`[parent] Gateway middleware: ACTIVE (${GATEWAY_MIDDLEWARE_PATH})`),GATEWAY_ROUTES.length>0&&console.log(`[parent] Gateway routes: ${GATEWAY_ROUTES.map(t=>`${t.host??"*"}${t.prefix??"/"}\u2192${t.target??"children"}`).join(" ")}`),et&&(console.log("[parent] HTTPS dev CA (trust ONCE, then rotations/new hostnames stay green):"),console.log(`[parent] sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${et}`)),console.log(`POST ${e}://localhost:${b}/webpack/reload to trigger rolling swap/respawn`)});const De=Number(process.env.INTERNAL_PORT||0);if(De>0&&!SOCKET_ONLY){const e=a((s,n)=>{const i=pe();if(!i){n.statusCode=503,n.setHeader("content-type","text/plain; charset=utf-8"),n.end("No healthy children available.");return}g.web(s,n,{target:{socketPath:i.socketPath}},o=>{i.healthy=!1,i.lastError=String(o?.stack||o),n.statusCode=502,n.end(`Upstream error from Child#${i.id}.`)})},"internalHandler"),t=http.createServer(e);t.on("upgrade",(s,n,i)=>{const o=pe();if(!o){n.destroy();return}g.ws(s,n,i,{target:{socketPath:o.socketPath}},()=>n.destroy())}),tt(t,De,"internal port",`peers calling localhost:${De} reach it`,s=>{console.warn(`[parent] internal port ${De} unavailable (${s.code}).`)},()=>{console.log(`[parent] Internal (service-to-service, no gateway middleware) on http://localhost:${De}`)}),xe.push(t)}const wt=SOCKET_ONLY?[]:(()=>{try{return JSON.parse(process.env.GATEWAY_EXTRA_PORTS||"[]")}catch{return[]}})();for(const e of wt){if(!Number.isInteger(e)||e===Number(b))continue;const t=GATEWAY_HTTPS?require("node:https").createServer({key:Ie,cert:Ie},Ce):http.createServer(Ce);t.on("upgrade",dt);const s=GATEWAY_HTTPS?"https":"http";tt(t,e,"extra port",`${s}://localhost:${e} reaches it`,n=>{console.warn(`[parent] extra port ${e} unavailable (${n.code}) \u2014 main port still up.`)},()=>{console.log(`[parent] Also listening on ${s}://localhost:${e}`)}),xe.push(t)}const $e=path.join(SOCK_DIR,"parent.sock");claimSock($e),(0,handoff_retire_1.clearHandoffRetire)(SOCK_DIR,POD_GENERATION);const Ge=http.createServer(Ce);Ge.on("error",e=>{console.warn(`[parent] control socket unavailable (${e.code}) \u2014 lensmcp logs/debug attach disabled.`)}),Ge.listen($e),xe.push(Ge);function ht(){k=!0;const e=[...S,...q];console.log(`[SIGTERM] [parent] generation g${POD_GENERATION} was handed over to a newer one \u2014 ${e.length} pod(s) finish their in-flight work, then it exits`);const t=sockOwnedByAnother($e);cleanupSock($e);for(const i of xe)if(!(i===Ge&&t))try{i.close()}catch{}try{_e.close()}catch{}Ke();for(const i of[...G])Ze(i);G.length=0;for(const i of S)if(!tell(i.proc,{type:"retire"}))try{i.proc.kill("SIGTERM")}catch{}const s=setTimeout(()=>{for(const i of e)if(!D(i)){console.error(`[parent] Child#${i.id} was still running ${l}ms after its generation was retired \u2014 killing it`);try{i.proc.kill("SIGKILL")}catch{}}},l);s.unref?.();const n=a(()=>{if(!(e.some(i=>!D(i))||[...te].some(i=>!Re(i)))){clearTimeout(s);for(const i of e)i.socketPath&&cleanupSock(i.socketPath,i.proc.pid);(0,handoff_retire_1.clearHandoffRetire)(SOCK_DIR,POD_GENERATION);try{fs.rmdirSync(SOCK_DIR)}catch{}console.log(`[parent] generation g${POD_GENERATION} retired`),process.exit(0)}},"finish");for(const i of e)i.proc.once("exit",n);for(const i of te)i.proc.once("exit",n);n()}u(ht,"wt"),a(ht,"retireGeneration");const ft=a(async e=>{k=!0,console.log(`[${e}] [parent] shutting down\u2026`);const t=sockOwnedByAnother($e);cleanupSock($e);for(const n of xe)if(!(n===Ge&&t))try{n.close()}catch{}Ke();for(const n of G){n.stopping=!0;try{n.proc.kill("SIGTERM")}catch{}}for(const n of WORKER_SPECS){const i=G.find(o=>o.name===n.name)?.proc.pid??0;y.publish((0,worker_supervisor_1.buildWorkerStoppedEvent)(Ae(n.name,i),{reason:`its devserver stopped (${e})`}))}for(const n of[...te])je(n,"was still draining when its devserver shut down");for(const n of q)try{n.proc.kill("SIGTERM")}catch{}for(const n of S){try{n.proc.kill("SIGTERM")}catch{}n.socketPath&&cleanupSock(n.socketPath,n.proc.pid)}try{fs.rmdirSync(SOCK_DIR)}catch{}const s=(0,devserver_host_1.devserverStopExitCode)(e);setTimeout(()=>process.exit(s),700).unref()},"shutdown");let rt=0;const mt=2e3;["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(e=>process.on(e,()=>{if(e==="SIGTERM"){if(!k&&(0,handoff_retire_1.handoffRetireRequested)(SOCK_DIR,POD_GENERATION)){rt=Date.now(),ht();return}if(rt>0&&Date.now()-rt<mt)return}ft(e)}));const Ve=Number(process.env.LENSMCP_GATEWAY_PID??0);if(Number.isInteger(Ve)&&Ve>0){const e=setInterval(()=>{try{process.kill(Ve,0)}catch(t){if(t.code==="EPERM")return;clearInterval(e),console.error(`[parent] gateway (pid ${Ve}) is gone \u2014 shutting the pod down to avoid an orphan tree.`),ft("gateway-gone")}},5e3);e.unref()}})()}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lensmcp/cluster",
3
- "version": "1.26.2",
3
+ "version": "1.26.3",
4
4
  "description": "Run your Nx workspace as a local production cluster: pods on unix sockets with true HMR, one https gateway with per-project domains, scale-from-zero, autoscale, idle-kill, local-CA TLS — observed by the LensMCP lens.",
5
5
  "main": "./index.js",
6
6
  "types": "./index.d.ts",
@@ -32,10 +32,10 @@
32
32
  "typescript": ">=5.0.0"
33
33
  },
34
34
  "dependencies": {
35
- "@lensmcp/core": "1.26.2",
36
- "@lensmcp/node-instrumentation": "1.26.2",
37
- "@lensmcp/nx-plugin": "1.26.2",
38
- "ringwall": "1.0.0",
35
+ "@lensmcp/core": "1.26.3",
36
+ "@lensmcp/node-instrumentation": "1.26.3",
37
+ "@lensmcp/nx-plugin": "1.26.3",
38
+ "ringwall": "1.0.1",
39
39
  "@typescript/native-preview": "^7.0.0-dev.20260707.2",
40
40
  "fork-ts-checker-webpack-plugin": "^9.0.0",
41
41
  "http-proxy": "^1.18.0",
@@ -0,0 +1,4 @@
1
+ export type ProgramRoute = 'tsgo-shim' | 'tsgo' | 'none';
2
+ export declare function programId(tsconfig: string, route: ProgramRoute, flags?: readonly string[], pinsOnly?: boolean): string;
3
+ /** The id of a typecheck command LensMCP can read no tsconfig from: its Nx target and what it runs. */
4
+ export declare function commandId(target: string, command: string): string;
package/program-id.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var d=Object.defineProperty;var o=(e,r)=>d(e,"name",{value:r,configurable:!0});var s=Object.defineProperty,t=o((e,r)=>s(e,"name",{value:r,configurable:!0}),"t");Object.defineProperty(exports,"__esModule",{value:!0}),exports.programId=programId,exports.commandId=commandId;const node_crypto_1=require("node:crypto");function programId(e,r,n=[],a=!1){return`tc_${(0,node_crypto_1.createHash)("sha256").update(JSON.stringify([e,r,[...n],...a?["pins"]:[]])).digest("hex").slice(0,12)}`}o(programId,"programId"),t(programId,"programId");function commandId(e,r){return programId("","none",[e,r])}o(commandId,"commandId"),t(commandId,"commandId");
@@ -1,4 +1,4 @@
1
- import type { HostOutbound, MemberJoinRequest } from './protocol';
1
+ import { type HostOutbound, type MemberJoinRequest } from './protocol';
2
2
  /** How long a project with no member keeps its entries — a recycle that kills then respawns does not drop them. */
3
3
  export declare const DEFAULT_PAUSE_MS = 5000;
4
4
  type WebpackFactory = (config: Record<string, any>) => any;
@@ -13,7 +13,38 @@ export interface BuildHostOptions {
13
13
  pauseMs?: number;
14
14
  /** The waits before compiling again after the compiler failed outright. Default {@link RETRY_AFTER_FAILURE_MS}. */
15
15
  retryDelaysMs?: readonly number[];
16
+ /** How often held projects are reported on (at most), and a suspended watcher's collected saves read. Default {@link HELD_REPORT_MS}. */
17
+ heldReportMs?: number;
16
18
  }
19
+ /** The parts of webpack's `Watching` (lib/Watching.js, 5.107) a hold drives and reads. */
20
+ interface WatchingLike {
21
+ suspended: boolean;
22
+ running: boolean;
23
+ /** A save came while it compiled: it compiles again when this one ends. */
24
+ invalid?: boolean;
25
+ closed?: boolean;
26
+ watcher?: WatcherLike | null;
27
+ pausedWatcher?: WatcherLike | null;
28
+ _collectedChangedFiles?: Set<string>;
29
+ _collectedRemovedFiles?: Set<string>;
30
+ suspend(): void;
31
+ resume(): void;
32
+ invalidate(): void;
33
+ }
34
+ interface WatcherLike {
35
+ getInfo?: () => {
36
+ changes?: Iterable<string> | null;
37
+ removals?: Iterable<string> | null;
38
+ };
39
+ }
40
+ /**
41
+ * The files a suspended watcher holds back — what `resume()` will compile (webpack 5.107 lib/Watching.js). The first
42
+ * batch of saves after `suspend()` is merged into `_collectedChangedFiles`/`_collectedRemovedFiles` (`_invalidate`,
43
+ * :439-442); the watcher then pauses (NodeWatchFileSystem's `aggregated` handler), and every later save lands only in
44
+ * watchpack's aggregated sets, which the watcher's `getInfo()` reads without clearing them — as `_go` does when the
45
+ * compile starts (:139-149). Read once per {@link HELD_REPORT_MS} while a group is suspended, never on a hot path.
46
+ */
47
+ export declare function suspendedChanges(watching: WatchingLike): Set<string>;
17
48
  /** Run `fn` with `process.env` replaced by `env` — synchronously, and restored whatever happens. */
18
49
  export declare function withEnv<T>(env: Record<string, string | undefined>, fn: () => T): T;
19
50
  /** `<project>:<target>[:<configuration>]` — what NxAppWebpackPlugin reads from `NX_BUILD_TARGET`. */
@@ -26,8 +57,64 @@ export declare class BuildHost {
26
57
  private readonly pauseMs;
27
58
  private readonly webpack;
28
59
  private stopped;
60
+ /** project → its hold (planning/updates/00-plan.md U1b). */
61
+ private readonly holds;
62
+ /** Members told at least one build — a hold never keeps a member from its first. Kept when a member moves group. */
63
+ private readonly served;
64
+ private readonly heldReportMs;
65
+ /** While anything is held: reads suspended watchers' saves, and sends the reports that changed. */
66
+ private ticker;
29
67
  constructor(opts: BuildHostOptions);
30
68
  private tell;
69
+ /**
70
+ * Hold a project's builds, or release them. Idempotent. A hold taken while a compile runs applies from the compile's
71
+ * emit on (the decision is made once per compilation, as its assets are processed); a release delivers what is owed —
72
+ * the bundle its last compile built and kept back, or the saves a suspended watcher collected for it — with one
73
+ * compile, and a release with nothing owed compiles nothing and tells nobody anything.
74
+ */
75
+ hold(project: string, held: boolean): void;
76
+ /** Deliver a held project's current sources once, and keep holding it. Nothing owed: nothing compiles. */
77
+ update(project: string): void;
78
+ private groupsOf;
79
+ /** The hash of the build a project's members were last told about, in any group. */
80
+ private deliveredHash;
81
+ /**
82
+ * Does a held project have a build to deliver: one its last compile made and kept back (its hash is not the delivered
83
+ * one), or saves of its files a suspended watcher holds? In a compile that is running and has not emitted yet, the
84
+ * release or update is taken by that compile's emit instead ({@link withheldNow} reads `deliver`): asked then, it is
85
+ * owed when that compile changed something for it.
86
+ */
87
+ private owes;
88
+ /** Is this project's build kept back from the compilation being emitted now? */
89
+ private withholds;
90
+ private withheldNow;
91
+ /** A held project whose next build must be delivered: an update or release asked, or a member was never told one. */
92
+ private owedDelivery;
93
+ /** Every project of the group is held — and a compilation has finished, so a watcher collects the saves. */
94
+ private everyHeld;
95
+ /**
96
+ * Fit the group's watcher to its holds. Webpack's `resume()` always compiles (`_invalidate()`, lib/Watching.js
97
+ * :461-466), so it is called only when a compile is owed: a delivery, a save a live project's bundle is built from,
98
+ * or `compile` (a join, a pause, a retry) while not every project is held. With nothing collected, the watcher is let
99
+ * go by its flag alone — it never stopped watching. A compile owed while every project stays held is `resume()` then
100
+ * `suspend()` at once: that compile runs to its end, delivers, and the saves after it are collected again.
101
+ */
102
+ private settle;
103
+ /** Settle once webpack is idle ({@link afterBuild}) — keeping a compile asked for. */
104
+ private defer;
105
+ /** webpack is compiling, or storing what it compiled. */
106
+ private busy;
107
+ /** Did a suspended watcher collect a save a project that is NOT held is built from — or one no bundle is built from yet? */
108
+ private liveChanged;
109
+ /** Add a changed file to a held project's list — moved to the end when it is there already. */
110
+ private collect;
111
+ private startTicker;
112
+ /**
113
+ * Once per {@link HELD_REPORT_MS} while anything is held: a suspended group's collected saves are attributed to the
114
+ * held projects they belong to (a round with new ones is a build each was spared), a group that collected a live
115
+ * project's save compiles, and every held project whose report changed is reported.
116
+ */
117
+ private tick;
31
118
  /** The projects each group compiles — for the spec and the gateway's status line. */
32
119
  describe(): Array<{
33
120
  group: string;
@@ -35,7 +122,10 @@ export declare class BuildHost {
35
122
  }>;
36
123
  /** Build a member's config the way the shared compilation will, and its signature. Throws what the config throws. */
37
124
  private evaluate;
38
- join(member: string, join: MemberJoinRequest): void;
125
+ /** `served`: the member already runs a build the gateway relayed it (it joins again a host that restarted — protocol.ts). */
126
+ join(member: string, join: MemberJoinRequest, opts?: {
127
+ served?: boolean;
128
+ }): void;
39
129
  /** Put an evaluated member into the group of its signature — a new group when none has it. */
40
130
  private admit;
41
131
  leave(member: string, opts?: {
@@ -52,7 +142,17 @@ export declare class BuildHost {
52
142
  * (with what changed meanwhile) watches again (compile-retry.ts, issues/closed/foodguard-91).
53
143
  */
54
144
  private compileAgain;
145
+ /** A build ended and webpack stored its cache: what the holds asked for meanwhile, and what they ask for now. */
146
+ private afterBuild;
55
147
  private onBuild;
148
+ /** file → the projects whose bundles a compilation built from it; a config file is every project's. */
149
+ private ownersOf;
150
+ /** A compilation built a held project and kept it back: the files of it that changed, and a build it was not given. */
151
+ private keptBack;
152
+ /** The files a delivery to a held project carries: what it held, and what this compilation changed of it. */
153
+ private carried;
154
+ /** A held or released project was told its build: a release is live from now on; a hold starts collecting again. */
155
+ private delivered;
56
156
  /**
57
157
  * A file the group's configs were read from changed (config-files.ts): every member is evaluated again, and one
58
158
  * whose signature changed — a `paths` alias added or retargeted, an emit option, its override — leaves for the group