@lensmcp/cluster 1.24.2 → 1.24.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/main.devserver.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Ve=Object.defineProperty;var f=(i,h)=>Ve(i,"name",{value:h,configurable:!0});var Ke=Object.defineProperty,n=f((i,h)=>Ke(i,"name",{value:h,configurable:!0}),"n");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")),exit_reason_1=require("./exit-reason"),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:n(function(){return inspector_secret_1.inspectorPortOf},"get")}),Object.defineProperty(exports,"redactInspectorUrls",{enumerable:!0,get:n(function(){return inspector_secret_1.redactInspectorUrls},"get")});const devserver_transport_1=require("./devserver-transport");Object.defineProperty(exports,"gatewayManaged",{enumerable:!0,get:n(function(){return devserver_transport_1.gatewayManaged},"get")}),Object.defineProperty(exports,"isOwnerOnlyTransport",{enumerable:!0,get:n(function(){return devserver_transport_1.isOwnerOnlyTransport},"get")}),Object.defineProperty(exports,"mayDriveThePool",{enumerable:!0,get:n(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"),stdio_guard_1=require("./stdio-guard"),bundle_parent_1=require("./bundle-parent"),checkout_cache_1=require("./checkout-cache"),dev_devtool_1=require("./dev-devtool"),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 i=process.env.GATEWAY_CONFIG;if(!i)return{};try{return JSON.parse(i)}catch{return{}}})();let gatewayMiddleware=null;if(GATEWAY_MIDDLEWARE_PATH)try{const i=require(GATEWAY_MIDDLEWARE_PATH);gatewayMiddleware=typeof i=="function"?i:typeof i.default=="function"?i.default:null,gatewayMiddleware||console.warn(`[gateway] ${GATEWAY_MIDDLEWARE_PATH} does not export a function, gateway disabled`)}catch(i){console.error(`[gateway] Failed to load middleware from ${GATEWAY_MIDDLEWARE_PATH}:`,i)}function applyGatewayMiddleware(i){if(gatewayMiddleware)try{gatewayMiddleware(i,GATEWAY_CONFIG)}catch(h){console.error("[gateway] Middleware error:",h)}}f(applyGatewayMiddleware,"applyGatewayMiddleware"),n(applyGatewayMiddleware,"applyGatewayMiddleware");const GATEWAY_ROUTES=(()=>{try{return JSON.parse(process.env.GATEWAY_ROUTES||"[]")}catch{return[]}})(),GATEWAY_HTTPS=process.env.GATEWAY_HTTPS==="1";function hostMatches(i,h){if(i.startsWith("*.")){const y=i.slice(1);return h.endsWith(y)||h===i.slice(2)}return h===i}f(hostMatches,"hostMatches"),n(hostMatches,"hostMatches");function matchGatewayRoute(i){if(GATEWAY_ROUTES.length===0)return;const h=(i.headers.host||"").split(":")[0],y=i.url||"/";for(const S of GATEWAY_ROUTES)if(!(S.host&&!hostMatches(S.host,h))&&!(S.prefix&&!y.startsWith(S.prefix)))return S}f(matchGatewayRoute,"matchGatewayRoute"),n(matchGatewayRoute,"matchGatewayRoute");const WORKER_NAMES=(()=>{try{return JSON.parse(process.env.WORKERS||"[]")}catch{return[]}})(),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 i=Number(process.env.LENSMCP_POD_GENERATION);return Number.isFinite(i)&&i>1?Math.floor(i):1})();function childSockPath(i){return path.join(SOCK_DIR,POD_GENERATION>1?`child-${i}-g${POD_GENERATION}.sock`:`child-${i}.sock`)}f(childSockPath,"childSockPath"),n(childSockPath,"childSockPath");function sockOwnerPath(i){return`${i}.owner`}f(sockOwnerPath,"sockOwnerPath"),n(sockOwnerPath,"sockOwnerPath");function sockRetiringPath(i){return`${i}.retiring`}f(sockRetiringPath,"sockRetiringPath"),n(sockRetiringPath,"sockRetiringPath");function tell(i,h){if(!i.connected||typeof i.send!="function")return!1;try{return i.send(h,()=>{})}catch{return!1}}f(tell,"tell"),n(tell,"tell");function refusePoolCommand(i,h){console.warn(`[devserver] refused ${i.method} ${i.url} on the public port \u2014 under a gateway the pool is driven on the control socket only.`),h.writeHead(404,{"content-type":"application/json"}),h.end(JSON.stringify({error:"not found"}))}f(refusePoolCommand,"refusePoolCommand"),n(refusePoolCommand,"refusePoolCommand"),exports.DEBUG_FIXED_PORTS_ENV="LENSMCP_DEBUG_FIXED_PORTS";function usesFixedInspectorPorts(i=process.env){const h=(i[exports.DEBUG_FIXED_PORTS_ENV]??"").trim().toLowerCase();return h==="1"||h==="true"||h==="yes"||h==="on"}f(usesFixedInspectorPorts,"usesFixedInspectorPorts"),n(usesFixedInspectorPorts,"usesFixedInspectorPorts");function inspectorPortFor(i,h,y=process.env){if(!usesFixedInspectorPorts(y))return 0;const S=Math.trunc(i)+Math.trunc(h);return Number.isInteger(S)&&S>1024&&S<=65535?S:0}f(inspectorPortFor,"inspectorPortFor"),n(inspectorPortFor,"inspectorPortFor");function ensureOwnerOnlyDir(i){try{fs.mkdirSync(i,{recursive:!0,mode:448})}catch{}try{const h=fs.lstatSync(i);h.isDirectory()&&(h.mode&63)!==0&&fs.chmodSync(i,448)}catch{}}f(ensureOwnerOnlyDir,"ensureOwnerOnlyDir"),n(ensureOwnerOnlyDir,"ensureOwnerOnlyDir");function claimSock(i,h=process.pid){ensureOwnerOnlyDir(path.dirname(i));try{const y=sockOwnerPath(i);try{fs.unlinkSync(y)}catch{}fs.writeFileSync(y,String(h),{flag:"wx",mode:384})}catch{}try{fs.unlinkSync(i)}catch{}try{fs.unlinkSync(sockRetiringPath(i))}catch{}}f(claimSock,"claimSock"),n(claimSock,"claimSock");function sockOwnedByAnother(i,h=process.pid){try{const y=fs.readFileSync(sockOwnerPath(i),"utf8").trim();return!!y&&y!==String(h)}catch{return!1}}f(sockOwnedByAnother,"sockOwnedByAnother"),n(sockOwnedByAnother,"sockOwnedByAnother");function cleanupSock(i,h=process.pid){if(i){try{const y=fs.readFileSync(sockOwnerPath(i),"utf8").trim();if(y&&y!==String(h))return}catch{}try{fs.unlinkSync(i)}catch{}try{fs.unlinkSync(sockOwnerPath(i))}catch{}try{fs.unlinkSync(sockRetiringPath(i))}catch{}}}f(cleanupSock,"cleanupSock"),n(cleanupSock,"cleanupSock");function serviceKeyFingerprint(){const i=process.env.LENSMCP_SERVICE_KEY;if(!i)return;const{createHash:h}=require("node:crypto");return h("sha256").update(i).digest("hex").slice(0,8)}f(serviceKeyFingerprint,"serviceKeyFingerprint"),n(serviceKeyFingerprint,"serviceKeyFingerprint");function rootModuleOf(i){let h;for(const y of i.getModules?.()?.values()??[])typeof y?.metatype!="function"||typeof y.distance!="number"||!Number.isFinite(y.distance)||(!h||y.distance<h.distance)&&(h=y);return h?.metatype}f(rootModuleOf,"rootModuleOf"),n(rootModuleOf,"rootModuleOf");let lastImportedModule;function takeImportedModule(){const i=lastImportedModule;return lastImportedModule=void 0,i}f(takeImportedModule,"takeImportedModule"),n(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 tt=Object.defineProperty;var f=(a,_)=>tt(a,"name",{value:_,configurable:!0});var Ze=Object.defineProperty,i=f((a,_)=>Ze(a,"name",{value:_,configurable:!0}),"i");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")),exit_reason_1=require("./exit-reason"),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:i(function(){return inspector_secret_1.inspectorPortOf},"get")}),Object.defineProperty(exports,"redactInspectorUrls",{enumerable:!0,get:i(function(){return inspector_secret_1.redactInspectorUrls},"get")});const devserver_transport_1=require("./devserver-transport");Object.defineProperty(exports,"gatewayManaged",{enumerable:!0,get:i(function(){return devserver_transport_1.gatewayManaged},"get")}),Object.defineProperty(exports,"isOwnerOnlyTransport",{enumerable:!0,get:i(function(){return devserver_transport_1.isOwnerOnlyTransport},"get")}),Object.defineProperty(exports,"mayDriveThePool",{enumerable:!0,get:i(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"),handoff_retire_1=require("./handoff-retire"),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"),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 a=process.env.GATEWAY_CONFIG;if(!a)return{};try{return JSON.parse(a)}catch{return{}}})();let gatewayMiddleware=null;if(GATEWAY_MIDDLEWARE_PATH)try{const a=require(GATEWAY_MIDDLEWARE_PATH);gatewayMiddleware=typeof a=="function"?a:typeof a.default=="function"?a.default:null,gatewayMiddleware||console.warn(`[gateway] ${GATEWAY_MIDDLEWARE_PATH} does not export a function, gateway disabled`)}catch(a){console.error(`[gateway] Failed to load middleware from ${GATEWAY_MIDDLEWARE_PATH}:`,a)}function applyGatewayMiddleware(a){if(gatewayMiddleware)try{gatewayMiddleware(a,GATEWAY_CONFIG)}catch(_){console.error("[gateway] Middleware error:",_)}}f(applyGatewayMiddleware,"applyGatewayMiddleware"),i(applyGatewayMiddleware,"applyGatewayMiddleware");const GATEWAY_ROUTES=(()=>{try{return JSON.parse(process.env.GATEWAY_ROUTES||"[]")}catch{return[]}})(),GATEWAY_HTTPS=process.env.GATEWAY_HTTPS==="1";function hostMatches(a,_){if(a.startsWith("*.")){const g=a.slice(1);return _.endsWith(g)||_===a.slice(2)}return _===a}f(hostMatches,"hostMatches"),i(hostMatches,"hostMatches");function matchGatewayRoute(a){if(GATEWAY_ROUTES.length===0)return;const _=(a.headers.host||"").split(":")[0],g=a.url||"/";for(const S of GATEWAY_ROUTES)if(!(S.host&&!hostMatches(S.host,_))&&!(S.prefix&&!g.startsWith(S.prefix)))return S}f(matchGatewayRoute,"matchGatewayRoute"),i(matchGatewayRoute,"matchGatewayRoute");const WORKER_NAMES=(()=>{try{return JSON.parse(process.env.WORKERS||"[]")}catch{return[]}})(),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 a=Number(process.env.LENSMCP_POD_GENERATION);return Number.isFinite(a)&&a>1?Math.floor(a):1})();function childSockPath(a){return path.join(SOCK_DIR,POD_GENERATION>1?`child-${a}-g${POD_GENERATION}.sock`:`child-${a}.sock`)}f(childSockPath,"childSockPath"),i(childSockPath,"childSockPath");function sockOwnerPath(a){return`${a}.owner`}f(sockOwnerPath,"sockOwnerPath"),i(sockOwnerPath,"sockOwnerPath");function sockRetiringPath(a){return`${a}.retiring`}f(sockRetiringPath,"sockRetiringPath"),i(sockRetiringPath,"sockRetiringPath");function tell(a,_){if(!a.connected||typeof a.send!="function")return!1;try{return a.send(_,()=>{})}catch{return!1}}f(tell,"tell"),i(tell,"tell");function refusePoolCommand(a,_){console.warn(`[devserver] refused ${a.method} ${a.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"}))}f(refusePoolCommand,"refusePoolCommand"),i(refusePoolCommand,"refusePoolCommand"),exports.DEBUG_FIXED_PORTS_ENV="LENSMCP_DEBUG_FIXED_PORTS";function usesFixedInspectorPorts(a=process.env){const _=(a[exports.DEBUG_FIXED_PORTS_ENV]??"").trim().toLowerCase();return _==="1"||_==="true"||_==="yes"||_==="on"}f(usesFixedInspectorPorts,"usesFixedInspectorPorts"),i(usesFixedInspectorPorts,"usesFixedInspectorPorts");function inspectorPortFor(a,_,g=process.env){if(!usesFixedInspectorPorts(g))return 0;const S=Math.trunc(a)+Math.trunc(_);return Number.isInteger(S)&&S>1024&&S<=65535?S:0}f(inspectorPortFor,"inspectorPortFor"),i(inspectorPortFor,"inspectorPortFor");function ensureOwnerOnlyDir(a){try{fs.mkdirSync(a,{recursive:!0,mode:448})}catch{}try{const _=fs.lstatSync(a);_.isDirectory()&&(_.mode&63)!==0&&fs.chmodSync(a,448)}catch{}}f(ensureOwnerOnlyDir,"ensureOwnerOnlyDir"),i(ensureOwnerOnlyDir,"ensureOwnerOnlyDir");function claimSock(a,_=process.pid){ensureOwnerOnlyDir(path.dirname(a));try{const g=sockOwnerPath(a);try{fs.unlinkSync(g)}catch{}fs.writeFileSync(g,String(_),{flag:"wx",mode:384})}catch{}try{fs.unlinkSync(a)}catch{}try{fs.unlinkSync(sockRetiringPath(a))}catch{}}f(claimSock,"claimSock"),i(claimSock,"claimSock");function sockOwnedByAnother(a,_=process.pid){try{const g=fs.readFileSync(sockOwnerPath(a),"utf8").trim();return!!g&&g!==String(_)}catch{return!1}}f(sockOwnedByAnother,"sockOwnedByAnother"),i(sockOwnedByAnother,"sockOwnedByAnother");function cleanupSock(a,_=process.pid){if(a){try{const g=fs.readFileSync(sockOwnerPath(a),"utf8").trim();if(g&&g!==String(_))return}catch{}try{fs.unlinkSync(a)}catch{}try{fs.unlinkSync(sockOwnerPath(a))}catch{}try{fs.unlinkSync(sockRetiringPath(a))}catch{}}}f(cleanupSock,"cleanupSock"),i(cleanupSock,"cleanupSock");function serviceKeyFingerprint(){const a=process.env.LENSMCP_SERVICE_KEY;if(!a)return;const{createHash:_}=require("node:crypto");return _("sha256").update(a).digest("hex").slice(0,8)}f(serviceKeyFingerprint,"serviceKeyFingerprint"),i(serviceKeyFingerprint,"serviceKeyFingerprint");function rootModuleOf(a){let _;for(const g of a.getModules?.()?.values()??[])typeof g?.metatype!="function"||typeof g.distance!="number"||!Number.isFinite(g.distance)||(!_||g.distance<_.distance)&&(_=g);return _?.metatype}f(rootModuleOf,"rootModuleOf"),i(rootModuleOf,"rootModuleOf");let lastImportedModule;function takeImportedModule(){const a=lastImportedModule;return lastImportedModule=void 0,a}f(takeImportedModule,"takeImportedModule"),i(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,15 +9,15 @@
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}f(importFresh,"importFresh"),n(importFresh,"importFresh");function debounce(i,h){let y=null;return(...S)=>{y&&clearTimeout(y),y=setTimeout(()=>i(...S),h)}}if(f(debounce,"debounce"),n(debounce,"debounce"),process.env.APP_RUNNER==="1"){(0,stdio_guard_1.guardBrokenStdio)();const i=n(y=>{if(!inspector.url())try{inspector.open(y,"127.0.0.1",!1)}catch(G){console.warn(`[child] inspector.open(${y}) failed (port taken by another devserver?) \u2014 falling back to a random port:`,G.message);try{inspector.open(0,"127.0.0.1",!1)}catch{}}const S=inspector.url();S&&tell(process,{type:"inspector-url",url:S})},"openInspector"),h=process.env.CHILD_DEBUG_PORT;if(h!==void 0&&h!==""){const y=Number(h);Number.isInteger(y)&&(y===0||y>1024)&&i(y)}try{require("@lensmcp/node-instrumentation/register")}catch{}(async()=>{let y=null,S=!1,G,J=!1;const Ce=(0,hot_swap_registries_1.registryPruningEnabled)(),te=n((t,s)=>{const p=(0,hot_swap_registries_1.describePrune)(t,s);p&&console.log(p)},"logPrune");let F={app:null,handler:n((t,s)=>{s.statusCode=503,s.end("starting")},"handler"),inflight:0};const re=(()=>{const t=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(t)&&t>=0?t:15*6e4})(),R=n(t=>{const s=globalThis.__lensmcpActiveWork;if(typeof s!="function")return{count:0};try{const p=s(t);return{count:Number(p?.count??0),...p?.oldestStartedAt?{oldestStartedAt:p.oldestStartedAt}:{}}}catch{return{count:0}}},"activeWork"),_e=n(t=>{const s=globalThis.__lensmcpStopWorkIntake;if(typeof s=="function")try{return s(t)}catch{return}},"stopWorkIntake"),oe=n(t=>{const s=globalThis.__lensmcpWorkIntakeReport;if(!(t===void 0||typeof s!="function"))try{return s(t)??void 0}catch{return}},"workIntakeReport"),be=(()=>{const t=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(t)&&t>=1?Math.floor(t):1})(),q=new Set,N=(0,swap_recycle_1.swapRecyclePolicy)();let L,j=0;const Ne=(()=>{const t=Number(process.env.LENSMCP_POD_RETIRE_NOTICE_MS);return Number.isFinite(t)&&t>=0?t:3500})();let ne=!1,X=!1;const xe=(0,pod_memory_1.podMemoryPolicy)();let Ae=0;const ge=new Set;let u=!1;const P=n(()=>{if(!u)return;let t=0;for(const s of ge)s.deref()===void 0?ge.delete(s):t+=1;return t},"liveContainers"),m=(0,pod_memory_1.createPodMemoryMonitor)({policy:xe,state:n(()=>({gen:F.gen??0,swaps:j,...L===void 0?{}:{baseline:L},busy:S||J||A.size>0,lastBusyAt:T}),"state"),send:n(t=>{tell(process,t)},"send"),containers:P,counter:(0,pod_memory_1.createLiveObjectCounter)(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH)),onRetained:n(()=>ie(),"onRetained")}),W=n(()=>((0,pod_memory_1.fullGc)()&&m.tracker.noteGc(),process.memoryUsage().heapUsed),"liveHeap"),$=(()=>{if(!(0,error_stack_release_1.errorFrameReleaseEnabled)())return null;try{const t=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH))+path.sep,s=`${path.sep}node_modules${path.sep}`,p=new Set(Object.keys(require.cache));return(0,error_stack_release_1.createErrorFrameReleaser)(require.cache,{skip:n(_=>p.has(_)||_.startsWith(t)&&!_.slice(t.length).includes(s)&&!_.slice(t.length).startsWith(`node_modules${path.sep}`),"skip")})}catch{return null}})();let se=!1;function x(){if(!(!$||se))try{const t=$();t.errors>0&&console.log(`[child] read the stack of ${t.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(t){console.error("[child] could not release library error frames:",t),se=!0}}f(x,"D"),n(x,"releaseLibraryErrorFrames");const A=new Map;let T=Date.now();const D=n(()=>N.settleMs<=0||!S&&!J&&A.size===0&&Date.now()-T>=N.settleMs,"settled");let Y;function he(t){if(!(!N.enabled||ne||X)){if(N.settleMs<=0){z(t);return}Y&&clearTimeout(Y),Y=setTimeout(()=>{Y=void 0,D()?z(t):he(t)},N.settleMs),Y.unref?.()}}f(he,"_e"),n(he,"recycleCheckWhenSettled");const fe=n(()=>{if(N.stuckCloseMs<=0)return 0;const t=Date.now();let s=0;for(const p of A.values())t-p>=N.stuckCloseMs&&(s+=1);return s},"stuckCloses");function z(t){if(!N.enabled||ne||X||!process.send)return;const s=v8.getHeapStatistics().heap_size_limit,p=n(g=>{const E=m.oldestRetained();return{swaps:j,usedBytes:g,limitBytes:s,stuckCloses:fe(),settled:D(),...L===void 0?{}:{baselineBytes:L},...E?{retained:{generation:E.gen,ageMs:Date.now()-E.closedAt,gcs:E.gcs}}:{}}},"state");if(!(0,swap_recycle_1.recycleReason)(N,p(process.memoryUsage().heapUsed)))return;const _=(0,swap_recycle_1.recycleReason)(N,p(W()));_&&(ne=!0,console.log(`[child] asking for a fresh pod ${t} \u2014 ${_}. 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:_}))}f(z,"ee"),n(z,"considerRecycle");let K;function ie(){if(!N.enabled||N.retainedMs<=0||ne||X)return;const t=m.oldestRetained();if(!t)return;const s=t.closedAt+N.retainedMs-Date.now();if(s<=0){z("with a closed generation still in memory");return}K||(K=setTimeout(()=>{K=void 0,m.measure("retention-check").catch(()=>{})},s),K.unref?.())}f(ie,"ae"),n(ie,"retainedRecycleCheck");function ae(t,s){const p={};s&&(p.module=s),t&&(p.app=t);try{const _=t?.app;if(_&&typeof _=="object"&&(p.nestApp=_,_.container&&typeof _.container=="object")){p.container=_.container;const g=rootModuleOf(_.container);g&&(p.rootModule=g)}}catch{}return p}f(ae,"ye"),n(ae,"generationTargets");async function ce(t,s){if(t.closed||(t.closed=!0,q.delete(t),s&&console.error(`[child] ${s}`),!t.app))return;A.set(t,Date.now());const p=N.enabled&&N.stuckCloseMs>0?setTimeout(()=>{A.has(t)&&(console.error(`[child] a previous app has been closing for ${Math.round(N.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.`),z("with a previous app stuck in close()"))},N.stuckCloseMs):void 0;p?.unref?.();const _=t.app;try{await t.app.close()}catch(g){console.error("[child] error closing a previous app:",g)}finally{A.delete(t),T=Date.now(),p&&clearTimeout(p),t.app=null,t.handler=(g,E)=>{E.statusCode=503,E.end("closed")},t.gen!==void 0&&m.closed(t.gen,j,ae(_,t.module)),t.module=void 0}if(t.superseded){try{te((0,hot_swap_registries_1.pruneRegistries)(t.superseded,"serve"),"after closing the previous app")}catch(g){console.error("[child] could not release the previous app's class registrations:",g)}t.superseded=void 0}he("after closing the previous app")}f(ce,"ge"),n(ce,"closeGeneration");async function Q(t){for(;q.size>=be;){const E=q.values().next().value;if(!E)break;await ce(E,`closing a still-draining generation early \u2014 ${q.size} were pending and the cap is ${be} (each holds a whole app: DI container, DB pool, queue workers). Raise LENSMCP_SWAP_MAX_DRAINING if this pod legitimately needs more.`)}q.add(t);const s=Date.now(),p=n(()=>({inflight:t.inflight,work:R(t.workGen).count}),"busy");for(;re>0&&Date.now()-s<re;){if(t.closed)return;const E=p();if(E.inflight===0&&E.work===0)break;await new Promise(H=>{setTimeout(H,250).unref?.()})}if(t.closed)return;const _=p(),g=oe(t.workGen);_.inflight>0||_.work>0?console.error(`[child] swap drain expired after ${Date.now()-s}ms \u2014 closing the previous app with ${_.inflight} in-flight request(s) and ${_.work} background job(s) still running. `+(g?`Previous app still processing ${g.running} queue job(s); ${g.takenAfterStop} were taken after the swap. `:"")+`A queue job killed here keeps its lock until the TTL lapses. Raise LENSMCP_SWAP_DRAIN_MS (currently ${re}ms) if this is legitimate work.`):(Date.now()-s>250||g?.runningAtStop||g?.takenAfterStop)&&console.log(`[child] previous app drained in ${Date.now()-s}ms \u2014 closing it`+(g?` (it finished ${g.finishedAfterStop} queue job(s) after the swap; ${g.takenAfterStop} were taken after the swap)`:"")),await ce(t)}f(Q,"ce"),n(Q,"drainThenClose");async function Z(){if(S)return J=!0,console.log("[child] Reload deferred \u2014 will re-swap after current swap completes"),y;S=!0,T=Date.now(),process.removeAllListeners("uncaughtException"),process.removeAllListeners("unhandledRejection"),process.on("uncaughtException",(b,U)=>{console.error(`[child] uncaughtException (${U}):`,b)}),process.on("unhandledRejection",b=>{const U=b instanceof Error?b.stack||b.message:String(b);U.includes("FronteggContextScope")||U.includes("populateLoggerMetadata")||console.error("[child] unhandledRejection:",b)});let t;if(Ce)try{t=(0,hot_swap_registries_1.captureRegistries)()}catch{t=void 0}const s=global.__lensmcpBeginWorkGeneration,p=typeof s=="function"?s():void 0;try{try{await importFresh(BUNDLE_PATH)}catch(b){if(!(b instanceof SyntaxError))throw b;console.warn(`[child] bundle was unreadable mid-write (${b.message}) \u2014 retrying the swap once`),await new Promise(U=>setTimeout(U,400)),await importFresh(BUNDLE_PATH)}}catch(b){throw S=!1,T=Date.now(),b}if(typeof global.createChildApp!="function")throw S=!1,T=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 _;if(t)try{_=(0,hot_swap_registries_1.supersededSince)(t),te((0,hot_swap_registries_1.pruneRegistries)(_,"build"),"at the swap")}catch(b){console.error("[child] could not release superseded class registrations:",b)}let g;try{g=await global.createChildApp()}catch(b){throw S=!1,T=Date.now(),takeImportedModule(),b}const E=F;_?.size&&(E.app?E.superseded=_:te((0,hot_swap_registries_1.pruneRegistries)(_,"serve"),"at the swap")),y=g;const H=takeImportedModule();F={app:g,handler:g.handler,inflight:0,gen:++Ae,...H?{module:H}:{},...p===void 0?{}:{workGen:p}};const de=ae(g,void 0).container;de&&(ge.add(new WeakRef(de)),u=!0);const V=E.app&&p!==void 0?_e(p):void 0;return console.log("[child] Swapped to fresh app (previous draining in background)"+(V?.workers?`; its ${V.workers} queue worker(s) stopped taking new jobs, previous app still processing ${V.runningAtStop} job(s)`:"")),x(),E.app&&(j+=1,Q(E).catch(b=>console.error("[child] background close error:",b)),setTimeout(()=>z("30s after a hot swap"),3e4).unref?.(),m.swapped(E.gen,()=>E.closed===!0&&!A.has(E))),S=!1,T=Date.now(),J?(J=!1,Z()):g}f(Z,"le"),n(Z,"swapNow");const ye=debounce(async()=>{try{console.log("[child] /webpack/reload"),await Z()}catch(t){console.error("[child] reload failed:",t)}},250),le=http.createServer((t,s)=>{if(t.method==="POST"&&t.url==="/webpack/reload"){s.writeHead(200,{"content-type":"application/json"}),s.end(JSON.stringify({ok:!0})),ye();return}if(t.method==="GET"&&t.url==="/__lensmcp/alive"){const _=t.headers["x-internal-token"],g=process.env.LENSMCP_SERVICE_KEY;if(g&&_!==g){s.writeHead(404,{"content-type":"text/plain"}),s.end("not found");return}const E=R();s.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),s.end(JSON.stringify({ok:!0,pid:process.pid,swapping:S,inflight:F.inflight,oldestInflightAt:F.oldestAt,activeWork:E.count,oldestWorkAt:E.oldestStartedAt,keyFingerprint:serviceKeyFingerprint(),...G?{watcher:G}:{},...Number.isFinite(Number(process.env.LENSMCP_POD_GENERATION))&&process.env.LENSMCP_POD_GENERATION?{podGeneration:Number(process.env.LENSMCP_POD_GENERATION)}:{}}));return}const p=F;p.inflight+=1,p.oldestAt===void 0&&(p.oldestAt=Date.now()),s.on("close",()=>{p.inflight-=1,p.inflight===0&&(p.oldestAt=void 0),m.activity()}),p.handler(t,s)});le.keepAliveTimeout=0;const I=process.env.CHILD_SOCK_PATH;process.on("disconnect",()=>{cleanupSock(I),process.exit(0)});try{const t=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH);if((0,schema_first_instance_1.schemaPrewarmEnabled)())try{const s=(0,schema_first_instance_1.prewarmZodFor)(t);s?.created&&console.log(`[child] zod${s.version?` ${s.version}`:""}: built ${s.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 s=(0,redis_disconnect_fix_1.finishStrandedDisconnectsFor)(t);s?.patched&&console.log(`[child] ioredis${s.versions.length?` ${s.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 Z(),L=(await m.booted()).live,console.log(`[child] Using bundle: ${t}`),claimSock(I),le.listen(I,()=>{console.log(`[child] Listening on ${I}`),tell(process,{type:"ready",socketPath:I})})}catch(t){console.error("[child] Startup error:",t),tell(process,{type:"boot-error",error:String(t?.stack||t)}),process.exitCode=1;return}process.on("message",async t=>{if(!(!t||typeof t!="object")){if(t.type==="debug-open"){const s=Number(t.port);i(Number.isInteger(s)&&s>1024?s:0);return}if(t.type==="watcher"){const s=t.testimony;s&&typeof s=="object"&&(G=s);return}if(t.type==="heap-snapshot"){me(t);return}if(t.type==="recycle-declined"){ne=!1;return}if(t.type==="retire"){ee();return}if(t.type==="reload"){if(X)return;try{await Z(),tell(process,{type:"reloaded",socketPath:I})}catch(s){console.error("[child] reload error:",s),tell(process,{type:"reload-error",error:String(s?.stack||s)})}}}});let pe=!1;async function me(t){const s=n(p=>{tell(process,{type:"heap-snapshot-result",id:t.id,...p})},"reply");if(pe)return s({ok:!1,refused:"a snapshot of this pod is already being written"});pe=!0;try{const p=W(),_=m.tracker.views().map(de=>de.gen),g=(0,heap_snapshot_1.heapSnapshotPolicy)();t.maxHeapBytes&&(g.maxHeapBytes=t.maxHeapBytes);const E=(0,heap_snapshot_1.heapSnapshotRefusal)(g,{live:p,...t.available?{available:t.available}:{}});if(E)return s({ok:!1,refused:E,live:p});console.log(`[child] writing a heap snapshot (${Math.round(p/1048576)} MB live) \u2014 the pod pauses while V8 serialises it`);const H=await(0,heap_snapshot_1.writeHeapSnapshot)(t.file);s({ok:!0,file:t.file,bytes:H.bytes,ms:H.ms,live:p,gen:F.gen??0,closedAlive:_})}catch(p){s({ok:!1,error:p?.message??String(p)})}finally{pe=!1}}f(me,"$e"),n(me,"takeHeapSnapshot");async function ee(){if(X)return;X=!0,m.stop(),console.log("[child] retiring \u2014 a fresh pod has taken over; finishing in-flight work, then exiting");const t=_e(Number.POSITIVE_INFINITY);t?.workers&&console.log(`[child] its ${t.workers} queue worker(s) stopped taking new jobs, still processing ${t.runningAtStop} job(s)`);try{fs.writeFileSync(sockRetiringPath(I),String(process.pid),{flag:"w",mode:384})}catch{}await new Promise(p=>{setTimeout(p,Ne).unref?.()}),cleanupSock(I),le.close();const s=Date.now();for(;Date.now()-s<re&&(le.closeIdleConnections?.(),!(F.inflight===0&&R().count===0));)await new Promise(p=>{setTimeout(p,250).unref?.()});setTimeout(()=>process.exit(0),3e4).unref?.();try{await y?.close()}catch(p){console.error("[child] close error while retiring:",p)}process.exit(0)}f(ee,"re"),n(ee,"retire"),process.on("beforeExit",()=>{try{inspector?.close?.()}catch{}});const we=n(async t=>{console.log(`[child ${t}] shutting down\u2026`);const s=y?.close().catch(_=>console.error("[child] close error:",_)),p=new Promise(_=>le.close(()=>_()));cleanupSock(I),setTimeout(()=>process.exit(0),700).unref(),await Promise.all([s,p]),process.exit(0)},"shutdown");["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(t=>{process.on(t,()=>{inspector?.close?.(),we(t)})})})()}else{let i=f(function(u){L.push(u),L.length>N&&L.splice(0,L.length-N),be?.write((0,inspector_secret_1.redactInspectorUrls)(u.replace(q,"")));for(const P of j)try{const m=P.plain?u.replace(q,""):u;P.res.write(P.redact?(0,inspector_secret_1.redactInspectorUrls)(m):m)}catch{j.delete(P)}},"z");n(i,"emitLogLine");const h=12,y=process.env.LENSMCP_PROJECT||SERVICE_NAME||"service",S=(0,pod_memory_events_1.createPodMemoryPublisher)(process.env.LENSMCP_EVENT_FILE),G=n(u=>({project:y,service:SERVICE_NAME||y,pod:u.id,pid:u.proc.pid??0,podGeneration:POD_GENERATION}),"podIdentity"),J=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[31m"],Ce="\x1B[0m",te=Math.max(1,Number(process.env.CHILD_COUNT||1)),F=LENSMCP_WS_KEY||path.basename(process.cwd()),re=n(u=>(0,process_name_1.namedExecPath)((0,process_name_1.processName)(F,SERVICE_NAME||"service",u)),"execPathFor");let R=(()=>{const u=Number(process.env.LENSMCP_DEBUG_PORT||"");return Number.isInteger(u)&&u>1024?u:0})();const _e=20;R&&(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 (${R}+slot, workers ${R}+${_e}+i). Any account on this host can connect to 127.0.0.1:${R} 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 oe=process.env.LENSMCP_LOG_FILE||"",be=oe?(()=>{try{fs.mkdirSync(path.dirname(oe),{recursive:!0});const u=fs.createWriteStream(oe,{flags:"a",mode:384});try{fs.chmodSync(oe,384)}catch{}return u}catch(u){return console.warn(`[parent] cannot open log file ${oe}:`,u.message),null}})():null,q=/\x1b\[[0-9;]*m/g,N=2e3,L=[],j=new Set,Ne=(0,devserver_transport_1.gatewayManaged)();for(const u of["log","info","warn","error"]){const P=console[u].bind(console),m=u==="log"||u==="info"?process.stdout:process.stderr;console[u]=(...W)=>{P(...W.map($=>typeof $=="string"?(0,inspector_secret_1.forStream)(m,Ne,$):$)),i(W.map($=>typeof $=="string"?$:util.inspect($)).join(" ")+`
13
- `)}}const ne=n(u=>J[(u-1)%J.length],"colorFor"),X=n(u=>{if(te===1)return"";const P=`[child#${u}] `;return`${ne(u)}${P}${Ce}`},"tagFor"),xe=n(u=>u.startsWith("{")&&u.endsWith("}"),"isJsonLog"),Ae=n((u,P,m)=>{const W=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:n(x=>`
14
- `+String(x),"stack")}}),$=n((x,A)=>{const T=x==="stdout"?process.stdout:process.stderr;try{m?.(A)}catch{}const D=xe(A)?W(A):`${A}
15
- `;T.write((0,inspector_secret_1.forStream)(T,Ne,`${P}${D}`)),i(`${P}${D}`)},"write"),se=n((x,A)=>{if(!x)return;const T=readline.createInterface({input:x});T.on("line",D=>$(A,D)),T.on("close",()=>{})},"attach");se(u.stdout,"stdout"),se(u.stderr,"stderr")},"wireProcLogging"),ge=n(u=>Ae(u.proc,X(u.id),P=>u.tail.push(P)),"wireChildLogging");(async()=>{ensureOwnerOnlyDir(SOCK_DIR);const u=httpProxy.createProxyServer({});let P=Number(process.env.PORT)||0;P||(P=9090);const m=[],W=new Set;function $(){let e=0;for(;W.has(e);)e++;return W.add(e),e}f($,"I"),n($,"allocDebugSlot");let se=1,x=0,A=!1,T=te,D=[],Y=0;const he=(()=>{const e=Number(process.env.LENSMCP_POD_BOOT_GRACE_MS);return Number.isFinite(e)&&e>=0?e:12e4})(),fe=n(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"childExited"),z=n(e=>e.booting&&!fe(e)&&Date.now()-e.spawnedAt<he,"stillBooting");function K(){return m.filter(e=>e.healthy&&typeof e.socketPath=="string")}f(K,"J"),n(K,"healthyChildren");let ie;function ae(e){if(!e||typeof e!="object")return;const o=e;if(o.schemaVersion===1){ie=o;for(const l of m)tell(l.proc,{type:"watcher",testimony:o})}}f(ae,"ye"),n(ae,"recordWatcherTestimony");function ce(e,o=256*1024){return new Promise(l=>{let d="",a=!1;e.on("data",r=>{a||(d+=r,d.length>o&&(a=!0))}),e.on("end",()=>{if(a||!d)return l(void 0);try{l(JSON.parse(d))}catch{l(void 0)}}),e.on("error",()=>l(void 0))})}f(ce,"ge"),n(ce,"readJsonBody");function Q(){const e=K();if(e.length===0)return null;const o=x%e.length;return x=(x+1)%e.length,e[o]}f(Q,"ce"),n(Q,"pickChild");function Z(e,o){const l=`Child#${e.id}`,d=SERVICE_NAME||y,a=Date.now();if(o.type==="pod-memory"){const r=o.report;if(!r||typeof r.live!="number")return;e.memory.latest=r,e.memory.history.push(r),e.memory.history.length>12&&e.memory.history.splice(0,e.memory.history.length-12),console.log(`[parent] ${(0,pod_memory_1.describePodMemory)(l,r)}`),S.publish((0,pod_memory_events_1.buildPodMemoryEvent)(G(e),r))}else if(o.type==="pod-memory-retained"){const r=o.retained;if(!r||typeof r.gen!="number")return;e.memory.retained.set(r.gen,{...r,at:a}),console.warn(`[parent] ${(0,pod_memory_1.describeRetained)(l,d,r)}`),S.publish((0,pod_memory_events_1.buildPodRetainedEvent)(G(e),r,a))}else{const r=o.released;if(!r||typeof r.gen!="number")return;e.memory.retained.delete(r.gen),console.log(`[parent] ${(0,pod_memory_1.describeReleased)(l,d,r)}`),S.publish((0,pod_memory_events_1.buildPodReleasedEvent)(G(e),r,a))}}f(Z,"le"),n(Z,"recordPodMemory");const ye=new Map;let le=0;async function I(){const e=se++,o=childSockPath(e);cleanupSock(o);const l=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&l.unshift("--require","@swc-node/register"),l.push(...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const d=R?$():-1,a=(0,node_child_process_1.fork)(__filename,{env:{...process.env,APP_RUNNER:"1",CHILD_SOCK_PATH:o,...d>=0&&{CHILD_DEBUG_PORT:String(inspectorPortFor(R,d))}},stdio:["inherit","pipe","pipe","ipc"],execArgv:l,execPath:re("pod")}),r={id:e,proc:a,healthy:!1,lastError:null,debugSlot:d,tail:new exit_reason_1.TailBuffer,booting:!0,spawnedAt:Date.now(),bootReloadSeq:Y,memory:{history:[],retained:new Map}};return a.on("error",w=>console.error(`[parent] Child#${e}: ${w.message}`)),a.on("message",w=>{if(!w||typeof w!="object")return;const c=w;c.type==="ready"?(r.socketPath=String(c.socketPath),r.healthy=!0,r.booting=!1,console.log(`[parent] Child#${r.id} ready on socket ${r.socketPath}`),ie&&tell(a,{type:"watcher",testimony:ie}),Y!==r.bootReloadSeq&&tell(a,{type:"reload"})):c.type==="recycle-request"?_(r,String(c.reason||"it has outgrown its bound")):c.type==="inspector-url"?(r.inspectorUrl=String(c.url),console.log(`[parent] Child#${r.id} Debugger listening on ${c.url}`)):c.type==="reloaded"?(r.socketPath=String(c.socketPath),r.healthy=!0,console.log(`[parent] Child#${r.id} hot-swapped on socket ${r.socketPath}`)):c.type==="reload-error"?(r.lastError=String(c.error||"unknown reload error"),console.error(`[parent] Child#${r.id} reload error: ${r.lastError}`),r.healthy=!1):c.type==="boot-error"?(r.lastError=String(c.error||"unknown boot error"),console.error(`[parent] Child#${r.id} boot error: ${r.lastError}`),r.healthy=!1,r.booting=!1):c.type==="pod-memory"||c.type==="pod-memory-retained"||c.type==="pod-memory-released"?Z(r,c):c.type==="heap-snapshot-result"&&ye.get(Number(c.id))?.(c)}),a.on("exit",(w,c)=>{r.booting=!1;for(const O of r.memory.retained.values()){const M={gen:O.gen,closedAt:O.closedAt,ageMs:Date.now()-O.closedAt,reason:"pod-exited"};console.log(`[parent] ${(0,pod_memory_1.describeReleased)(`Child#${r.id}`,SERVICE_NAME||y,M)}`),S.publish((0,pod_memory_events_1.buildPodReleasedEvent)(G(r),M,Date.now()))}r.memory.retained.clear(),r.memory.latest&&S.publish((0,pod_memory_events_1.buildPodExitedEvent)(G(r),{code:w,signal:c},Date.now())),r.debugSlot>=0&&(W.delete(r.debugSlot),r.debugSlot=-1);const v=c==="SIGINT"||c==="SIGTERM"||w===0;if(v?console.log(`[parent] Child#${r.id} exited cleanly (code=${w}, signal=${c??"none"})`):(console.error((0,exit_reason_1.crashReport)(`[parent] Child#${r.id} crashed (code=${w}, signal=${c??"none"}, pid=${r.proc.pid}, ${r.healthy?"was serving":"was not ready"})`,w,c,r.tail.snapshot())),r.lastError||(r.lastError=`Child exited abnormally (code=${w}, signal=${c??"none"})`)),r.healthy=!1,cleanupSock(r.socketPath,r.proc.pid),r.socketPath=void 0,!v&&!A){const O=m.indexOf(r);O>=0&&m.splice(O,1);const M=Date.now();if(D=D.filter(B=>M-B<3e4),D.length>=5){console.error(`[parent] crash-loop detected (${D.length} respawns/30s) \u2014 pausing auto-respawn; POST /webpack/reload to retry`);return}D.push(M),setTimeout(()=>{const B=m.filter(ve=>ve.proc.killed===!1).length;!A&&B<T&&(console.log(`[parent] respawning a crashed pod (${B}/${T} live)`),I().catch(()=>{}))},1500).unref?.()}}),m.push(r),ge(r),r}f(I,"O"),n(I,"spawnChild");async function pe(e){T=Math.max(T,e);const o=m.filter(d=>d.proc.killed===!1),l=e-o.length;for(let d=0;d<l;d++)await I()}f(pe,"pe"),n(pe,"ensurePoolSize");async function me(){const e=m.filter(o=>(!o.healthy||typeof o.socketPath!="string")&&!z(o));await Promise.all(e.map(async o=>{try{o.proc.kill("SIGTERM")}catch{}cleanupSock(o.socketPath,o.proc.pid),o.socketPath=void 0;const l=m.indexOf(o);l>=0&&m.splice(l,1),await I()}))}f(me,"$e"),n(me,"respawnUnhealthy");const ee=new Set;let we=!1,t=0;const s=3e4,p=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return(Number.isFinite(e)&&e>=0?e:15*6e4)+6e4})();async function _(e,o){const l=n(a=>{console.log(`[parent] Child#${e.id} asked for a fresh pod (${o}) \u2014 not now: ${a}`),tell(e.proc,{type:"recycle-declined"})},"decline");if(A||!m.includes(e))return;if(we)return l("another pod is already being replaced");const d=Date.now()-t;if(d<s)return l(`a pod was replaced ${Math.round(d/1e3)}s ago`);we=!0,console.log(`[parent] Child#${e.id} asked for a fresh pod \u2014 ${o}. Starting one; Child#${e.id} keeps serving until it is ready.`);try{const a=await I(),r=Date.now()+he;for(;!a.healthy&&!a.lastError&&!fe(a)&&Date.now()<r;)await new Promise(v=>{setTimeout(v,100).unref?.()});if(A)return;if(!a.healthy){const v=m.indexOf(a);v>=0&&m.splice(v,1);try{a.proc.kill("SIGTERM")}catch{}return l(`its successor Child#${a.id} did not come up (${a.lastError??"no answer in time"})`)}const w=m.indexOf(e);w>=0&&m.splice(w,1),e.healthy=!1,ee.add(e);const c=setTimeout(()=>{if(!fe(e)){console.error(`[parent] Child#${e.id} was still running ${p}ms after it was retired \u2014 killing it`);try{e.proc.kill("SIGKILL")}catch{}}},p);if(c.unref?.(),e.proc.once("exit",()=>{clearTimeout(c),ee.delete(e)}),!tell(e.proc,{type:"retire"}))try{e.proc.kill("SIGTERM")}catch{}t=Date.now(),console.log(`[parent] Child#${a.id} took over from Child#${e.id} (pid ${e.proc.pid} \u2192 ${a.proc.pid})`)}catch(a){l(`could not start a successor: ${a?.message??String(a)}`)}finally{we=!1}}f(_,"f"),n(_,"recyclePod");const g=[];function E(e){const o=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH)),l=path.join(o,`${e}.js`);if(!fs.existsSync(l))return console.error(`[parent] Worker "${e}" bundle not found: ${l}`),null;const d=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&d.unshift("--require","@swc-node/register");try{d.push("--require",require.resolve("@lensmcp/node-instrumentation/register"))}catch{}const a=inspectorPortFor(R||9229,_e+Math.max(0,WORKER_NAMES.indexOf(e)));d.push(R?`--inspect=127.0.0.1:${a}`:`--inspect-port=127.0.0.1:${a}`,...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const r=(0,node_child_process_1.fork)(l,{env:process.env,stdio:["inherit","pipe","pipe","ipc"],execArgv:d,execPath:re(`w-${e}`)}),w={name:e,proc:r,debugPort:a};return g.push(w),r.on("error",c=>console.error(`[parent] Worker "${e}": ${c.message}`)),Ae(r,`\x1B[35m[worker:${e}] \x1B[0m`,c=>{const v=/Debugger listening on (wss?:\/\/\S+)/.exec(c);v&&(w.inspectorUrl=v[1])}),r.on("exit",(c,v)=>{v==="SIGINT"||v==="SIGTERM"||c===0||console.error(`[parent] Worker "${e}" crashed (code=${c}, signal=${v??"none"})`);const O=g.indexOf(w);O>=0&&g.splice(O,1)}),console.log(`[parent] Worker "${e}" started (pid=${r.pid})`),w}f(E,"E"),n(E,"spawnWorkerProcess");const H=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(e)&&e>=0?e:15*6e4})(),de=(()=>{const e=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(e)&&e>=1?Math.floor(e):1})(),V=new Set,b=n(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"workerExited");function U(e,o){if(V.delete(e),!b(e)){console.error(`[parent] Worker "${e.name}" (pid=${e.proc.pid}) ${o} \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{}}}f(U,"x"),n(U,"killDrainingWorker");function Ge(e){try{e.proc.kill("SIGTERM")}catch{}if(b(e))return;const o=[...V].filter(d=>d.name===e.name);for(;o.length>=de;)U(o.shift(),`was still running when a later reload replaced its successor (cap ${de})`);V.add(e);const l=setTimeout(()=>U(e,`was still running ${H}ms after SIGTERM`),H);l.unref?.(),e.proc.once("exit",()=>{clearTimeout(l),V.delete(e)})}f(Ge,"Ue"),n(Ge,"retireWorker");function Le(){for(const e of[...g])Ge(e);g.length=0;for(const e of WORKER_NAMES)E(e)}f(Le,"He"),n(Le,"restartWorkers");const Be=debounce(async()=>{Y+=1;const e=K();if(e.length>0){console.log(`[parent] Forwarding reload to ${e.length} child(ren)`);for(const o of e)tell(o.proc,{type:"reload"})}await me(),WORKER_NAMES.length>0&&Le()},200),Ee=n(async(e,o)=>{if(e.method==="POST"&&e.url==="/webpack/reload"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,o);o.writeHead(200,{"content-type":"application/json"}),o.end(JSON.stringify({ok:!0})),ce(e).then(a=>ae(a?.watcher)),Be();return}if(e.method==="POST"&&e.url==="/webpack/watching"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,o);const a=await ce(e);ae(a),o.writeHead(200,{"content-type":"application/json"}),o.end(JSON.stringify({ok:!0,relayed:ie!==void 0}));return}if(e.method==="POST"&&e.url==="/webpack/scale"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,o);let a="";e.on("data",r=>{a+=r}),e.on("end",async()=>{let r=0;try{r=Number(JSON.parse(a||"{}").pods)||0}catch{}r=Math.max(1,Math.min(r,16)),await pe(r),o.writeHead(200,{"content-type":"application/json"}),o.end(JSON.stringify({ok:!0,pods:r}))});return}if(e.method==="GET"&&e.url?.startsWith("/webpack/logs")){const a=new URL(e.url,"http://localhost").searchParams,r=Math.min(Math.max(Number(a.get("tail")??"100")||0,0),N),w=a.get("follow")!=="0",c=a.get("plain")==="1",v=!(0,devserver_transport_1.isOwnerOnlyTransport)(e);o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-cache"});const O=r===0?"":L.slice(-r).join(""),M=c?O.replace(q,""):O;if(o.write(v?(0,inspector_secret_1.redactInspectorUrls)(M):M),!w){o.end();return}const B={res:o,plain:c,redact:v};j.add(B),e.on("close",()=>j.delete(B));return}if(e.method==="POST"&&e.url?.startsWith("/webpack/debug")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){o.writeHead(404,{"content-type":"application/json"}),o.end(JSON.stringify({error:"not found"}));return}const a=Number(new URL(e.url,"http://localhost").searchParams.get("port")||"");Number.isInteger(a)&&a>1024&&(R=a),R||(R=9229);const r=m.filter(c=>c.proc.exitCode===null&&c.proc.signalCode===null);for(const c of r)c.debugSlot<0&&(c.debugSlot=$()),tell(c.proc,{type:"debug-open",port:inspectorPortFor(R,c.debugSlot)});for(const c of g)try{c.proc.kill("SIGUSR1")}catch{}const w=Date.now()+2e3;for(;Date.now()<w&&r.some(c=>!c.inspectorUrl);)await new Promise(c=>setTimeout(c,50));o.writeHead(200,{"content-type":"application/json"}),o.end(JSON.stringify({ok:!0,basePort:R,fixedPorts:usesFixedInspectorPorts(),pods:r.map(c=>({id:c.id,inspectorUrl:c.inspectorUrl??null})),workers:g.map(c=>({name:c.name,port:c.debugPort||(0,inspector_secret_1.inspectorPortOf)(c.inspectorUrl),inspectorUrl:c.inspectorUrl??null}))},null,2)+`
16
- `);return}if(e.method==="GET"&&e.url==="/webpack/memory"){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){o.writeHead(404,{"content-type":"application/json"}),o.end(JSON.stringify({error:"not found"}));return}const a=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),r=[...m,...ee].map(w=>({id:w.id,pid:w.proc.pid??0,podGeneration:POD_GENERATION,healthy:w.healthy,retiring:ee.has(w),latest:w.memory.latest??null,history:w.memory.history,retained:[...w.memory.retained.values()]}));o.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),o.end(JSON.stringify({ok:!0,service:SERVICE_NAME,project:y,bundle:{path:a},pods:r},null,2)+`
17
- `);return}if(e.method==="POST"&&e.url?.startsWith("/webpack/heap")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){o.writeHead(404,{"content-type":"application/json"}),o.end(JSON.stringify({error:"not found"}));return}const a=n((C,ke)=>{o.writeHead(C,{"content-type":"application/json"}),o.end(JSON.stringify(ke,null,2)+`
18
- `)},"reply"),r=new URL(e.url,"http://localhost").searchParams,w=Number(r.get("pod")||""),c=r.has("maxMb")?Number(r.get("maxMb")):void 0;if(c!==void 0&&!(Number.isFinite(c)&&c>0)){a(400,{ok:!1,error:"maxMb takes a positive number of MB"});return}const v=Number.isInteger(w)&&w>0?m.find(C=>C.id===w):K()[0];if(!v||fe(v)){a(404,{ok:!1,error:w?`no pod #${w} \u2014 running: ${m.map(C=>`#${C.id}`).join(", ")||"none"}`:"no pod is serving"});return}if(ye.size>0){a(409,{ok:!1,refused:"a heap snapshot is already being written for this service"});return}const O=(0,heap_snapshot_1.heapSnapshotPolicy)(),M=(0,heap_snapshot_1.heapSnapshotDir)();let B;try{(0,heap_snapshot_1.ensureHeapDir)(M);const C=(0,heap_snapshot_1.pruneHeapSnapshots)(M,O);C.length&&console.log(`[parent] removed ${C.length} older heap snapshot(s) from ${M}`),B=path.join(M,(0,heap_snapshot_1.heapSnapshotFileName)(SERVICE_NAME||y,v.id,v.proc.pid??0,v.memory.latest?.gen??0,Date.now()))}catch(C){a(500,{ok:!1,error:`cannot prepare ${M}: ${C.message}`});return}const ve=++le,Me=(0,heap_snapshot_1.availableSystemMemory)();let Pe;const k=await new Promise(C=>{const ke=setTimeout(()=>C(void 0),6e5);ke.unref?.(),ye.set(ve,Ye=>{clearTimeout(ke),C(Ye)}),Pe=n(()=>{clearTimeout(ke),C(void 0)},"onExit"),v.proc.once("exit",Pe);const je={type:"heap-snapshot",id:ve,file:B,...Me?{available:Me}:{},...c!==void 0?{maxHeapBytes:Math.floor(c*1048576)}:{}};tell(v.proc,je)||Pe()}).finally(()=>{ye.delete(ve),Pe&&v.proc.off("exit",Pe)});if(!k){a(504,{ok:!1,pod:v.id,error:"the pod did not finish the snapshot (it exited, or took longer than 10 minutes)"});return}k.ok?console.log(`[parent] Child#${v.id} wrote a ${Math.round((k.bytes??0)/1048576)} MB heap snapshot in ${k.ms} ms \u2192 ${k.file}`):console.warn(`[parent] Child#${v.id} heap snapshot not taken: ${k.refused??k.error}`),a(k.ok?200:k.refused?409:500,{ok:k.ok,pod:v.id,pid:v.proc.pid??0,service:SERVICE_NAME,bundle:path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),...Me?{available:Me}:{},...k.file?{file:k.file,bytes:k.bytes,ms:k.ms}:{},...k.live!==void 0?{live:k.live}:{},...k.gen!==void 0?{gen:k.gen,closedAlive:k.closedAlive??[]}:{},...k.refused?{refused:k.refused}:{},...k.error?{error:k.error}:{}});return}const l=matchGatewayRoute(e);if(l?.prependPrefix&&!e.url?.startsWith(l.prependPrefix)&&(e.url=l.prependPrefix+(e.url??"/")),l?.target){applyGatewayMiddleware(e),u.web(e,o,{target:l.target,autoRewrite:typeof l.target=="string",changeOrigin:!0},a=>{console.error(`[parent] proxy error to ${l.target}:`,a),o.statusCode=502,o.setHeader("content-type","text/plain; charset=utf-8"),o.end(`Upstream error from ${l.target}.`)});return}if(SERVICE_PREFIX){if(!e.url?.startsWith(SERVICE_PREFIX)){o.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),o.end(`Not found. This service is mounted at ${SERVICE_PREFIX}/`);return}e.url=e.url.slice(SERVICE_PREFIX.length)||"/"}applyGatewayMiddleware(e);const d=Q();if(!d){o.statusCode=503,o.setHeader("content-type","text/plain; charset=utf-8");const a=m.map(r=>`#${r.id}: ${r.lastError??"no error recorded"}`).join(`
19
- `);o.end(`No healthy children available. POST /webpack/reload to recover.
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}f(importFresh,"importFresh"),i(importFresh,"importFresh");function debounce(a,_){let g=null;return(...S)=>{g&&clearTimeout(g),g=setTimeout(()=>a(...S),_)}}if(f(debounce,"debounce"),i(debounce,"debounce"),process.env.APP_RUNNER==="1"){(0,stdio_guard_1.guardBrokenStdio)();const a=i(g=>{if(!inspector.url())try{inspector.open(g,"127.0.0.1",!1)}catch(F){console.warn(`[child] inspector.open(${g}) failed (port taken by another devserver?) \u2014 falling back to a random port:`,F.message);try{inspector.open(0,"127.0.0.1",!1)}catch{}}const S=inspector.url();S&&tell(process,{type:"inspector-url",url:S})},"openInspector"),_=process.env.CHILD_DEBUG_PORT;if(_!==void 0&&_!==""){const g=Number(_);Number.isInteger(g)&&(g===0||g>1024)&&a(g)}try{require("@lensmcp/node-instrumentation/register")}catch{}(async()=>{let g=null,S=!1,F,re=!1;const Le=(0,hot_swap_registries_1.registryPruningEnabled)(),ce=i((t,n)=>{const c=(0,hot_swap_registries_1.describePrune)(t,n);c&&console.log(c)},"logPrune");let H={app:null,handler:i((t,n)=>{n.statusCode=503,n.end("starting")},"handler"),inflight:0};const le=(()=>{const t=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(t)&&t>=0?t:15*6e4})(),T=i(t=>{const n=globalThis.__lensmcpActiveWork;if(typeof n!="function")return{count:0};try{const c=n(t);return{count:Number(c?.count??0),...c?.oldestStartedAt?{oldestStartedAt:c.oldestStartedAt}:{}}}catch{return{count:0}}},"activeWork"),ve=i(t=>{const n=globalThis.__lensmcpStopWorkIntake;if(typeof n=="function")try{return n(t)}catch{return}},"stopWorkIntake"),de=i(t=>{const n=globalThis.__lensmcpWorkIntakeReport;if(!(t===void 0||typeof n!="function"))try{return n(t)??void 0}catch{return}},"workIntakeReport"),ye=(()=>{const t=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(t)&&t>=1?Math.floor(t):1})(),x=new Set,Q=(()=>{const t=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(t)&&t>=0?t:3e4})(),j=i(t=>{if(!t.abandoned?.size)return 0;const n=Date.now();for(const[c,p]of t.abandoned)(c.writableEnded||n-p>=Q)&&t.abandoned.delete(c);return t.abandoned.size},"abandonedRunning"),oe=i(t=>{let n=0;for(const c of t.open??[])c.headersSent||(n+=1);return{unanswered:n+j(t),streams:Math.max(0,t.inflight-n),work:T(t.workGen).count}},"owedBy"),ne=i((t,n,c=`${n}s`)=>`${t} ${t===1?n:c}`,"plural");async function Ie(){if(Q<=0)return;const t=Date.now();let n=!1;for(;!(x.size<ye);){const c=x.values().next().value;if(!c||c.closed)break;const p=oe(c);if(p.unanswered===0&&p.work===0)break;const m=(c.drainingSince??t)+Q-Date.now();if(m<=0)break;n||(n=!0,console.log(`[child] swap held \u2014 the app replaced ${Math.round((Date.now()-(c.drainingSince??t))/100)/10}s ago is still `+[p.unanswered?`answering ${ne(p.unanswered,"request")}`:"",p.work?`running ${ne(p.work,"background job")}`:""].filter(Boolean).join(" and ")+`, and this pod keeps at most ${ye} replaced app(s) alive (LENSMCP_SWAP_MAX_DRAINING). The new build is applied when it is done \u2014 in ${Math.ceil(m/1e3)}s at the latest (LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS).`)),await new Promise(E=>{setTimeout(E,Math.min(100,m)).unref?.()})}n&&console.log(`[child] swap resumed after ${Date.now()-t}ms`)}f(Ie,"xe"),i(Ie,"holdForOwedWork");const R=(0,swap_recycle_1.swapRecyclePolicy)();let pe,se=0;const We=(()=>{const t=Number(process.env.LENSMCP_POD_RETIRE_NOTICE_MS);return Number.isFinite(t)&&t>=0?t:3500})();let h=!1,b=!1;const v=(0,pod_memory_1.podMemoryPolicy)();let B=0;const O=new Set;let ue=!1;const U=i(()=>{if(!ue)return;let t=0;for(const n of O)n.deref()===void 0?O.delete(n):t+=1;return t},"liveContainers"),k=(0,pod_memory_1.createPodMemoryMonitor)({policy:v,state:i(()=>({gen:H.gen??0,swaps:se,...pe===void 0?{}:{baseline:pe},busy:S||re||I.size>0,lastBusyAt:Y}),"state"),send:i(t=>{tell(process,t)},"send"),containers:U,counter:(0,pod_memory_1.createLiveObjectCounter)(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH)),onRetained:i(()=>we(),"onRetained")}),G=i(()=>((0,pod_memory_1.fullGc)()&&k.tracker.noteGc(),process.memoryUsage().heapUsed),"liveHeap"),L=(()=>{if(!(0,error_stack_release_1.errorFrameReleaseEnabled)())return null;try{const t=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH))+path.sep,n=`${path.sep}node_modules${path.sep}`,c=new Set(Object.keys(require.cache));return(0,error_stack_release_1.createErrorFrameReleaser)(require.cache,{skip:i(p=>c.has(p)||p.startsWith(t)&&!p.slice(t.length).includes(n)&&!p.slice(t.length).startsWith(`node_modules${path.sep}`),"skip")})}catch{return null}})();let me=!1;function be(){if(!(!L||me))try{const t=L();t.errors>0&&console.log(`[child] read the stack of ${t.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(t){console.error("[child] could not release library error frames:",t),me=!0}}f(be,"Ne"),i(be,"releaseLibraryErrorFrames");const I=new Map;let Y=Date.now();const he=i(()=>R.settleMs<=0||!S&&!re&&I.size===0&&Date.now()-Y>=R.settleMs,"settled");let K;function ie(t){if(!(!R.enabled||h||b)){if(R.settleMs<=0){Z(t);return}K&&clearTimeout(K),K=setTimeout(()=>{K=void 0,he()?Z(t):ie(t)},R.settleMs),K.unref?.()}}f(ie,"de"),i(ie,"recycleCheckWhenSettled");const Me=i(()=>{if(R.stuckCloseMs<=0)return 0;const t=Date.now();let n=0;for(const c of I.values())t-c>=R.stuckCloseMs&&(n+=1);return n},"stuckCloses");function Z(t){if(!R.enabled||h||b||!process.send)return;const n=v8.getHeapStatistics().heap_size_limit,c=i(m=>{const E=k.oldestRetained();return{swaps:se,usedBytes:m,limitBytes:n,stuckCloses:Me(),settled:he(),...pe===void 0?{}:{baselineBytes:pe},...E?{retained:{generation:E.gen,ageMs:Date.now()-E.closedAt,gcs:E.gcs}}:{}}},"state");if(!(0,swap_recycle_1.recycleReason)(R,c(process.memoryUsage().heapUsed)))return;const p=(0,swap_recycle_1.recycleReason)(R,c(G()));p&&(h=!0,console.log(`[child] asking for a fresh pod ${t} \u2014 ${p}. 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:p}))}f(Z,"re"),i(Z,"considerRecycle");let fe;function we(){if(!R.enabled||R.retainedMs<=0||h||b)return;const t=k.oldestRetained();if(!t)return;const n=t.closedAt+R.retainedMs-Date.now();if(n<=0){Z("with a closed generation still in memory");return}fe||(fe=setTimeout(()=>{fe=void 0,k.measure("retention-check").catch(()=>{})},n),fe.unref?.())}f(we,"Oe"),i(we,"retainedRecycleCheck");function _e(t,n){const c={};n&&(c.module=n),t&&(c.app=t);try{const p=t?.app;if(p&&typeof p=="object"&&(c.nestApp=p,p.container&&typeof p.container=="object")){c.container=p.container;const m=rootModuleOf(p.container);m&&(c.rootModule=m)}}catch{}return c}f(_e,"we"),i(_e,"generationTargets");async function V(t,n){if(t.closed||(t.closed=!0,x.delete(t),n&&console.error(`[child] ${n}`),!t.app))return;I.set(t,Date.now());const c=R.enabled&&R.stuckCloseMs>0?setTimeout(()=>{I.has(t)&&(console.error(`[child] a previous app has been closing for ${Math.round(R.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.`),Z("with a previous app stuck in close()"))},R.stuckCloseMs):void 0;c?.unref?.();const p=t.app;try{await t.app.close()}catch(m){console.error("[child] error closing a previous app:",m)}finally{I.delete(t),Y=Date.now(),c&&clearTimeout(c),t.app=null,t.abandoned=void 0,t.handler=(m,E)=>{E.statusCode=503,E.end("closed")},t.gen!==void 0&&k.closed(t.gen,se,_e(p,t.module)),t.module=void 0}if(t.superseded){try{ce((0,hot_swap_registries_1.pruneRegistries)(t.superseded,"serve"),"after closing the previous app")}catch(m){console.error("[child] could not release the previous app's class registrations:",m)}t.superseded=void 0}ie("after closing the previous app")}f(V,"oe"),i(V,"closeGeneration");async function ke(t){const n=Date.now();t.drainingSince=n;const c=i(()=>({inflight:t.inflight+j(t),work:T(t.workGen).count}),"busy"),p=c();if(p.inflight>0||p.work>0){for(;x.size>=ye;){const $=x.values().next().value;if(!$)break;const P=oe($),te=Math.round((Date.now()-($.drainingSince??n))/1e3);if(P.unanswered===0&&P.streams===0&&P.work===0){await V($);continue}await V($,`closing a still-draining generation early \u2014 ${x.size} were pending and the cap is ${ye} (each holds a whole app: DI container, DB pool, queue workers). `+(P.unanswered>0||P.work>0?`It was replaced ${te}s ago and had still not answered ${ne(P.unanswered,"request")}`+(P.work?` or finished ${ne(P.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 ${Q}ms) to wait longer for them. `:`It held only ${ne(P.streams,"open stream")}; their clients reconnect to the new app. `)+"Raise LENSMCP_SWAP_MAX_DRAINING if this pod legitimately needs more.")}x.add(t)}for(;le>0&&Date.now()-n<le;){if(t.closed)return;const $=c();if($.inflight===0&&$.work===0)break;await new Promise(P=>{setTimeout(P,250).unref?.()})}if(t.closed)return;const m=c(),E=de(t.workGen);m.inflight>0||m.work>0?console.error(`[child] swap drain expired after ${Date.now()-n}ms \u2014 closing the previous app with ${m.inflight} in-flight request(s) and ${m.work} background job(s) still running. `+(E?`Previous app still processing ${E.running} queue job(s); ${E.takenAfterStop} were taken after the swap. `:"")+`A queue job killed here keeps its lock until the TTL lapses. Raise LENSMCP_SWAP_DRAIN_MS (currently ${le}ms) if this is legitimate work.`):(Date.now()-n>250||E?.runningAtStop||E?.takenAfterStop)&&console.log(`[child] previous app drained in ${Date.now()-n}ms \u2014 closing it`+(E?` (it finished ${E.finishedAfterStop} queue job(s) after the swap; ${E.takenAfterStop} were taken after the swap)`:"")),await V(t)}f(ke,"Ge"),i(ke,"drainThenClose");async function J(){if(S)return re=!0,console.log("[child] Reload deferred \u2014 will re-swap after current swap completes"),g;S=!0,Y=Date.now(),await Ie(),process.removeAllListeners("uncaughtException"),process.removeAllListeners("unhandledRejection"),process.on("uncaughtException",(A,X)=>{console.error(`[child] uncaughtException (${X}):`,A)}),process.on("unhandledRejection",A=>{const X=A instanceof Error?A.stack||A.message:String(A);X.includes("FronteggContextScope")||X.includes("populateLoggerMetadata")||console.error("[child] unhandledRejection:",A)});let t;if(Le)try{t=(0,hot_swap_registries_1.captureRegistries)()}catch{t=void 0}const n=global.__lensmcpBeginWorkGeneration,c=typeof n=="function"?n():void 0;try{try{await importFresh(BUNDLE_PATH)}catch(A){if(!(A instanceof SyntaxError))throw A;console.warn(`[child] bundle was unreadable mid-write (${A.message}) \u2014 retrying the swap once`),await new Promise(X=>setTimeout(X,400)),await importFresh(BUNDLE_PATH)}}catch(A){throw S=!1,Y=Date.now(),A}if(typeof global.createChildApp!="function")throw S=!1,Y=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 p;if(t)try{p=(0,hot_swap_registries_1.supersededSince)(t),ce((0,hot_swap_registries_1.pruneRegistries)(p,"build"),"at the swap")}catch(A){console.error("[child] could not release superseded class registrations:",A)}let m;try{m=await global.createChildApp()}catch(A){throw S=!1,Y=Date.now(),takeImportedModule(),A}const E=H;p?.size&&(E.app?E.superseded=p:ce((0,hot_swap_registries_1.pruneRegistries)(p,"serve"),"at the swap")),g=m;const $=takeImportedModule();H={app:m,handler:m.handler,inflight:0,gen:++B,...$?{module:$}:{},...c===void 0?{}:{workGen:c}};const P=_e(m,void 0).container;P&&(O.add(new WeakRef(P)),ue=!0);const te=E.app&&c!==void 0?ve(c):void 0;return console.log("[child] Swapped to fresh app (previous draining in background)"+(te?.workers?`; its ${te.workers} queue worker(s) stopped taking new jobs, previous app still processing ${te.runningAtStop} job(s)`:"")),be(),E.app&&(se+=1,ke(E).catch(A=>console.error("[child] background close error:",A)),setTimeout(()=>Z("30s after a hot swap"),3e4).unref?.(),k.swapped(E.gen,()=>E.closed===!0&&!I.has(E))),S=!1,Y=Date.now(),re?(re=!1,J()):m}f(J,"q"),i(J,"swapNow");const Fe=debounce(async()=>{try{console.log("[child] /webpack/reload"),await J()}catch(t){console.error("[child] reload failed:",t)}},250),q=http.createServer((t,n)=>{if(t.method==="POST"&&t.url==="/webpack/reload"){n.writeHead(200,{"content-type":"application/json"}),n.end(JSON.stringify({ok:!0})),Fe();return}if(t.method==="GET"&&t.url==="/__lensmcp/alive"){const p=t.headers["x-internal-token"],m=process.env.LENSMCP_SERVICE_KEY;if(m&&p!==m){n.writeHead(404,{"content-type":"text/plain"}),n.end("not found");return}const E=T();n.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),n.end(JSON.stringify({ok:!0,pid:process.pid,swapping:S,inflight:H.inflight,oldestInflightAt:H.oldestAt,activeWork:E.count,oldestWorkAt:E.oldestStartedAt,keyFingerprint:serviceKeyFingerprint(),...F?{watcher:F}:{},...Number.isFinite(Number(process.env.LENSMCP_POD_GENERATION))&&process.env.LENSMCP_POD_GENERATION?{podGeneration:Number(process.env.LENSMCP_POD_GENERATION)}:{}}));return}const c=H;c.inflight+=1,(c.open??=new Set).add(n),c.oldestAt===void 0&&(c.oldestAt=Date.now()),n.on("close",()=>{c.inflight-=1,c.open?.delete(n),Q>0&&!c.closed&&!n.headersSent&&!n.writableEnded&&((c.abandoned??=new Map).set(n,Date.now()),c.abandoned.size>256&&j(c)),c.inflight===0&&(c.oldestAt=void 0),k.activity()}),c.handler(t,n)});q.keepAliveTimeout=0;const W=process.env.CHILD_SOCK_PATH;process.on("disconnect",()=>{cleanupSock(W),process.exit(0)});try{const t=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH);if((0,schema_first_instance_1.schemaPrewarmEnabled)())try{const n=(0,schema_first_instance_1.prewarmZodFor)(t);n?.created&&console.log(`[child] zod${n.version?` ${n.version}`:""}: built ${n.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 n=(0,redis_disconnect_fix_1.finishStrandedDisconnectsFor)(t);n?.patched&&console.log(`[child] ioredis${n.versions.length?` ${n.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 J(),pe=(await k.booted()).live,console.log(`[child] Using bundle: ${t}`),claimSock(W),q.listen(W,()=>{console.log(`[child] Listening on ${W}`),tell(process,{type:"ready",socketPath:W})})}catch(t){console.error("[child] Startup error:",t),tell(process,{type:"boot-error",error:String(t?.stack||t)}),process.exitCode=1;return}process.on("message",async t=>{if(!(!t||typeof t!="object")){if(t.type==="debug-open"){const n=Number(t.port);a(Number.isInteger(n)&&n>1024?n:0);return}if(t.type==="watcher"){const n=t.testimony;n&&typeof n=="object"&&(F=n);return}if(t.type==="heap-snapshot"){ee(t);return}if(t.type==="recycle-declined"){h=!1;return}if(t.type==="retire"){ge();return}if(t.type==="reload"){if(b)return;try{const n=Date.now();await J(),tell(process,{type:"reloaded",socketPath:W,swap:{generation:B,swaps:se,swapMs:Date.now()-n,draining:x.size}})}catch(n){console.error("[child] reload error:",n),tell(process,{type:"reload-error",error:String(n?.stack||n)})}}}});let Ee=!1;async function ee(t){const n=i(c=>{tell(process,{type:"heap-snapshot-result",id:t.id,...c})},"reply");if(Ee)return n({ok:!1,refused:"a snapshot of this pod is already being written"});Ee=!0;try{const c=G(),p=k.tracker.views().map(P=>P.gen),m=(0,heap_snapshot_1.heapSnapshotPolicy)();t.maxHeapBytes&&(m.maxHeapBytes=t.maxHeapBytes);const E=(0,heap_snapshot_1.heapSnapshotRefusal)(m,{live:c,...t.available?{available:t.available}:{}});if(E)return n({ok:!1,refused:E,live:c});console.log(`[child] writing a heap snapshot (${Math.round(c/1048576)} MB live) \u2014 the pod pauses while V8 serialises it`);const $=await(0,heap_snapshot_1.writeHeapSnapshot)(t.file);n({ok:!0,file:t.file,bytes:$.bytes,ms:$.ms,live:c,gen:H.gen??0,closedAlive:p})}catch(c){n({ok:!1,error:c?.message??String(c)})}finally{Ee=!1}}f(ee,"ne"),i(ee,"takeHeapSnapshot");async function ge(t="a fresh pod has taken over"){if(b)return;b=!0,k.stop(),console.log(`[child] retiring \u2014 ${t}; finishing in-flight work, then exiting`);const n=ve(Number.POSITIVE_INFINITY);n?.workers&&console.log(`[child] its ${n.workers} queue worker(s) stopped taking new jobs, still processing ${n.runningAtStop} job(s)`);try{fs.writeFileSync(sockRetiringPath(W),String(process.pid),{flag:"w",mode:384})}catch{}await new Promise(p=>{setTimeout(p,We).unref?.()}),cleanupSock(W),q.close();const c=Date.now();for(;Date.now()-c<le;){q.closeIdleConnections?.();let p=0;for(const m of x)p+=oe(m).unanswered;if(H.inflight+j(H)===0&&p===0&&T().count===0)break;await new Promise(m=>{setTimeout(m,250).unref?.()})}setTimeout(()=>process.exit(0),3e4).unref?.();try{await g?.close()}catch(p){console.error("[child] close error while retiring:",p)}process.exit(0)}f(ge,"_e"),i(ge,"retire"),process.on("beforeExit",()=>{try{inspector?.close?.()}catch{}});const Ce=i(async t=>{console.log(`[child ${t}] shutting down\u2026`);const n=g?.close().catch(p=>console.error("[child] close error:",p)),c=new Promise(p=>q.close(()=>p()));cleanupSock(W),setTimeout(()=>process.exit(0),700).unref(),await Promise.all([n,c]),process.exit(0)},"shutdown");["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(t=>{process.on(t,()=>{if(t==="SIGTERM"&&!b&&(0,handoff_retire_1.handoffRetireRequested)(SOCK_DIR,POD_GENERATION)){ge("this generation was handed over to a newer one");return}inspector?.close?.(),Ce(t)})})})()}else{let a=f(function(h){j.push(h),j.length>Q&&j.splice(0,j.length-Q),ye?.write((0,inspector_secret_1.redactInspectorUrls)(h.replace(x,"")));for(const b of oe)try{const v=b.plain?h.replace(x,""):h;b.res.write(b.redact?(0,inspector_secret_1.redactInspectorUrls)(v):v)}catch{oe.delete(b)}},"pe");i(a,"emitLogLine");const _=12,g=process.env.LENSMCP_PROJECT||SERVICE_NAME||"service",S=(0,pod_memory_events_1.createPodMemoryPublisher)(process.env.LENSMCP_EVENT_FILE),F=i(h=>({project:g,service:SERVICE_NAME||g,pod:h.id,pid:h.proc.pid??0,podGeneration:POD_GENERATION}),"podIdentity"),re=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[31m"],Le="\x1B[0m",ce=Math.max(1,Number(process.env.CHILD_COUNT||1)),H=LENSMCP_WS_KEY||path.basename(process.cwd()),le=i(h=>(0,process_name_1.namedExecPath)((0,process_name_1.processName)(H,SERVICE_NAME||"service",h)),"execPathFor");let T=(()=>{const h=Number(process.env.LENSMCP_DEBUG_PORT||"");return Number.isInteger(h)&&h>1024?h:0})();const ve=20;T&&(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 (${T}+slot, workers ${T}+${ve}+i). Any account on this host can connect to 127.0.0.1:${T} 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 de=process.env.LENSMCP_LOG_FILE||"",ye=de?(()=>{try{fs.mkdirSync(path.dirname(de),{recursive:!0});const h=fs.createWriteStream(de,{flags:"a",mode:384});try{fs.chmodSync(de,384)}catch{}return h}catch(h){return console.warn(`[parent] cannot open log file ${de}:`,h.message),null}})():null,x=/\x1b\[[0-9;]*m/g,Q=2e3,j=[],oe=new Set,ne=(0,devserver_transport_1.gatewayManaged)();for(const h of["log","info","warn","error"]){const b=console[h].bind(console),v=h==="log"||h==="info"?process.stdout:process.stderr;console[h]=(...B)=>{b(...B.map(O=>typeof O=="string"?(0,inspector_secret_1.forStream)(v,ne,O):O)),a(B.map(O=>typeof O=="string"?O:util.inspect(O)).join(" ")+`
13
+ `)}}const Ie=i(h=>re[(h-1)%re.length],"colorFor"),R=i(h=>{if(ce===1)return"";const b=`[child#${h}] `;return`${Ie(h)}${b}${Le}`},"tagFor"),pe=i(h=>h.startsWith("{")&&h.endsWith("}"),"isJsonLog"),se=i((h,b,v)=>{const B=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:i(U=>`
14
+ `+String(U),"stack")}}),O=i((U,k)=>{const G=U==="stdout"?process.stdout:process.stderr;try{v?.(k)}catch{}const L=pe(k)?B(k):`${k}
15
+ `;G.write((0,inspector_secret_1.forStream)(G,ne,`${b}${L}`)),a(`${b}${L}`)},"write"),ue=i((U,k)=>{if(!U)return;const G=readline.createInterface({input:U});G.on("line",L=>O(k,L)),G.on("close",()=>{})},"attach");ue(h.stdout,"stdout"),ue(h.stderr,"stderr")},"wireProcLogging"),We=i(h=>se(h.proc,R(h.id),b=>h.tail.push(b)),"wireChildLogging");(async()=>{ensureOwnerOnlyDir(SOCK_DIR);const h=httpProxy.createProxyServer({});let b=Number(process.env.PORT)||0;b||(b=9090);const v=[],B=new Set;function O(){let e=0;for(;B.has(e);)e++;return B.add(e),e}f(O,"I"),i(O,"allocDebugSlot");let ue=1,U=0,k=!1,G=ce,L=[],me=0;const be=(()=>{const e=Number(process.env.LENSMCP_POD_BOOT_GRACE_MS);return Number.isFinite(e)&&e>=0?e:12e4})(),I=i(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"childExited"),Y=i(e=>e.booting&&!I(e)&&Date.now()-e.spawnedAt<be,"stillBooting");function he(){return v.filter(e=>e.healthy&&typeof e.socketPath=="string")}f(he,"he"),i(he,"healthyChildren");let K,ie=0,Me;const Z={project:g,service:SERVICE_NAME||g,podGeneration:POD_GENERATION};function fe(e){const r=(0,service_build_events_1.buildAccountOf)(e.building);r&&r.startedAt!==ie&&(ie=r.startedAt,S.publish((0,service_build_events_1.buildServiceBuildEvent)(Z,"started",r,{root:process.cwd()})));const l=(0,service_build_events_1.buildAccountOf)(e.failed);l&&(ie=0,S.publish((0,service_build_events_1.buildServiceBuildEvent)(Z,"failed",l,{root:process.cwd()})))}f(fe,"fe"),i(fe,"recordBuildProgress");function we(e){if(!e||typeof e!="object")return;const r=e;if(r.schemaVersion===1){fe(r),"failed"in r&&delete r.failed,K=r;for(const l of v)tell(l.proc,{type:"watcher",testimony:r})}}f(we,"Oe"),i(we,"recordWatcherTestimony");function _e(e,r=256*1024){return new Promise(l=>{let u="",s=!1;e.on("data",o=>{s||(u+=o,u.length>r&&(s=!0))}),e.on("end",()=>{if(s||!u)return l(void 0);try{l(JSON.parse(u))}catch{l(void 0)}}),e.on("error",()=>l(void 0))})}f(_e,"we"),i(_e,"readJsonBody");function V(){const e=he();if(e.length===0)return null;const r=U%e.length;return U=(U+1)%e.length,e[r]}f(V,"oe"),i(V,"pickChild");function ke(e,r){const l=`Child#${e.id}`,u=SERVICE_NAME||g,s=Date.now();if(r.type==="pod-memory"){const o=r.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)(l,o)}`),S.publish((0,pod_memory_events_1.buildPodMemoryEvent)(F(e),o))}else if(r.type==="pod-memory-retained"){const o=r.retained;if(!o||typeof o.gen!="number")return;e.memory.retained.set(o.gen,{...o,at:s}),console.warn(`[parent] ${(0,pod_memory_1.describeRetained)(l,u,o)}`),S.publish((0,pod_memory_events_1.buildPodRetainedEvent)(F(e),o,s))}else{const o=r.released;if(!o||typeof o.gen!="number")return;e.memory.retained.delete(o.gen),console.log(`[parent] ${(0,pod_memory_1.describeReleased)(l,u,o)}`),S.publish((0,pod_memory_events_1.buildPodReleasedEvent)(F(e),o,s))}}f(ke,"Ge"),i(ke,"recordPodMemory");const J=new Map;let Fe=0;async function q(){const e=ue++,r=childSockPath(e);cleanupSock(r);const l=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&l.unshift("--require","@swc-node/register"),l.push(...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const u=T?O():-1,s=(0,node_child_process_1.fork)(__filename,{env:{...process.env,APP_RUNNER:"1",CHILD_SOCK_PATH:r,...u>=0&&{CHILD_DEBUG_PORT:String(inspectorPortFor(T,u))}},stdio:["inherit","pipe","pipe","ipc"],execArgv:l,execPath:le("pod")}),o={id:e,proc:s,healthy:!1,lastError:null,debugSlot:u,tail:new exit_reason_1.TailBuffer,booting:!0,spawnedAt:Date.now(),bootReloadSeq:me,memory:{history:[],retained:new Map}};return s.on("error",w=>console.error(`[parent] Child#${e}: ${w.message}`)),s.on("message",w=>{if(!w||typeof w!="object")return;const d=w;if(d.type==="ready")o.socketPath=String(d.socketPath),o.healthy=!0,o.booting=!1,console.log(`[parent] Child#${o.id} ready on socket ${o.socketPath}`),K&&tell(s,{type:"watcher",testimony:K}),me!==o.bootReloadSeq&&tell(s,{type:"reload"});else if(d.type==="recycle-request")c(o,String(d.reason||"it has outgrown its bound"));else if(d.type==="inspector-url")o.inspectorUrl=String(d.url),console.log(`[parent] Child#${o.id} Debugger listening on ${d.url}`);else if(d.type==="reloaded"){o.socketPath=String(d.socketPath),o.healthy=!0,console.log(`[parent] Child#${o.id} hot-swapped on socket ${o.socketPath}`);const y=d.swap;y&&typeof y.generation=="number"&&typeof y.swaps=="number"&&S.publish((0,service_build_events_1.buildServiceSwapEvent)(F(o),{generation:y.generation,swaps:y.swaps,swapMs:typeof y.swapMs=="number"?y.swapMs:0,draining:typeof y.draining=="number"?y.draining:0},Me,{root:process.cwd()}))}else d.type==="reload-error"?(o.lastError=String(d.error||"unknown reload error"),console.error(`[parent] Child#${o.id} reload error: ${o.lastError}`),o.healthy=!1):d.type==="boot-error"?(o.lastError=String(d.error||"unknown boot error"),console.error(`[parent] Child#${o.id} boot error: ${o.lastError}`),o.healthy=!1,o.booting=!1):d.type==="pod-memory"||d.type==="pod-memory-retained"||d.type==="pod-memory-released"?ke(o,d):d.type==="heap-snapshot-result"&&J.get(Number(d.id))?.(d)}),s.on("exit",(w,d)=>{o.booting=!1;for(const M of o.memory.retained.values()){const C={gen:M.gen,closedAt:M.closedAt,ageMs:Date.now()-M.closedAt,reason:"pod-exited"};console.log(`[parent] ${(0,pod_memory_1.describeReleased)(`Child#${o.id}`,SERVICE_NAME||g,C)}`),S.publish((0,pod_memory_events_1.buildPodReleasedEvent)(F(o),C,Date.now()))}o.memory.retained.clear(),o.memory.latest&&S.publish((0,pod_memory_events_1.buildPodExitedEvent)(F(o),{code:w,signal:d},Date.now())),o.debugSlot>=0&&(B.delete(o.debugSlot),o.debugSlot=-1);const y=d==="SIGINT"||d==="SIGTERM"||w===0;if(y?console.log(`[parent] Child#${o.id} exited cleanly (code=${w}, signal=${d??"none"})`):(console.error((0,exit_reason_1.crashReport)(`[parent] Child#${o.id} crashed (code=${w}, signal=${d??"none"}, pid=${o.proc.pid}, ${o.healthy?"was serving":"was not ready"})`,w,d,o.tail.snapshot())),o.lastError||(o.lastError=`Child exited abnormally (code=${w}, signal=${d??"none"})`)),o.healthy=!1,cleanupSock(o.socketPath,o.proc.pid),o.socketPath=void 0,!y&&!k){const M=v.indexOf(o);M>=0&&v.splice(M,1);const C=Date.now();if(L=L.filter(z=>C-z<3e4),L.length>=5){console.error(`[parent] crash-loop detected (${L.length} respawns/30s) \u2014 pausing auto-respawn; POST /webpack/reload to retry`);return}L.push(C),setTimeout(()=>{const z=v.filter(Te=>Te.proc.killed===!1).length;!k&&z<G&&(console.log(`[parent] respawning a crashed pod (${z}/${G} live)`),q().catch(()=>{}))},1500).unref?.()}}),v.push(o),We(o),o}f(q,"K"),i(q,"spawnChild");async function W(e){G=Math.max(G,e);const r=v.filter(u=>u.proc.killed===!1),l=e-r.length;for(let u=0;u<l;u++)await q()}f(W,"U"),i(W,"ensurePoolSize");async function Ee(){const e=v.filter(r=>(!r.healthy||typeof r.socketPath!="string")&&!Y(r));await Promise.all(e.map(async r=>{try{r.proc.kill("SIGTERM")}catch{}cleanupSock(r.socketPath,r.proc.pid),r.socketPath=void 0;const l=v.indexOf(r);l>=0&&v.splice(l,1),await q()}))}f(Ee,"Ee"),i(Ee,"respawnUnhealthy");const ee=new Set;let ge=!1,Ce=0;const t=3e4,n=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return(Number.isFinite(e)&&e>=0?e:15*6e4)+6e4})();async function c(e,r){const l=i(s=>{console.log(`[parent] Child#${e.id} asked for a fresh pod (${r}) \u2014 not now: ${s}`),tell(e.proc,{type:"recycle-declined"})},"decline");if(k||!v.includes(e))return;if(ge)return l("another pod is already being replaced");const u=Date.now()-Ce;if(u<t)return l(`a pod was replaced ${Math.round(u/1e3)}s ago`);ge=!0,console.log(`[parent] Child#${e.id} asked for a fresh pod \u2014 ${r}. Starting one; Child#${e.id} keeps serving until it is ready.`);try{const s=await q(),o=Date.now()+be;for(;!s.healthy&&!s.lastError&&!I(s)&&Date.now()<o;)await new Promise(y=>{setTimeout(y,100).unref?.()});if(k)return;if(!s.healthy){const y=v.indexOf(s);y>=0&&v.splice(y,1);try{s.proc.kill("SIGTERM")}catch{}return l(`its successor Child#${s.id} did not come up (${s.lastError??"no answer in time"})`)}const w=v.indexOf(e);w>=0&&v.splice(w,1),e.healthy=!1,ee.add(e);const d=setTimeout(()=>{if(!I(e)){console.error(`[parent] Child#${e.id} was still running ${n}ms after it was retired \u2014 killing it`);try{e.proc.kill("SIGKILL")}catch{}}},n);if(d.unref?.(),e.proc.once("exit",()=>{clearTimeout(d),ee.delete(e)}),!tell(e.proc,{type:"retire"}))try{e.proc.kill("SIGTERM")}catch{}Ce=Date.now(),console.log(`[parent] Child#${s.id} took over from Child#${e.id} (pid ${e.proc.pid} \u2192 ${s.proc.pid})`)}catch(s){l(`could not start a successor: ${s?.message??String(s)}`)}finally{ge=!1}}f(c,"a"),i(c,"recyclePod");const p=[];function m(e){const r=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH)),l=path.join(r,`${e}.js`);if(!fs.existsSync(l))return console.error(`[parent] Worker "${e}" bundle not found: ${l}`),null;const u=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&u.unshift("--require","@swc-node/register");try{u.push("--require",require.resolve("@lensmcp/node-instrumentation/register"))}catch{}const s=inspectorPortFor(T||9229,ve+Math.max(0,WORKER_NAMES.indexOf(e)));u.push(T?`--inspect=127.0.0.1:${s}`:`--inspect-port=127.0.0.1:${s}`,...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const o=(0,node_child_process_1.fork)(l,{env:process.env,stdio:["inherit","pipe","pipe","ipc"],execArgv:u,execPath:le(`w-${e}`)}),w={name:e,proc:o,debugPort:s};return p.push(w),o.on("error",d=>console.error(`[parent] Worker "${e}": ${d.message}`)),se(o,`\x1B[35m[worker:${e}] \x1B[0m`,d=>{const y=/Debugger listening on (wss?:\/\/\S+)/.exec(d);y&&(w.inspectorUrl=y[1])}),o.on("exit",(d,y)=>{y==="SIGINT"||y==="SIGTERM"||d===0||console.error(`[parent] Worker "${e}" crashed (code=${d}, signal=${y??"none"})`);const M=p.indexOf(w);M>=0&&p.splice(M,1)}),console.log(`[parent] Worker "${e}" started (pid=${o.pid})`),w}f(m,"y"),i(m,"spawnWorkerProcess");const E=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(e)&&e>=0?e:15*6e4})(),$=(()=>{const e=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(e)&&e>=1?Math.floor(e):1})(),P=new Set,te=i(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"workerExited");function A(e,r){if(P.delete(e),!te(e)){console.error(`[parent] Worker "${e.name}" (pid=${e.proc.pid}) ${r} \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{}}}f(A,"R"),i(A,"killDrainingWorker");function X(e){try{e.proc.kill("SIGTERM")}catch{}if(te(e))return;const r=[...P].filter(u=>u.name===e.name);for(;r.length>=$;)A(r.shift(),`was still running when a later reload replaced its successor (cap ${$})`);P.add(e);const l=setTimeout(()=>A(e,`was still running ${E}ms after SIGTERM`),E);l.unref?.(),e.proc.once("exit",()=>{clearTimeout(l),P.delete(e)})}f(X,"B"),i(X,"retireWorker");function Be(){for(const e of[...p])X(e);p.length=0;for(const e of WORKER_NAMES)m(e)}f(Be,"Ke"),i(Be,"restartWorkers");const Je=debounce(async()=>{me+=1;const e=he();if(e.length>0){console.log(`[parent] Forwarding reload to ${e.length} child(ren)`);for(const r of e)tell(r.proc,{type:"reload"})}await Ee(),WORKER_NAMES.length>0&&Be()},200),Pe=i(async(e,r)=>{if(e.method==="POST"&&e.url==="/webpack/reload"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,r);r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({ok:!0})),_e(e).then(s=>{const o=s;Me=(0,service_build_events_1.buildAccountOf)(o?.build),ie=0,we(o?.watcher)}),Je();return}if(e.method==="POST"&&e.url==="/webpack/watching"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,r);const s=await _e(e);we(s),r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({ok:!0,relayed:K!==void 0}));return}if(e.method==="POST"&&e.url==="/webpack/scale"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,r);let s="";e.on("data",o=>{s+=o}),e.on("end",async()=>{let o=0;try{o=Number(JSON.parse(s||"{}").pods)||0}catch{}o=Math.max(1,Math.min(o,16)),await W(o),r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({ok:!0,pods:o}))});return}if(e.method==="GET"&&e.url?.startsWith("/webpack/logs")){const s=new URL(e.url,"http://localhost").searchParams,o=Math.min(Math.max(Number(s.get("tail")??"100")||0,0),Q),w=s.get("follow")!=="0",d=s.get("plain")==="1",y=!(0,devserver_transport_1.isOwnerOnlyTransport)(e);r.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-cache"});const M=o===0?"":j.slice(-o).join(""),C=d?M.replace(x,""):M;if(r.write(y?(0,inspector_secret_1.redactInspectorUrls)(C):C),!w){r.end();return}const z={res:r,plain:d,redact:y};oe.add(z),e.on("close",()=>oe.delete(z));return}if(e.method==="POST"&&e.url?.startsWith("/webpack/debug")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){r.writeHead(404,{"content-type":"application/json"}),r.end(JSON.stringify({error:"not found"}));return}const s=Number(new URL(e.url,"http://localhost").searchParams.get("port")||"");Number.isInteger(s)&&s>1024&&(T=s),T||(T=9229);const o=v.filter(d=>d.proc.exitCode===null&&d.proc.signalCode===null);for(const d of o)d.debugSlot<0&&(d.debugSlot=O()),tell(d.proc,{type:"debug-open",port:inspectorPortFor(T,d.debugSlot)});for(const d of p)try{d.proc.kill("SIGUSR1")}catch{}const w=Date.now()+2e3;for(;Date.now()<w&&o.some(d=>!d.inspectorUrl);)await new Promise(d=>setTimeout(d,50));r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({ok:!0,basePort:T,fixedPorts:usesFixedInspectorPorts(),pods:o.map(d=>({id:d.id,inspectorUrl:d.inspectorUrl??null})),workers:p.map(d=>({name:d.name,port:d.debugPort||(0,inspector_secret_1.inspectorPortOf)(d.inspectorUrl),inspectorUrl:d.inspectorUrl??null}))},null,2)+`
16
+ `);return}if(e.method==="GET"&&e.url==="/webpack/memory"){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){r.writeHead(404,{"content-type":"application/json"}),r.end(JSON.stringify({error:"not found"}));return}const s=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),o=[...v,...ee].map(w=>({id:w.id,pid:w.proc.pid??0,podGeneration:POD_GENERATION,healthy:w.healthy,retiring:ee.has(w),latest:w.memory.latest??null,history:w.memory.history,retained:[...w.memory.retained.values()]}));r.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),r.end(JSON.stringify({ok:!0,service:SERVICE_NAME,project:g,bundle:{path:s},pods:o},null,2)+`
17
+ `);return}if(e.method==="POST"&&e.url?.startsWith("/webpack/heap")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){r.writeHead(404,{"content-type":"application/json"}),r.end(JSON.stringify({error:"not found"}));return}const s=i((D,$e)=>{r.writeHead(D,{"content-type":"application/json"}),r.end(JSON.stringify($e,null,2)+`
18
+ `)},"reply"),o=new URL(e.url,"http://localhost").searchParams,w=Number(o.get("pod")||""),d=o.has("maxMb")?Number(o.get("maxMb")):void 0;if(d!==void 0&&!(Number.isFinite(d)&&d>0)){s(400,{ok:!1,error:"maxMb takes a positive number of MB"});return}const y=Number.isInteger(w)&&w>0?v.find(D=>D.id===w):he()[0];if(!y||I(y)){s(404,{ok:!1,error:w?`no pod #${w} \u2014 running: ${v.map(D=>`#${D.id}`).join(", ")||"none"}`:"no pod is serving"});return}if(J.size>0){s(409,{ok:!1,refused:"a heap snapshot is already being written for this service"});return}const M=(0,heap_snapshot_1.heapSnapshotPolicy)(),C=(0,heap_snapshot_1.heapSnapshotDir)();let z;try{(0,heap_snapshot_1.ensureHeapDir)(C);const D=(0,heap_snapshot_1.pruneHeapSnapshots)(C,M);D.length&&console.log(`[parent] removed ${D.length} older heap snapshot(s) from ${C}`),z=path.join(C,(0,heap_snapshot_1.heapSnapshotFileName)(SERVICE_NAME||g,y.id,y.proc.pid??0,y.memory.latest?.gen??0,Date.now()))}catch(D){s(500,{ok:!1,error:`cannot prepare ${C}: ${D.message}`});return}const Te=++Fe,Ge=(0,heap_snapshot_1.availableSystemMemory)();let Oe;const N=await new Promise(D=>{const $e=setTimeout(()=>D(void 0),6e5);$e.unref?.(),J.set(Te,et=>{clearTimeout($e),D(et)}),Oe=i(()=>{clearTimeout($e),D(void 0)},"onExit"),y.proc.once("exit",Oe);const Qe={type:"heap-snapshot",id:Te,file:z,...Ge?{available:Ge}:{},...d!==void 0?{maxHeapBytes:Math.floor(d*1048576)}:{}};tell(y.proc,Qe)||Oe()}).finally(()=>{J.delete(Te),Oe&&y.proc.off("exit",Oe)});if(!N){s(504,{ok:!1,pod:y.id,error:"the pod did not finish the snapshot (it exited, or took longer than 10 minutes)"});return}N.ok?console.log(`[parent] Child#${y.id} wrote a ${Math.round((N.bytes??0)/1048576)} MB heap snapshot in ${N.ms} ms \u2192 ${N.file}`):console.warn(`[parent] Child#${y.id} heap snapshot not taken: ${N.refused??N.error}`),s(N.ok?200:N.refused?409:500,{ok:N.ok,pod:y.id,pid:y.proc.pid??0,service:SERVICE_NAME,bundle:path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),...Ge?{available:Ge}:{},...N.file?{file:N.file,bytes:N.bytes,ms:N.ms}:{},...N.live!==void 0?{live:N.live}:{},...N.gen!==void 0?{gen:N.gen,closedAlive:N.closedAlive??[]}:{},...N.refused?{refused:N.refused}:{},...N.error?{error:N.error}:{}});return}const l=matchGatewayRoute(e);if(l?.prependPrefix&&!e.url?.startsWith(l.prependPrefix)&&(e.url=l.prependPrefix+(e.url??"/")),l?.target){applyGatewayMiddleware(e),h.web(e,r,{target:l.target,autoRewrite:typeof l.target=="string",changeOrigin:!0},s=>{console.error(`[parent] proxy error to ${l.target}:`,s),r.statusCode=502,r.setHeader("content-type","text/plain; charset=utf-8"),r.end(`Upstream error from ${l.target}.`)});return}if(SERVICE_PREFIX){if(!e.url?.startsWith(SERVICE_PREFIX)){r.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),r.end(`Not found. This service is mounted at ${SERVICE_PREFIX}/`);return}e.url=e.url.slice(SERVICE_PREFIX.length)||"/"}applyGatewayMiddleware(e);const u=V();if(!u){r.statusCode=503,r.setHeader("content-type","text/plain; charset=utf-8");const s=v.map(o=>`#${o.id}: ${o.lastError??"no error recorded"}`).join(`
19
+ `);r.end(`No healthy children available. POST /webpack/reload to recover.
20
20
 
21
21
  Last errors:
22
- ${a}`);return}u.web(e,o,{target:{socketPath:d.socketPath},headers:{"x-proxy-child-id":String(d.id)}},a=>{console.error(`[parent] proxy error to Child#${d.id}:`,a),d.healthy=!1,d.lastError=String(a?.stack||a),o.statusCode=502,o.setHeader("content-type","text/plain; charset=utf-8"),o.end(`Upstream error from Child#${d.id}. Try /webpack/reload.
23
- ${d.lastError}`)})},"requestHandler");let ue,Se,De;const Te=[];if(GATEWAY_HTTPS){const e=require("./basic-ssl"),o=GATEWAY_ROUTES.map(d=>d.host).filter(d=>!!d),l=(0,checkout_cache_1.checkoutCacheDir)(process.cwd(),"davnx-webpack");Se=e.getCertificateSync(l,SERVICE_NAME||"lensmcp.dev",o),De=e.caCertPath(),ue=require("node:https").createServer({key:Se,cert:Se},Ee)}else ue=http.createServer(Ee);const We=n((e,o,l)=>{const d=matchGatewayRoute(e);if(d?.prependPrefix&&!e.url?.startsWith(d.prependPrefix)&&(e.url=d.prependPrefix+(e.url??"/")),d?.target){u.ws(e,o,l,{target:d.target,changeOrigin:!0},()=>o.destroy());return}const a=Q();if(!a){o.destroy();return}u.ws(e,o,l,{target:{socketPath:a.socketPath}},()=>o.destroy())},"upgradeHandler");ue.on("upgrade",We);const Ue=2e3;let Fe=!1;ue.on("error",e=>{if(e.code==="EADDRINUSE"){Fe||(Fe=!0,console.warn(`[parent] public port ${P} already in use \u2014 continuing on the unix-socket pool only (gateway routing is unaffected) and retrying the bind every ${Ue/1e3}s. Give this service a distinct cluster.port if this is not a rolling handoff.`)),setTimeout(()=>{!A&&!ue.listening&&ue.listen(P)},Ue).unref?.();return}console.error("[parent] public server error:",e)}),await pe(te);for(const e of WORKER_NAMES)E(e);SOCKET_ONLY?console.log(`[parent] socket-only: no TCP listener (port ${P} is not bound \u2014 the gateway reaches this service through its socket pool)`):ue.listen(P,()=>{const e=GATEWAY_HTTPS?"https":"http";console.log(`[parent] Listening on ${e}://localhost:${P}`),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(o=>`${o.host??"*"}${o.prefix??"/"}\u2192${o.target??"children"}`).join(" ")}`),De&&(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 ${De}`)),console.log(`POST ${e}://localhost:${P}/webpack/reload to trigger rolling swap/respawn`)});const Re=Number(process.env.INTERNAL_PORT||0);if(Re>0&&!SOCKET_ONLY){const e=n((l,d)=>{const a=Q();if(!a){d.statusCode=503,d.setHeader("content-type","text/plain; charset=utf-8"),d.end("No healthy children available.");return}u.web(l,d,{target:{socketPath:a.socketPath}},r=>{a.healthy=!1,a.lastError=String(r?.stack||r),d.statusCode=502,d.end(`Upstream error from Child#${a.id}.`)})},"internalHandler"),o=http.createServer(e);o.on("upgrade",(l,d,a)=>{const r=Q();if(!r){d.destroy();return}u.ws(l,d,a,{target:{socketPath:r.socketPath}},()=>d.destroy())}),o.on("error",l=>{console.warn(`[parent] internal port ${Re} unavailable (${l.code}).`)}),o.listen(Re,()=>{console.log(`[parent] Internal (service-to-service, no gateway middleware) on http://localhost:${Re}`)}),Te.push(o)}const qe=SOCKET_ONLY?[]:(()=>{try{return JSON.parse(process.env.GATEWAY_EXTRA_PORTS||"[]")}catch{return[]}})();for(const e of qe){if(!Number.isInteger(e)||e===Number(P))continue;const o=GATEWAY_HTTPS?require("node:https").createServer({key:Se,cert:Se},Ee):http.createServer(Ee);o.on("upgrade",We),o.on("error",l=>{console.warn(`[parent] extra port ${e} unavailable (${l.code}) \u2014 main port still up.`)}),o.listen(e,()=>{console.log(`[parent] Also listening on ${GATEWAY_HTTPS?"https":"http"}://localhost:${e}`)}),Te.push(o)}const $e=path.join(SOCK_DIR,"parent.sock");claimSock($e);const Ie=http.createServer(Ee);Ie.on("error",e=>{console.warn(`[parent] control socket unavailable (${e.code}) \u2014 lensmcp logs/debug attach disabled.`)}),Ie.listen($e),Te.push(Ie);const He=n(async e=>{A=!0,console.log(`[${e}] [parent] shutting down\u2026`);const o=sockOwnedByAnother($e);cleanupSock($e);for(const l of Te)if(!(l===Ie&&o))try{l.close()}catch{}for(const l of g)try{l.proc.kill("SIGTERM")}catch{}for(const l of[...V])U(l,"was still draining when its devserver shut down");for(const l of ee)try{l.proc.kill("SIGTERM")}catch{}for(const l of m){try{l.proc.kill("SIGTERM")}catch{}l.socketPath&&cleanupSock(l.socketPath,l.proc.pid)}try{fs.rmdirSync(SOCK_DIR)}catch{}setTimeout(()=>process.exit(0),700).unref()},"shutdown");["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(e=>process.on(e,()=>{He(e)}));const Oe=Number(process.env.LENSMCP_GATEWAY_PID??0);if(Number.isInteger(Oe)&&Oe>0){const e=setInterval(()=>{try{process.kill(Oe,0)}catch(o){if(o.code==="EPERM")return;clearInterval(e),console.error(`[parent] gateway (pid ${Oe}) is gone \u2014 shutting the pod down to avoid an orphan tree.`),He("gateway-gone")}},5e3);e.unref()}})()}
22
+ ${s}`);return}h.web(e,r,{target:{socketPath:u.socketPath},headers:{"x-proxy-child-id":String(u.id)}},s=>{console.error(`[parent] proxy error to Child#${u.id}:`,s),u.healthy=!1,u.lastError=String(s?.stack||s),r.statusCode=502,r.setHeader("content-type","text/plain; charset=utf-8"),r.end(`Upstream error from Child#${u.id}. Try /webpack/reload.
23
+ ${u.lastError}`)})},"requestHandler");let ae,Ae,Ue;const Ne=[];if(GATEWAY_HTTPS){const e=require("./basic-ssl"),r=GATEWAY_ROUTES.map(u=>u.host).filter(u=>!!u),l=(0,checkout_cache_1.checkoutCacheDir)(process.cwd(),"davnx-webpack");Ae=e.getCertificateSync(l,SERVICE_NAME||"lensmcp.dev",r),Ue=e.caCertPath(),ae=require("node:https").createServer({key:Ae,cert:Ae},Pe)}else ae=http.createServer(Pe);const qe=i((e,r,l)=>{const u=matchGatewayRoute(e);if(u?.prependPrefix&&!e.url?.startsWith(u.prependPrefix)&&(e.url=u.prependPrefix+(e.url??"/")),u?.target){h.ws(e,r,l,{target:u.target,changeOrigin:!0},()=>r.destroy());return}const s=V();if(!s){r.destroy();return}h.ws(e,r,l,{target:{socketPath:s.socketPath}},()=>r.destroy())},"upgradeHandler");ae.on("upgrade",qe);const je=2e3;let Ye=!1;ae.on("error",e=>{if(e.code==="EADDRINUSE"){Ye||(Ye=!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 ${je/1e3}s. Give this service a distinct cluster.port if this is not a rolling handoff.`)),setTimeout(()=>{!k&&!ae.listening&&ae.listen(b)},je).unref?.();return}console.error("[parent] public server error:",e)}),await W(ce);for(const e of WORKER_NAMES)m(e);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)`):ae.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(r=>`${r.host??"*"}${r.prefix??"/"}\u2192${r.target??"children"}`).join(" ")}`),Ue&&(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 ${Ue}`)),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=i((l,u)=>{const s=V();if(!s){u.statusCode=503,u.setHeader("content-type","text/plain; charset=utf-8"),u.end("No healthy children available.");return}h.web(l,u,{target:{socketPath:s.socketPath}},o=>{s.healthy=!1,s.lastError=String(o?.stack||o),u.statusCode=502,u.end(`Upstream error from Child#${s.id}.`)})},"internalHandler"),r=http.createServer(e);r.on("upgrade",(l,u,s)=>{const o=V();if(!o){u.destroy();return}h.ws(l,u,s,{target:{socketPath:o.socketPath}},()=>u.destroy())}),r.on("error",l=>{console.warn(`[parent] internal port ${De} unavailable (${l.code}).`)}),r.listen(De,()=>{console.log(`[parent] Internal (service-to-service, no gateway middleware) on http://localhost:${De}`)}),Ne.push(r)}const Xe=SOCKET_ONLY?[]:(()=>{try{return JSON.parse(process.env.GATEWAY_EXTRA_PORTS||"[]")}catch{return[]}})();for(const e of Xe){if(!Number.isInteger(e)||e===Number(b))continue;const r=GATEWAY_HTTPS?require("node:https").createServer({key:Ae,cert:Ae},Pe):http.createServer(Pe);r.on("upgrade",qe),r.on("error",l=>{console.warn(`[parent] extra port ${e} unavailable (${l.code}) \u2014 main port still up.`)}),r.listen(e,()=>{console.log(`[parent] Also listening on ${GATEWAY_HTTPS?"https":"http"}://localhost:${e}`)}),Ne.push(r)}const Se=path.join(SOCK_DIR,"parent.sock");claimSock(Se),(0,handoff_retire_1.clearHandoffRetire)(SOCK_DIR,POD_GENERATION);const Re=http.createServer(Pe);Re.on("error",e=>{console.warn(`[parent] control socket unavailable (${e.code}) \u2014 lensmcp logs/debug attach disabled.`)}),Re.listen(Se),Ne.push(Re);function Ke(){k=!0;const e=[...v,...ee];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 r=sockOwnedByAnother(Se);cleanupSock(Se);for(const s of Ne)if(!(s===Re&&r))try{s.close()}catch{}try{ae.close()}catch{}for(const s of[...p])X(s);p.length=0;for(const s of v)if(!tell(s.proc,{type:"retire"}))try{s.proc.kill("SIGTERM")}catch{}const l=setTimeout(()=>{for(const s of e)if(!I(s)){console.error(`[parent] Child#${s.id} was still running ${n}ms after its generation was retired \u2014 killing it`);try{s.proc.kill("SIGKILL")}catch{}}},n);l.unref?.();const u=i(()=>{if(!(e.some(s=>!I(s))||[...P].some(s=>!te(s)))){clearTimeout(l);for(const s of e)s.socketPath&&cleanupSock(s.socketPath,s.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 s of e)s.proc.once("exit",u);for(const s of P)s.proc.once("exit",u);u()}f(Ke,"Xe"),i(Ke,"retireGeneration");const Ve=i(async e=>{k=!0,console.log(`[${e}] [parent] shutting down\u2026`);const r=sockOwnedByAnother(Se);cleanupSock(Se);for(const l of Ne)if(!(l===Re&&r))try{l.close()}catch{}for(const l of p)try{l.proc.kill("SIGTERM")}catch{}for(const l of[...P])A(l,"was still draining when its devserver shut down");for(const l of ee)try{l.proc.kill("SIGTERM")}catch{}for(const l of v){try{l.proc.kill("SIGTERM")}catch{}l.socketPath&&cleanupSock(l.socketPath,l.proc.pid)}try{fs.rmdirSync(SOCK_DIR)}catch{}setTimeout(()=>process.exit(0),700).unref()},"shutdown");let He=0;const ze=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)){He=Date.now(),Ke();return}if(He>0&&Date.now()-He<ze)return}Ve(e)}));const xe=Number(process.env.LENSMCP_GATEWAY_PID??0);if(Number.isInteger(xe)&&xe>0){const e=setInterval(()=>{try{process.kill(xe,0)}catch(r){if(r.code==="EPERM")return;clearInterval(e),console.error(`[parent] gateway (pid ${xe}) is gone \u2014 shutting the pod down to avoid an orphan tree.`),Ve("gateway-gone")}},5e3);e.unref()}})()}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lensmcp/cluster",
3
- "version": "1.24.2",
3
+ "version": "1.24.4",
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",
@@ -57,9 +57,9 @@
57
57
  }
58
58
  },
59
59
  "dependencies": {
60
- "@lensmcp/core": "1.24.2",
61
- "@lensmcp/node-instrumentation": "1.24.2",
62
- "@lensmcp/nx-plugin": "1.24.2",
60
+ "@lensmcp/core": "1.24.4",
61
+ "@lensmcp/node-instrumentation": "1.24.4",
62
+ "@lensmcp/nx-plugin": "1.24.4",
63
63
  "fastify": "^5.8.5",
64
64
  "@fastify/reply-from": "^12.6.2",
65
65
  "@typescript/native-preview": "^7.0.0-dev.20260707.2",
@@ -59,9 +59,17 @@ interface BusHygiene {
59
59
  };
60
60
  }
61
61
  /** Appends pod-memory events to the bus. */
62
+ /** What the publisher needs of an event: its flood bucket, and a `raw` to note what the bucket held back in. */
63
+ export interface BusEventLike {
64
+ fingerprint: string;
65
+ raw: Record<string, unknown>;
66
+ }
62
67
  export interface PodMemoryPublisher {
63
- /** `false` when the flood guard dropped it, or there is no bus to write to. */
64
- publish(event: PodMemoryBusEvent): boolean;
68
+ /**
69
+ * Append one event to the bus file. `false`: held back by its flood bucket, or the bus could not be written.
70
+ * Any bus event of this devserver goes through here — pod memory, and what a build ends in (service-build-events.ts).
71
+ */
72
+ publish(event: BusEventLike): boolean;
65
73
  }
66
74
  /**
67
75
  * A publisher for `eventFile` (the devserver's `LENSMCP_EVENT_FILE`, which the serve executor always sets).
@@ -0,0 +1,50 @@
1
+ import type { PodIdentity } from './pod-memory-events';
2
+ /** Loose BaseEvent shape — cluster does not depend on `@lensmcp/protocol-types`. */
3
+ export interface ServiceBuildBusEvent {
4
+ id: string;
5
+ sessionId: string;
6
+ timestamp: number;
7
+ source: 'gateway';
8
+ category: 'cluster';
9
+ severity: 'info' | 'warning';
10
+ context: {
11
+ sessionId: string;
12
+ projectName: string;
13
+ };
14
+ fingerprint: string;
15
+ title: string;
16
+ raw: Record<string, unknown>;
17
+ }
18
+ /** One build's own account, as the build's notifier sends it (devserver-notifier.ts `BuildAccountWire`). */
19
+ export interface BuildAccount {
20
+ startedAt: number;
21
+ endedAt?: number;
22
+ changedFiles: string[];
23
+ moreChanged?: number;
24
+ }
25
+ /** What a pod says of the swap it just made (the `reloaded` IPC message). */
26
+ export interface SwapReport {
27
+ /** The app generation now serving: 1 at boot, then one per swap. */
28
+ generation: number;
29
+ swaps: number;
30
+ /** How long the swap itself took — building the new app, not compiling it. */
31
+ swapMs: number;
32
+ /** Replaced apps still finishing their work. */
33
+ draining: number;
34
+ }
35
+ /** Paths as a reader names them: relative to the workspace, forward slashes. One outside it stays as it is. */
36
+ export declare function workspaceRelative(files: readonly string[], root: string | undefined): string[];
37
+ /** Parse what arrived over HTTP into a build account, or nothing: never trust a body's shape. */
38
+ export declare function buildAccountOf(raw: unknown): BuildAccount | undefined;
39
+ /** A build of this service started (`phase: 'started'`) or ended with errors (`'failed'`). */
40
+ export declare function buildServiceBuildEvent(who: Pick<PodIdentity, 'project' | 'service' | 'podGeneration'>, phase: 'started' | 'failed', build: BuildAccount, opts?: {
41
+ root?: string;
42
+ at?: number;
43
+ id?: () => string;
44
+ }): ServiceBuildBusEvent;
45
+ /** A pod is now serving the app built from `build` — the event a backend edit ends in. */
46
+ export declare function buildServiceSwapEvent(who: PodIdentity, swap: SwapReport, build: BuildAccount | undefined, opts?: {
47
+ root?: string;
48
+ at?: number;
49
+ id?: () => string;
50
+ }): ServiceBuildBusEvent;
@@ -0,0 +1 @@
1
+ "use strict";var u=Object.defineProperty;var a=(d,e)=>u(d,"name",{value:e,configurable:!0});var p=Object.defineProperty,i=a((d,e)=>p(d,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.workspaceRelative=workspaceRelative,exports.buildAccountOf=buildAccountOf,exports.buildServiceBuildEvent=buildServiceBuildEvent,exports.buildServiceSwapEvent=buildServiceSwapEvent;const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),MAX_FILES=50;let idCounter=0;function makeId(){return idCounter=(idCounter+1)%65535,`${Date.now().toString(36)}${idCounter.toString(36)}${Math.random().toString(36).slice(2,8)}`}a(makeId,"makeId"),i(makeId,"makeId");function workspaceRelative(d,e){return d.slice(0,MAX_FILES).map(t=>{if(!e||!path.isAbsolute(t))return t;const n=path.relative(e,t);return n&&!n.startsWith("..")&&!path.isAbsolute(n)?n.split(path.sep).join("/"):t})}a(workspaceRelative,"workspaceRelative"),i(workspaceRelative,"workspaceRelative");function buildAccountOf(d){if(!d||typeof d!="object")return;const e=d;if(typeof e.startedAt!="number"||!Number.isFinite(e.startedAt)||e.startedAt<=0)return;const t=Array.isArray(e.changedFiles)?e.changedFiles.filter(n=>typeof n=="string"&&n.length>0&&n.length<1024).slice(0,MAX_FILES):[];return{startedAt:e.startedAt,...typeof e.endedAt=="number"&&Number.isFinite(e.endedAt)?{endedAt:e.endedAt}:{},changedFiles:t,...typeof e.moreChanged=="number"&&e.moreChanged>0?{moreChanged:Math.floor(e.moreChanged)}:{}}}a(buildAccountOf,"buildAccountOf"),i(buildAccountOf,"buildAccountOf");function envelope(d,e,t,n,o,s,c){const r="pending";return{id:c(),sessionId:r,timestamp:e,source:"gateway",category:"cluster",severity:t,context:{sessionId:r,projectName:d.project},fingerprint:`cluster:${d.project}:${n}`,title:o,raw:{kind:n,...s,project:d.project,service:d.service,podGeneration:d.podGeneration}}}a(envelope,"envelope"),i(envelope,"envelope");const filesText=i((d,e)=>{const t=d+e;return t===0?"no source change":`${t} file${t===1?"":"s"}`},"filesText"),seconds=i(d=>d<1e3?`${d}ms`:`${(d/1e3).toFixed(1)}s`,"seconds");function buildServiceBuildEvent(d,e,t,n={}){const o=workspaceRelative(t.changedFiles,n.root),s=t.moreChanged??0,c=n.at??(e==="failed"?t.endedAt??Date.now():t.startedAt),r=t.endedAt!==void 0?Math.max(0,t.endedAt-t.startedAt):void 0,l=e==="started"?`build started: ${d.project} \u2014 ${filesText(o.length,s)}`:`build failed: ${d.project} \u2014 ${filesText(o.length,s)}${r!==void 0?` \xB7 ${seconds(r)}`:""} \xB7 nothing was swapped, the pod serves the last good build`;return envelope(d,c,e==="failed"?"warning":"info","service-build",l,{phase:e,startedAt:t.startedAt,...t.endedAt!==void 0?{endedAt:t.endedAt,compileMs:r}:{},changedFiles:o,...s>0?{moreChanged:s}:{}},n.id??makeId)}a(buildServiceBuildEvent,"buildServiceBuildEvent"),i(buildServiceBuildEvent,"buildServiceBuildEvent");function buildServiceSwapEvent(d,e,t,n={}){const o=n.at??Date.now(),s=workspaceRelative(t?.changedFiles??[],n.root),c=t?.moreChanged??0,r=t?.endedAt!==void 0?Math.max(0,t.endedAt-t.startedAt):void 0,l=`swap: ${d.project} \u2014 generation ${e.generation} (${e.swaps} swap${e.swaps===1?"":"s"})`+(t?` \xB7 ${filesText(s.length,c)}`:"")+(r!==void 0?` \xB7 compiled in ${seconds(r)}`:"")+` \xB7 swapped in ${seconds(e.swapMs)}`;return envelope(d,o,"info","service-swap",l,{pod:d.pod,pid:d.pid,generation:e.generation,swaps:e.swaps,swappedAt:o,swapMs:e.swapMs,draining:e.draining,...t?{compile:{startedAt:t.startedAt,...t.endedAt!==void 0?{endedAt:t.endedAt,ms:r}:{}},changedFiles:s,...c>0?{moreChanged:c}:{}}:{}},n.id??makeId)}a(buildServiceSwapEvent,"buildServiceSwapEvent"),i(buildServiceSwapEvent,"buildServiceSwapEvent");