@lensmcp/cluster 1.25.25 → 1.25.27
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/compile-retry.d.ts +26 -0
- package/compile-retry.js +1 -0
- package/create-webpack-dev.js +1 -1
- package/devserver-notifier.d.ts +13 -2
- package/devserver-notifier.js +1 -1
- package/executors/gateway/gateway.impl.js +1 -1
- package/executors/gateway/runtime/lens-children.js +1 -1
- package/executors/gateway/runtime/lifecycle.d.ts +18 -3
- package/executors/gateway/runtime/lifecycle.js +3 -3
- package/executors/gateway/runtime/observability.js +3 -2
- package/executors/gateway/runtime/orphan-reaper.d.ts +44 -0
- package/executors/gateway/runtime/orphan-reaper.js +2 -0
- package/executors/gateway/runtime/own-log.d.ts +71 -0
- package/executors/gateway/runtime/own-log.js +6 -4
- package/executors/gateway/runtime/server.js +2 -2
- package/executors/gateway/runtime/types.d.ts +10 -0
- package/executors/gateway/runtime/types.js +1 -1
- package/executors/serve/serve.impl.js +1 -1
- package/executors/serve/stop-on-signal.d.ts +19 -0
- package/executors/serve/stop-on-signal.js +1 -0
- package/main.devserver.js +7 -7
- package/package.json +4 -4
- package/process-name.d.ts +11 -2
- package/process-name.js +1 -1
- package/service-build-events.d.ts +2 -0
- package/service-build-events.js +2 -1
- package/shared-build/host.d.ts +7 -0
- package/shared-build/host.js +4 -4
- package/tsgo-check-plugin.d.ts +23 -0
- package/tsgo-check-plugin.js +5 -5
- package/typecheck-bus.d.ts +24 -0
- package/typecheck-bus.js +3 -3
- package/typecheck-queue.d.ts +24 -1
- package/typecheck-queue.js +1 -1
package/main.devserver.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var yt=Object.defineProperty;var u=(
|
|
1
|
+
"use strict";var yt=Object.defineProperty;var u=(d,_)=>yt(d,"name",{value:_,configurable:!0});var gt=Object.defineProperty,a=u((d,_)=>gt(d,"name",{value:_,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0}),exports.redactInspectorUrls=exports.inspectorPortOf=exports.DEBUG_FIXED_PORTS_ENV=exports.mayDriveThePool=exports.isOwnerOnlyTransport=exports.gatewayManaged=void 0,exports.tell=tell,exports.usesFixedInspectorPorts=usesFixedInspectorPorts,exports.inspectorPortFor=inspectorPortFor;const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),node_child_process_1=require("node:child_process"),http=tslib_1.__importStar(require("node:http")),readline=tslib_1.__importStar(require("node:readline")),inspector=tslib_1.__importStar(require("node:inspector")),util=tslib_1.__importStar(require("node:util")),v8=tslib_1.__importStar(require("node:v8")),child_process_env_1=require("./child-process-env"),exit_reason_1=require("./exit-reason"),worker_supervisor_1=require("./worker-supervisor"),hot_swap_registries_1=require("./hot-swap-registries"),process_name_1=require("./process-name"),inspector_secret_1=require("./inspector-secret");Object.defineProperty(exports,"inspectorPortOf",{enumerable:!0,get:a(function(){return inspector_secret_1.inspectorPortOf},"get")}),Object.defineProperty(exports,"redactInspectorUrls",{enumerable:!0,get:a(function(){return inspector_secret_1.redactInspectorUrls},"get")});const devserver_transport_1=require("./devserver-transport");Object.defineProperty(exports,"gatewayManaged",{enumerable:!0,get:a(function(){return devserver_transport_1.gatewayManaged},"get")}),Object.defineProperty(exports,"isOwnerOnlyTransport",{enumerable:!0,get:a(function(){return devserver_transport_1.isOwnerOnlyTransport},"get")}),Object.defineProperty(exports,"mayDriveThePool",{enumerable:!0,get:a(function(){return devserver_transport_1.mayDriveThePool},"get")});const schema_first_instance_1=require("./schema-first-instance"),redis_disconnect_fix_1=require("./redis-disconnect-fix"),error_stack_release_1=require("./error-stack-release"),swap_recycle_1=require("./swap-recycle"),swap_mode_1=require("./swap-mode"),handoff_retire_1=require("./handoff-retire"),gc_notice_1=require("./gc-notice"),pod_sock_1=require("./pod-sock"),notice_generation_1=require("./notice-generation"),service_build_events_1=require("./service-build-events"),stdio_guard_1=require("./stdio-guard"),bundle_parent_1=require("./bundle-parent"),checkout_cache_1=require("./checkout-cache"),dev_devtool_1=require("./dev-devtool"),pod_memory_1=require("./pod-memory"),pod_memory_events_1=require("./pod-memory-events"),heap_snapshot_1=require("./heap-snapshot"),httpProxy=require("http-proxy"),{prettyFactory}=require("pino-pretty"),BUNDLE_PATH=process.env.BUNDLE_PATH?.trim()||"./main.js",SERVICE_NAME=process.env.SERVICE_NAME||"",SERVICE_PREFIX=process.env.SERVE_PREFIX?`/${process.env.SERVE_PREFIX}`:"",GATEWAY_MIDDLEWARE_PATH=process.env.GATEWAY_MIDDLEWARE||"",GATEWAY_CONFIG=(()=>{const d=process.env.GATEWAY_CONFIG;if(!d)return{};try{return JSON.parse(d)}catch{return{}}})();let gatewayMiddleware=null;if(GATEWAY_MIDDLEWARE_PATH)try{const d=require(GATEWAY_MIDDLEWARE_PATH);gatewayMiddleware=typeof d=="function"?d:typeof d.default=="function"?d.default:null,gatewayMiddleware||console.warn(`[gateway] ${GATEWAY_MIDDLEWARE_PATH} does not export a function, gateway disabled`)}catch(d){console.error(`[gateway] Failed to load middleware from ${GATEWAY_MIDDLEWARE_PATH}:`,d)}function applyGatewayMiddleware(d){if(gatewayMiddleware)try{gatewayMiddleware(d,GATEWAY_CONFIG)}catch(_){console.error("[gateway] Middleware error:",_)}}u(applyGatewayMiddleware,"applyGatewayMiddleware"),a(applyGatewayMiddleware,"applyGatewayMiddleware");const GATEWAY_ROUTES=(()=>{try{return JSON.parse(process.env.GATEWAY_ROUTES||"[]")}catch{return[]}})(),GATEWAY_HTTPS=process.env.GATEWAY_HTTPS==="1";function hostMatches(d,_){if(d.startsWith("*.")){const f=d.slice(1);return _.endsWith(f)||_===d.slice(2)}return _===d}u(hostMatches,"hostMatches"),a(hostMatches,"hostMatches");function matchGatewayRoute(d){if(GATEWAY_ROUTES.length===0)return;const _=(d.headers.host||"").split(":")[0],f=d.url||"/";for(const m of GATEWAY_ROUTES)if(!(m.host&&!hostMatches(m.host,_))&&!(m.prefix&&!f.startsWith(m.prefix)))return m}u(matchGatewayRoute,"matchGatewayRoute"),a(matchGatewayRoute,"matchGatewayRoute");const{specs:WORKER_SPECS,problems:WORKER_PROBLEMS}=(0,worker_supervisor_1.parseWorkerSpecs)(process.env.WORKERS),WORKER_NAMES=WORKER_SPECS.map(d=>d.name),LENSMCP_WS_KEY=process.env.LENSMCP_WS_KEY||"",SOCK_NS=process.env.LENSMCP_SOCK_NS||LENSMCP_WS_KEY,SOCK_DIR=SOCK_NS?path.join(os.tmpdir(),SOCK_NS,`${SERVICE_NAME||"lensmcp-cluster"}-devserver`):path.join(os.tmpdir(),`${SERVICE_NAME||"lensmcp-cluster"}-devserver`),SOCKET_ONLY=process.env.LENSMCP_SOCKET_ONLY==="1",POD_GENERATION=(()=>{const d=Number(process.env.LENSMCP_POD_GENERATION);return Number.isFinite(d)&&d>1?Math.floor(d):1})();function childSockPath(d){return path.join(SOCK_DIR,(0,pod_sock_1.podSockName)(d,POD_GENERATION))}u(childSockPath,"childSockPath"),a(childSockPath,"childSockPath");function sockOwnerPath(d){return`${d}.owner`}u(sockOwnerPath,"sockOwnerPath"),a(sockOwnerPath,"sockOwnerPath");function sockRetiringPath(d){return`${d}.retiring`}u(sockRetiringPath,"sockRetiringPath"),a(sockRetiringPath,"sockRetiringPath");function tell(d,_){if(!d.connected||typeof d.send!="function")return!1;try{return d.send(_,()=>{})}catch{return!1}}u(tell,"tell"),a(tell,"tell");function refusePoolCommand(d,_){console.warn(`[devserver] refused ${d.method} ${d.url} on the public port \u2014 under a gateway the pool is driven on the control socket only.`),_.writeHead(404,{"content-type":"application/json"}),_.end(JSON.stringify({error:"not found"}))}u(refusePoolCommand,"refusePoolCommand"),a(refusePoolCommand,"refusePoolCommand"),exports.DEBUG_FIXED_PORTS_ENV="LENSMCP_DEBUG_FIXED_PORTS";function usesFixedInspectorPorts(d=process.env){const _=(d[exports.DEBUG_FIXED_PORTS_ENV]??"").trim().toLowerCase();return _==="1"||_==="true"||_==="yes"||_==="on"}u(usesFixedInspectorPorts,"usesFixedInspectorPorts"),a(usesFixedInspectorPorts,"usesFixedInspectorPorts");function inspectorPortFor(d,_,f=process.env){if(!usesFixedInspectorPorts(f))return 0;const m=Math.trunc(d)+Math.trunc(_);return Number.isInteger(m)&&m>1024&&m<=65535?m:0}u(inspectorPortFor,"inspectorPortFor"),a(inspectorPortFor,"inspectorPortFor");function ensureOwnerOnlyDir(d){try{fs.mkdirSync(d,{recursive:!0,mode:448})}catch{}try{const _=fs.lstatSync(d);_.isDirectory()&&(_.mode&63)!==0&&fs.chmodSync(d,448)}catch{}}u(ensureOwnerOnlyDir,"ensureOwnerOnlyDir"),a(ensureOwnerOnlyDir,"ensureOwnerOnlyDir");function claimSock(d,_=process.pid){ensureOwnerOnlyDir(path.dirname(d));try{const f=sockOwnerPath(d);try{fs.unlinkSync(f)}catch{}fs.writeFileSync(f,String(_),{flag:"wx",mode:384})}catch{}try{fs.unlinkSync(d)}catch{}try{fs.unlinkSync(sockRetiringPath(d))}catch{}}u(claimSock,"claimSock"),a(claimSock,"claimSock");function sockOwnedByAnother(d,_=process.pid){try{const f=fs.readFileSync(sockOwnerPath(d),"utf8").trim();return!!f&&f!==String(_)}catch{return!1}}u(sockOwnedByAnother,"sockOwnedByAnother"),a(sockOwnedByAnother,"sockOwnedByAnother");function cleanupSock(d,_=process.pid){if(d){try{const f=fs.readFileSync(sockOwnerPath(d),"utf8").trim();if(f&&f!==String(_))return}catch{}try{fs.unlinkSync(d)}catch{}try{fs.unlinkSync(sockOwnerPath(d))}catch{}try{fs.unlinkSync(sockRetiringPath(d))}catch{}(0,gc_notice_1.clearGcNotice)(d)}}u(cleanupSock,"cleanupSock"),a(cleanupSock,"cleanupSock");function postRetiringNotice(d,_){if(!(!d||!_)){try{const f=fs.readFileSync(sockOwnerPath(d),"utf8").trim();if(f&&f!==String(_))return}catch{}try{fs.writeFileSync(sockRetiringPath(d),String(_),{flag:"w",mode:384})}catch{}}}u(postRetiringNotice,"postRetiringNotice"),a(postRetiringNotice,"postRetiringNotice");function serviceKeyFingerprint(){const d=process.env.LENSMCP_SERVICE_KEY;if(!d)return;const{createHash:_}=require("node:crypto");return _("sha256").update(d).digest("hex").slice(0,8)}u(serviceKeyFingerprint,"serviceKeyFingerprint"),a(serviceKeyFingerprint,"serviceKeyFingerprint");function rootModuleOf(d){let _;for(const f of d.getModules?.()?.values()??[])typeof f?.metatype!="function"||typeof f.distance!="number"||!Number.isFinite(f.distance)||(!_||f.distance<_.distance)&&(_=f);return _?.metatype}u(rootModuleOf,"rootModuleOf"),a(rootModuleOf,"rootModuleOf");let lastImportedModule;function takeImportedModule(){const d=lastImportedModule;return lastImportedModule=void 0,d}u(takeImportedModule,"takeImportedModule"),a(takeImportedModule,"takeImportedModule");async function importFresh(spec){process.env.DEVSERVER_MODE="1";const requested=path.isAbsolute(spec)?spec:path.join(__dirname,spec);let resolved=requested;try{resolved=fs.realpathSync(requested)}catch{}eval(`(() => {
|
|
2
2
|
const key = ${JSON.stringify(resolved)};
|
|
3
3
|
const previous = require.cache[key];
|
|
4
4
|
delete require.cache[key]; // delete from CJS cache
|
|
@@ -9,16 +9,16 @@
|
|
|
9
9
|
const at = owner && Array.isArray(owner.children) ? owner.children.indexOf(previous) : -1;
|
|
10
10
|
if (at >= 0) owner.children.splice(at, 1);
|
|
11
11
|
}
|
|
12
|
-
})()`),(0,bundle_parent_1.routeBundleRequires)(requested,resolved);const exports=eval(`require(${JSON.stringify(resolved)})`);try{const mod=eval("require.cache")[resolved];lastImportedModule=mod&&typeof mod=="object"?mod:void 0}catch{}return exports}u(importFresh,"importFresh"),a(importFresh,"importFresh");function debounce(l,_){let f=null;return(...m)=>{f&&clearTimeout(f),f=setTimeout(()=>l(...m),_)}}if(u(debounce,"debounce"),a(debounce,"debounce"),process.env.APP_RUNNER==="1"){(0,stdio_guard_1.guardBrokenStdio)();const l=a(f=>{if(!inspector.url())try{inspector.open(f,"127.0.0.1",!1)}catch(W){console.warn(`[child] inspector.open(${f}) failed (port taken by another devserver?) \u2014 falling back to a random port:`,W.message);try{inspector.open(0,"127.0.0.1",!1)}catch{}}const m=inspector.url();m&&tell(process,{type:"inspector-url",url:m})},"openInspector"),_=process.env.CHILD_DEBUG_PORT;if(_!==void 0&&_!==""){const f=Number(_);Number.isInteger(f)&&(f===0||f>1024)&&l(f)}try{require("@lensmcp/node-instrumentation/register")}catch{}(async()=>{let f=null,m=!1,W,re=!1;const Ve=(0,hot_swap_registries_1.registryPruningEnabled)(),he=a((r,c)=>{const p=(0,hot_swap_registries_1.describePrune)(r,c);p&&console.log(p)},"logPrune");let j={app:null,handler:a((r,c)=>{c.statusCode=503,c.end("starting")},"handler"),inflight:0};const fe=(()=>{const r=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(r)&&r>=0?r:15*6e4})(),M=a(r=>{const c=globalThis.__lensmcpActiveWork;if(typeof c!="function")return{count:0};try{const p=c(r);return{count:Number(p?.count??0),...p?.oldestStartedAt?{oldestStartedAt:p.oldestStartedAt}:{}}}catch{return{count:0}}},"activeWork"),$e=a(r=>{const c=globalThis.__lensmcpStopWorkIntake;if(typeof c=="function")try{return c(r)}catch{return}},"stopWorkIntake"),_e=a(r=>{const c=globalThis.__lensmcpWorkIntakeReport;if(!(r===void 0||typeof c!="function"))try{return c(r)??void 0}catch{return}},"workIntakeReport"),ke=(()=>{const r=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(r)&&r>=1?Math.floor(r):1})(),F=new Set,Z=(()=>{const r=Number(process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS);return process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS!==void 0&&process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS!==""&&Number.isFinite(r)&&r>=0?r:3e4})(),V=a(r=>{if(!r.abandoned?.size)return 0;const c=Date.now();for(const[p,h]of r.abandoned)(p.writableEnded||c-h>=Z)&&r.abandoned.delete(p);return r.abandoned.size},"abandonedRunning"),oe=a(r=>{let c=0;for(const p of r.open??[])p.headersSent||(c+=1);return{unanswered:c+V(r),streams:Math.max(0,r.inflight-c),work:M(r.workGen).count}},"owedBy"),ne=a((r,c,p=`${c}s`)=>`${r} ${r===1?c:p}`,"plural");async function We(){if(Z<=0)return;const r=Date.now();let c=!1;for(;!(F.size<ke);){const p=F.values().next().value;if(!p||p.closed)break;const h=oe(p);if(h.unanswered===0&&h.work===0)break;const E=(p.drainingSince??r)+Z-Date.now();if(E<=0)break;c||(c=!0,console.log(`[child] swap held \u2014 the app replaced ${Math.round((Date.now()-(p.drainingSince??r))/100)/10}s ago is still `+[h.unanswered?`answering ${ne(h.unanswered,"request")}`:"",h.work?`running ${ne(h.work,"background job")}`:""].filter(Boolean).join(" and ")+`, and this pod keeps at most ${ke} replaced app(s) alive (LENSMCP_SWAP_MAX_DRAINING). The new build is applied when it is done \u2014 in ${Math.ceil(E/1e3)}s at the latest (LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS).`)),await new Promise(S=>{setTimeout(S,Math.min(100,E)).unref?.()})}c&&console.log(`[child] swap resumed after ${Date.now()-r}ms`)}u(We,"He"),a(We,"holdForOwedWork");const O=(0,swap_recycle_1.swapRecyclePolicy)();let ge,se=0;const Je=(()=>{const r=Number(process.env.LENSMCP_POD_RETIRE_NOTICE_MS);return Number.isFinite(r)&&r>=0?r:3500})();let g=!1,b=!1;const v=(0,pod_memory_1.podMemoryPolicy)();let K=0;const x=new Set;let we=!1;const B=a(()=>{if(!we)return;let r=0;for(const c of x)c.deref()===void 0?x.delete(c):r+=1;return r},"liveContainers"),k=(0,pod_memory_1.createPodMemoryMonitor)({policy:v,state:a(()=>({gen:j.gen??0,swaps:se,...ge===void 0?{}:{baseline:ge},busy:m||re||J.size>0,lastBusyAt:D}),"state"),send:a(r=>{tell(process,r)},"send"),containers:B,counter:(0,pod_memory_1.createLiveObjectCounter)(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH)),onRetained:a(()=>Te(),"onRetained"),gc:a(()=>(0,gc_notice_1.withGcNotice)(I,pod_memory_1.fullGc),"gc")}),H=a(()=>((0,gc_notice_1.withGcNotice)(I,pod_memory_1.fullGc)&&k.tracker.noteGc(),process.memoryUsage().heapUsed),"liveHeap"),U=(()=>{if(!(0,error_stack_release_1.errorFrameReleaseEnabled)())return null;try{const r=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH))+path.sep,c=`${path.sep}node_modules${path.sep}`,p=new Set(Object.keys(require.cache));return(0,error_stack_release_1.createErrorFrameReleaser)(require.cache,{skip:a(h=>p.has(h)||h.startsWith(r)&&!h.slice(r.length).includes(c)&&!h.slice(r.length).startsWith(`node_modules${path.sep}`),"skip")})}catch{return null}})();let ie=!1;function Oe(){if(!(!U||ie))try{const r=U();r.errors>0&&console.log(`[child] read the stack of ${r.errors} Error object(s) that libraries created while loading and keep for good \u2014 unread, each held the functions that were on its stack, this bundle's included`)}catch(r){console.error("[child] could not release library error frames:",r),ie=!0}}u(Oe,"De"),a(Oe,"releaseLibraryErrorFrames");const J=new Map;let D=Date.now();const Fe=a(()=>O.settleMs<=0||!m&&!re&&J.size===0&&Date.now()-D>=O.settleMs,"settled");let Y;function ae(r){if(!(!O.enabled||g||b)){if(O.settleMs<=0){X(r);return}Y&&clearTimeout(Y),Y=setTimeout(()=>{Y=void 0,Fe()?X(r):ae(r)},O.settleMs),Y.unref?.()}}u(ae,"ue"),a(ae,"recycleCheckWhenSettled");const be=a(()=>{if(O.stuckCloseMs<=0)return 0;const r=Date.now();let c=0;for(const p of J.values())r-p>=O.stuckCloseMs&&(c+=1);return c},"stuckCloses");function X(r){if(!O.enabled||g||b||!process.send)return;const c=v8.getHeapStatistics().heap_size_limit,p=a(E=>{const S=k.oldestRetained();return{swaps:se,usedBytes:E,limitBytes:c,stuckCloses:be(),settled:Fe(),...ge===void 0?{}:{baselineBytes:ge},...S?{retained:{generation:S.gen,ageMs:Date.now()-S.closedAt,gcs:S.gcs}}:{}}},"state");if(!(0,swap_recycle_1.recycleReason)(O,p(process.memoryUsage().heapUsed)))return;const h=(0,swap_recycle_1.recycleReason)(O,p(H()));h&&(g=!0,console.log(`[child] asking for a fresh pod ${r} \u2014 ${h}. This pod keeps serving until its successor is ready. Size the bound with LENSMCP_SWAP_RECYCLE_HEAP_FACTOR / _HEAP_RATIO / _MIN_MB / _RETAINED_MS, or turn it off with LENSMCP_SWAP_RECYCLE=0.`),tell(process,{type:"recycle-request",reason:h}))}u(X,"Q"),a(X,"considerRecycle");let me;function Te(){if(!O.enabled||O.retainedMs<=0||g||b)return;const r=k.oldestRetained();if(!r)return;const c=r.closedAt+O.retainedMs-Date.now();if(c<=0){X("with a closed generation still in memory");return}me||(me=setTimeout(()=>{me=void 0,k.measure("retention-check").catch(()=>{})},c),me.unref?.())}u(Te,"je"),a(Te,"retainedRecycleCheck");function ye(r,c){const p={};c&&(p.module=c),r&&(p.app=r);try{const h=r?.app;if(h&&typeof h=="object"&&(p.nestApp=h,h.container&&typeof h.container=="object")){p.container=h.container;const E=rootModuleOf(h.container);E&&(p.rootModule=E)}}catch{}return p}u(ye,"Ne"),a(ye,"generationTargets");async function ce(r,c){if(r.closed||(r.closed=!0,F.delete(r),c&&console.error(`[child] ${c}`),!r.app))return;J.set(r,Date.now());const p=O.enabled&&O.stuckCloseMs>0?setTimeout(()=>{J.has(r)&&(console.error(`[child] a previous app has been closing for ${Math.round(O.stuckCloseMs/1e3)}s and its close() has not returned \u2014 one of its shutdown hooks is waiting on something that does not end (a queue worker, a connection, a stream). It stays in memory until this pod is replaced.`),X("with a previous app stuck in close()"))},O.stuckCloseMs):void 0;p?.unref?.();const h=r.app;try{await r.app.close()}catch(E){console.error("[child] error closing a previous app:",E)}finally{J.delete(r),D=Date.now(),p&&clearTimeout(p),r.app=null,r.abandoned=void 0,r.handler=(E,S)=>{S.statusCode=503,S.end("closed")},r.gen!==void 0&&k.closed(r.gen,se,ye(h,r.module)),r.module=void 0}if(r.superseded){try{he((0,hot_swap_registries_1.pruneRegistries)(r.superseded,"serve"),"after closing the previous app")}catch(E){console.error("[child] could not release the previous app's class registrations:",E)}r.superseded=void 0}ae("after closing the previous app")}u(ce,"me"),a(ce,"closeGeneration");async function le(r){const c=Date.now();r.drainingSince=c;const p=a(()=>({inflight:r.inflight+V(r),work:M(r.workGen).count}),"busy"),h=p();if(h.inflight>0||h.work>0){for(;F.size>=ke;){const C=F.values().next().value;if(!C)break;const N=oe(C),z=Math.round((Date.now()-(C.drainingSince??c))/1e3);if(N.unanswered===0&&N.streams===0&&N.work===0){await ce(C);continue}await ce(C,`closing a still-draining generation early \u2014 ${F.size} were pending and the cap is ${ke} (each holds a whole app: DI container, DB pool, queue workers). `+(N.unanswered>0||N.work>0?`It was replaced ${z}s ago and had still not answered ${ne(N.unanswered,"request")}`+(N.work?` or finished ${ne(N.work,"background job")}`:"")+` \u2014 those fail now (a queue job keeps its lock until the TTL lapses). Raise LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS (currently ${Z}ms) to wait longer for them. `:`It held only ${ne(N.streams,"open stream")}; their clients reconnect to the new app. `)+"Raise LENSMCP_SWAP_MAX_DRAINING if this pod legitimately needs more.")}F.add(r)}for(;fe>0&&Date.now()-c<fe;){if(r.closed)return;const C=p();if(C.inflight===0&&C.work===0)break;await new Promise(N=>{setTimeout(N,250).unref?.()})}if(r.closed)return;const E=p(),S=_e(r.workGen);E.inflight>0||E.work>0?console.error(`[child] swap drain expired after ${Date.now()-c}ms \u2014 closing the previous app with ${E.inflight} in-flight request(s) and ${E.work} background job(s) still running. `+(S?`Previous app still processing ${S.running} queue job(s); ${S.takenAfterStop} were taken after the swap. `:"")+`A queue job killed here keeps its lock until the TTL lapses. Raise LENSMCP_SWAP_DRAIN_MS (currently ${fe}ms) if this is legitimate work.`):(Date.now()-c>250||S?.runningAtStop||S?.takenAfterStop)&&console.log(`[child] previous app drained in ${Date.now()-c}ms \u2014 closing it`+(S?` (it finished ${S.finishedAfterStop} queue job(s) after the swap; ${S.takenAfterStop} were taken after the swap)`:"")),await ce(r)}u(le,"ye"),a(le,"drainThenClose");async function de(){if(m)return re=!0,console.log("[child] Reload deferred \u2014 will re-swap after current swap completes"),f;m=!0,D=Date.now(),await We(),process.removeAllListeners("uncaughtException"),process.removeAllListeners("unhandledRejection"),process.on("uncaughtException",(P,ee)=>{console.error(`[child] uncaughtException (${ee}):`,P)}),process.on("unhandledRejection",P=>{const ee=P instanceof Error?P.stack||P.message:String(P);ee.includes("FronteggContextScope")||ee.includes("populateLoggerMetadata")||console.error("[child] unhandledRejection:",P)});let r;if(Ve)try{r=(0,hot_swap_registries_1.captureRegistries)()}catch{r=void 0}const c=global.__lensmcpBeginWorkGeneration,p=typeof c=="function"?c():void 0;try{try{await importFresh(BUNDLE_PATH)}catch(P){if(!(P instanceof SyntaxError))throw P;console.warn(`[child] bundle was unreadable mid-write (${P.message}) \u2014 retrying the swap once`),await new Promise(ee=>setTimeout(ee,400)),await importFresh(BUNDLE_PATH)}}catch(P){throw m=!1,D=Date.now(),P}if(typeof global.createChildApp!="function")throw m=!1,D=Date.now(),new Error(`Bundle '${BUNDLE_PATH}' does not export createChildApp() and the zero-touch bridge is not active. Either install @lensmcp/node-instrumentation (a plain NestFactory.create + app.listen main.ts then just works) or set global.createChildApp in main.ts when DEVSERVER_MODE === '1'.`);let h;if(r)try{h=(0,hot_swap_registries_1.supersededSince)(r),he((0,hot_swap_registries_1.pruneRegistries)(h,"build"),"at the swap")}catch(P){console.error("[child] could not release superseded class registrations:",P)}let E;try{E=await global.createChildApp()}catch(P){throw m=!1,D=Date.now(),takeImportedModule(),P}const S=j;h?.size&&(S.app?S.superseded=h:he((0,hot_swap_registries_1.pruneRegistries)(h,"serve"),"at the swap")),f=E;const C=takeImportedModule();j={app:E,handler:E.handler,inflight:0,gen:++K,...C?{module:C}:{},...p===void 0?{}:{workGen:p}};const N=ye(E,void 0).container;N&&(x.add(new WeakRef(N)),we=!0);const z=S.app&&p!==void 0?$e(p):void 0;return console.log("[child] Swapped to fresh app (previous draining in background)"+(z?.workers?`; its ${z.workers} queue worker(s) stopped taking new jobs, previous app still processing ${z.runningAtStop} job(s)`:"")),Oe(),S.app&&(se+=1,le(S).catch(P=>console.error("[child] background close error:",P)),setTimeout(()=>X("30s after a hot swap"),3e4).unref?.(),k.swapped(S.gen,()=>S.closed===!0&&!J.has(S))),m=!1,D=Date.now(),re?(re=!1,de()):E}u(de,"Ee"),a(de,"swapNow");const Pe=debounce(async()=>{try{console.log("[child] /webpack/reload"),await de()}catch(r){console.error("[child] reload failed:",r)}},250),Ee=http.createServer((r,c)=>{if(r.method==="POST"&&r.url==="/webpack/reload"){c.writeHead(200,{"content-type":"application/json"}),c.end(JSON.stringify({ok:!0})),Pe();return}if(r.method==="GET"&&r.url==="/__lensmcp/alive"){const h=r.headers["x-internal-token"],E=process.env.LENSMCP_SERVICE_KEY;if(E&&h!==E){c.writeHead(404,{"content-type":"text/plain"}),c.end("not found");return}const S=M();c.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),c.end(JSON.stringify({ok:!0,pid:process.pid,swapping:m,inflight:j.inflight,oldestInflightAt:j.oldestAt,activeWork:S.count,oldestWorkAt:S.oldestStartedAt,keyFingerprint:serviceKeyFingerprint(),...W?{watcher:W}:{},...Number.isFinite(Number(process.env.LENSMCP_POD_GENERATION))&&process.env.LENSMCP_POD_GENERATION?{podGeneration:Number(process.env.LENSMCP_POD_GENERATION)}:{}}));return}const p=j;p.inflight+=1,(p.open??=new Set).add(c),p.oldestAt===void 0&&(p.oldestAt=Date.now()),c.on("close",()=>{p.inflight-=1,p.open?.delete(c),Z>0&&!p.closed&&!c.headersSent&&!c.writableEnded&&((p.abandoned??=new Map).set(c,Date.now()),p.abandoned.size>256&&V(p)),p.inflight===0&&(p.oldestAt=void 0),k.activity()}),p.handler(r,c)});Ee.keepAliveTimeout=0;const I=process.env.CHILD_SOCK_PATH;process.on("disconnect",()=>{cleanupSock(I),process.exit(0)});try{const r=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH);if((0,schema_first_instance_1.schemaPrewarmEnabled)())try{const c=(0,schema_first_instance_1.prewarmZodFor)(r);c?.created&&console.log(`[child] zod${c.version?` ${c.version}`:""}: built ${c.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 c=(0,redis_disconnect_fix_1.finishStrandedDisconnectsFor)(r);c?.patched&&console.log(`[child] ioredis${c.versions.length?` ${c.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 de(),ge=(await k.booted()).live,console.log(`[child] Using bundle: ${r}`),claimSock(I),Ee.listen(I,()=>{console.log(`[child] Listening on ${I}`),tell(process,{type:"ready",socketPath:I})})}catch(r){console.error("[child] Startup error:",r),tell(process,{type:"boot-error",error:String(r?.stack||r)}),process.exitCode=1;return}process.on("message",async r=>{if(!(!r||typeof r!="object")){if(r.type==="debug-open"){const c=Number(r.port);l(Number.isInteger(c)&&c>1024?c:0);return}if(r.type==="watcher"){const c=r.testimony;c&&typeof c=="object"&&(W=c);return}if(r.type==="heap-snapshot"){Me(r);return}if(r.type==="recycle-declined"){g=!1;return}if(r.type==="retire"){q();return}if(r.type==="reload"){if(b)return;try{const c=Date.now();await de(),tell(process,{type:"reloaded",socketPath:I,swap:{generation:K,swaps:se,swapMs:Date.now()-c,draining:F.size}})}catch(c){console.error("[child] reload error:",c),tell(process,{type:"reload-error",error:String(c?.stack||c)})}}}});let Se=!1;async function Me(r){const c=a(p=>{tell(process,{type:"heap-snapshot-result",id:r.id,...p})},"reply");if(Se)return c({ok:!1,refused:"a snapshot of this pod is already being written"});Se=!0;try{const p=H(),h=k.tracker.views().map(N=>N.gen),E=(0,heap_snapshot_1.heapSnapshotPolicy)();r.maxHeapBytes&&(E.maxHeapBytes=r.maxHeapBytes);const S=(0,heap_snapshot_1.heapSnapshotRefusal)(E,{live:p,...r.available?{available:r.available}:{}});if(S)return c({ok:!1,refused:S,live:p});console.log(`[child] writing a heap snapshot (${Math.round(p/1048576)} MB live) \u2014 the pod pauses while V8 serialises it`);const C=await(0,heap_snapshot_1.writeHeapSnapshot)(r.file);c({ok:!0,file:r.file,bytes:C.bytes,ms:C.ms,live:p,gen:j.gen??0,closedAlive:h})}catch(p){c({ok:!1,error:p?.message??String(p)})}finally{Se=!1}}u(Me,"Ye"),a(Me,"takeHeapSnapshot");async function q(r="a fresh pod has taken over"){if(b)return;b=!0,k.stop(),console.log(`[child] retiring \u2014 ${r}; ${path.basename(I,".sock")} (pid ${process.pid}) is finishing in-flight work, then exiting`);const c=$e(Number.POSITIVE_INFINITY);c?.workers&&console.log(`[child] its ${c.workers} queue worker(s) stopped taking new jobs, still processing ${c.runningAtStop} job(s)`);try{fs.writeFileSync(sockRetiringPath(I),String(process.pid),{flag:"w",mode:384})}catch{}await new Promise(h=>{setTimeout(h,Je).unref?.()}),cleanupSock(I),Ee.close();const p=Date.now();for(;Date.now()-p<fe;){Ee.closeIdleConnections?.();let h=0;for(const E of F)h+=oe(E).unanswered;if(j.inflight+V(j)===0&&h===0&&M().count===0)break;await new Promise(E=>{setTimeout(E,250).unref?.()})}setTimeout(()=>process.exit(0),3e4).unref?.();try{await f?.close()}catch(h){console.error("[child] close error while retiring:",h)}process.exit(0)}u(q,"B"),a(q,"retire"),process.on("beforeExit",()=>{try{inspector?.close?.()}catch{}});const pe=a(async r=>{console.log(`[child ${r}] shutting down\u2026`);const c=f?.close().catch(h=>console.error("[child] close error:",h)),p=new Promise(h=>Ee.close(()=>h()));cleanupSock(I),setTimeout(()=>process.exit(0),700).unref(),await Promise.all([c,p]),process.exit(0)},"shutdown");["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(r=>{process.on(r,()=>{if(r==="SIGTERM"&&!b&&(0,handoff_retire_1.handoffRetireRequested)(SOCK_DIR,POD_GENERATION)){q("this generation was handed over to a newer one");return}inspector?.close?.(),pe(r)})})})()}else{let l=u(function(g){V.push(g),V.length>Z&&V.splice(0,V.length-Z),ke?.write((0,inspector_secret_1.redactInspectorUrls)(g.replace(F,"")));for(const b of oe)try{const v=b.plain?g.replace(F,""):g;b.res.write(b.redact?(0,inspector_secret_1.redactInspectorUrls)(v):v)}catch{oe.delete(b)}},"we");a(l,"emitLogLine");const _=12,f=process.env.LENSMCP_PROJECT||SERVICE_NAME||"service",m=(0,pod_memory_events_1.createPodMemoryPublisher)(process.env.LENSMCP_EVENT_FILE),W=a(g=>({project:f,service:SERVICE_NAME||f,pod:g.id,pid:g.proc.pid??0,podGeneration:POD_GENERATION}),"podIdentity"),re=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[31m"],Ve="\x1B[0m",he=Math.max(1,Number(process.env.CHILD_COUNT||1)),j=LENSMCP_WS_KEY||path.basename(process.cwd()),fe=a(g=>(0,process_name_1.namedExecPath)((0,process_name_1.processName)(j,SERVICE_NAME||"service",g)),"execPathFor");let M=(()=>{const g=Number(process.env.LENSMCP_DEBUG_PORT||"");return Number.isInteger(g)&&g>1024?g:0})();const $e=20;M&&(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 (${M}+slot, workers ${M}+${$e}+i). Any account on this host can connect to 127.0.0.1:${M} 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 _e=process.env.LENSMCP_LOG_FILE||"",ke=_e?(()=>{try{fs.mkdirSync(path.dirname(_e),{recursive:!0});const g=fs.createWriteStream(_e,{flags:"a",mode:384});try{fs.chmodSync(_e,384)}catch{}return g}catch(g){return console.warn(`[parent] cannot open log file ${_e}:`,g.message),null}})():null,F=/\x1b\[[0-9;]*m/g,Z=2e3,V=[],oe=new Set,ne=(0,devserver_transport_1.gatewayManaged)();for(const g of["log","info","warn","error"]){const b=console[g].bind(console),v=g==="log"||g==="info"?process.stdout:process.stderr;console[g]=(...K)=>{b(...K.map(x=>typeof x=="string"?(0,inspector_secret_1.forStream)(v,ne,x):x)),l(K.map(x=>typeof x=="string"?x:util.inspect(x)).join(" ")+`
|
|
13
|
-
`)}}const We=a(g=>re[(g-1)%re.length],"colorFor"),O=a(g=>{if(
|
|
14
|
-
`+String(B),"stack")}}),x=a((B,k)=>{const H=B==="stdout"?process.stdout:process.stderr;try{v?.(k)}catch{}const U=
|
|
15
|
-
`;H.write((0,inspector_secret_1.forStream)(H,ne,`${b}${U}`)),l(`${b}${U}`)},"write"),we=a((B,k)=>{if(!B)return;const H=readline.createInterface({input:B});H.on("line",U=>x(k,U)),H.on("close",()=>{})},"attach");we(g.stdout,"stdout"),we(g.stderr,"stderr")},"wireProcLogging"),Je=a(g=>se(g.proc,O(g.id),b=>g.tail.push(b)),"wireChildLogging");(async()=>{ensureOwnerOnlyDir(SOCK_DIR);const g=httpProxy.createProxyServer({});let b=Number(process.env.PORT)||0;b||(b=9090);const v=[],K=new Set;function x(){let e=0;for(;K.has(e);)e++;return K.add(e),e}u(x,"D"),a(x,"allocDebugSlot");let we=1,B=0,k=!1,H=he,U=[],ie=0;const Oe=(0,swap_mode_1.swapMode)(),J=(()=>{const e=Number(process.env.LENSMCP_POD_BOOT_GRACE_MS);return Number.isFinite(e)&&e>=0?e:12e4})(),D=a(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"childExited"),Fe=a(e=>e.booting&&!D(e)&&Date.now()-e.spawnedAt<J,"stillBooting");function Y(){return v.filter(e=>e.healthy&&typeof e.socketPath=="string")}u(Y,"J"),a(Y,"healthyChildren");let ae,be=0,X;const me={project:f,service:SERVICE_NAME||f,podGeneration:POD_GENERATION};function Te(e){const t=(0,service_build_events_1.buildAccountOf)(e.building);t&&t.startedAt!==be&&(be=t.startedAt,m.publish((0,service_build_events_1.buildServiceBuildEvent)(me,"started",t,{root:process.cwd()})));const n=(0,service_build_events_1.buildAccountOf)(e.failed);n&&(be=0,m.publish((0,service_build_events_1.buildServiceBuildEvent)(me,"failed",n,{root:process.cwd()})))}u(Te,"je"),a(Te,"recordBuildProgress");function ye(e){if(!e||typeof e!="object")return;const t=e;if(t.schemaVersion===1){Te(t),"failed"in t&&delete t.failed,ae=t;for(const n of v)tell(n.proc,{type:"watcher",testimony:t})}}u(ye,"Ne"),a(ye,"recordWatcherTestimony");function ce(e,t=256*1024){return new Promise(n=>{let i="",s=!1;e.on("data",o=>{s||(i+=o,i.length>t&&(s=!0))}),e.on("end",()=>{if(s||!i)return n(void 0);try{n(JSON.parse(i))}catch{n(void 0)}}),e.on("error",()=>n(void 0))})}u(ce,"me"),a(ce,"readJsonBody");function le(){const e=Y();if(e.length===0)return null;const t=B%e.length;return B=(B+1)%e.length,e[t]}u(le,"ye"),a(le,"pickChild");function de(e,t){const n=`Child#${e.id}`,i=SERVICE_NAME||f,s=Date.now();if(t.type==="pod-memory"){const o=t.report;if(!o||typeof o.live!="number")return;e.memory.latest=o,e.memory.history.push(o),e.memory.history.length>12&&e.memory.history.splice(0,e.memory.history.length-12),console.log(`[parent] ${(0,pod_memory_1.describePodMemory)(n,o)}`),m.publish((0,pod_memory_events_1.buildPodMemoryEvent)(W(e),o))}else if(t.type==="pod-memory-retained"){const o=t.retained;if(!o||typeof o.gen!="number")return;e.memory.retained.set(o.gen,{...o,at:s}),console.warn(`[parent] ${(0,pod_memory_1.describeRetained)(n,i,o)}`),m.publish((0,pod_memory_events_1.buildPodRetainedEvent)(W(e),o,s))}else{const o=t.released;if(!o||typeof o.gen!="number")return;e.memory.retained.delete(o.gen),console.log(`[parent] ${(0,pod_memory_1.describeReleased)(n,i,o)}`),m.publish((0,pod_memory_events_1.buildPodReleasedEvent)(W(e),o,s))}}u(de,"Ee"),a(de,"recordPodMemory");const Pe=new Map;let Ee=0;async function I(){const e=we++,t=childSockPath(e);cleanupSock(t);const n=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&n.unshift("--require","@swc-node/register"),n.push(...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const i=M?x():-1,s=(0,node_child_process_1.fork)(__filename,{env:(0,child_process_env_1.childProcessEnv)({...process.env,APP_RUNNER:"1",CHILD_SOCK_PATH:t,...i>=0&&{CHILD_DEBUG_PORT:String(inspectorPortFor(M,i))}}),stdio:["inherit","pipe","pipe","ipc"],execArgv:n,execPath:fe("pod")}),o={id:e,proc:s,healthy:!1,lastError:null,debugSlot:i,tail:new exit_reason_1.TailBuffer,booting:!0,spawnedAt:Date.now(),bootReloadSeq:ie,memory:{history:[],retained:new Map}};return s.on("error",y=>console.error(`[parent] Child#${e}: ${y.message}`)),s.on("message",y=>{if(!y||typeof y!="object")return;const d=y;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}`),ae&&tell(s,{type:"watcher",testimony:ae}),ie!==o.bootReloadSeq&&(Oe==="process"?P():tell(s,{type:"reload"}));else if(d.type==="recycle-request")S(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"){if(q.has(o)){console.log(`[parent] Child#${o.id} finished a swap it began before it was retired \u2014 not serving it: a fresh pod has taken over`);return}o.socketPath=String(d.socketPath),o.healthy=!0,console.log(`[parent] Child#${o.id} hot-swapped on socket ${o.socketPath}`);const w=d.swap;w&&typeof w.generation=="number"&&typeof w.swaps=="number"&&m.publish((0,service_build_events_1.buildServiceSwapEvent)(W(o),{generation:w.generation,swaps:w.swaps,swapMs:typeof w.swapMs=="number"?w.swapMs:0,draining:typeof w.draining=="number"?w.draining:0},X,{root:process.cwd()}))}else 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"?de(o,d):d.type==="heap-snapshot-result"&&Pe.get(Number(d.id))?.(d)}),s.on("exit",(y,d)=>{o.booting=!1;for(const A of o.memory.retained.values()){const T={gen:A.gen,closedAt:A.closedAt,ageMs:Date.now()-A.closedAt,reason:"pod-exited"};console.log(`[parent] ${(0,pod_memory_1.describeReleased)(`Child#${o.id}`,SERVICE_NAME||f,T)}`),m.publish((0,pod_memory_events_1.buildPodReleasedEvent)(W(o),T,Date.now()))}o.memory.retained.clear(),o.memory.latest&&m.publish((0,pod_memory_events_1.buildPodExitedEvent)(W(o),{code:y,signal:d},Date.now())),o.debugSlot>=0&&(K.delete(o.debugSlot),o.debugSlot=-1);const w=d==="SIGINT"||d==="SIGTERM"||y===0;if(w?console.log(`[parent] Child#${o.id} exited cleanly (code=${y}, signal=${d??"none"})`):(console.error((0,exit_reason_1.crashReport)(`[parent] Child#${o.id} crashed (code=${y}, signal=${d??"none"}, pid=${o.proc.pid}, ${o.healthy?"was serving":"was not ready"})`,y,d,o.tail.snapshot())),o.lastError||(o.lastError=`Child exited abnormally (code=${y}, signal=${d??"none"})`)),o.healthy=!1,cleanupSock(o.socketPath,o.proc.pid),o.socketPath=void 0,!w&&!k){const A=v.indexOf(o);A>=0&&v.splice(A,1);const T=Date.now();if(U=U.filter($=>T-$<3e4),U.length>=5){console.error(`[parent] crash-loop detected (${U.length} respawns/30s) \u2014 pausing auto-respawn; POST /webpack/reload to retry`);return}U.push(T),setTimeout(()=>{const $=v.filter(Q=>Q.proc.killed===!1).length;!k&&$<H&&(console.log(`[parent] respawning a crashed pod (${$}/${H} live)`),I().catch(()=>{}))},1500).unref?.()}}),v.push(o),Je(o),o}u(I,"C"),a(I,"spawnChild");async function Se(e){H=Math.max(H,e);const t=v.filter(i=>i.proc.killed===!1),n=e-t.length;for(let i=0;i<n;i++)await I()}u(Se,"be"),a(Se,"ensurePoolSize");async function Me(){const e=v.filter(t=>(!t.healthy||typeof t.socketPath!="string")&&!Fe(t));await Promise.all(e.map(async t=>{try{t.proc.kill("SIGTERM")}catch{}cleanupSock(t.socketPath,t.proc.pid),t.socketPath=void 0;const n=v.indexOf(t);n>=0&&v.splice(n,1),await I()}))}u(Me,"Ye"),a(Me,"respawnUnhealthy");const q=new Set;let pe=!1,r=0;const c=3e4,p=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return(Number.isFinite(e)&&e>=0?e:15*6e4)+6e4})();async function h(e,t={}){const n=Date.now(),i=await I(),s=Date.now()+J;for(;!i.healthy&&!i.lastError&&!D(i)&&Date.now()<s;){if(t.superseded?.()){const o=v.indexOf(i);o>=0&&v.splice(o,1);try{i.proc.kill("SIGTERM")}catch{}return{why:`a newer build landed while Child#${i.id} booted`,superseded:!0}}await new Promise(o=>{setTimeout(o,100).unref?.()})}if(k)return{why:"shutting down"};if(!i.healthy){const o=v.indexOf(i);o>=0&&v.splice(o,1);try{i.proc.kill("SIGTERM")}catch{}return{why:`its successor Child#${i.id} did not come up (${i.lastError??"no answer in time"})`}}return E(e),{fresh:i,readyMs:Date.now()-n}}u(h,"_"),a(h,"replacePod");function E(e){const t=v.indexOf(e);if(t>=0&&v.splice(t,1),e.healthy=!1,D(e))return;q.add(e),postRetiringNotice(e.socketPath,e.proc.pid);const n=setTimeout(()=>{if(!D(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(n.unref?.(),e.proc.once("exit",()=>{clearTimeout(n),q.delete(e)}),!tell(e.proc,{type:"retire"}))try{e.proc.kill("SIGTERM")}catch{}}u(E,"m"),a(E,"retirePod");async function S(e,t){const n=a(s=>{console.log(`[parent] Child#${e.id} asked for a fresh pod (${t}) \u2014 not now: ${s}`),tell(e.proc,{type:"recycle-declined"})},"decline");if(k||!v.includes(e))return;if(pe)return n("another pod is already being replaced");const i=Date.now()-r;if(i<c)return n(`a pod was replaced ${Math.round(i/1e3)}s ago`);pe=!0,console.log(`[parent] Child#${e.id} asked for a fresh pod \u2014 ${t}. Starting one; Child#${e.id} keeps serving until it is ready.`);try{const s=await h(e);if("why"in s){s.why!=="shutting down"&&n(s.why);return}r=Date.now(),console.log(`[parent] Child#${s.fresh.id} took over from Child#${e.id} (pid ${e.proc.pid} \u2192 ${s.fresh.proc.pid})`)}catch(s){n(`could not start a successor: ${s?.message??String(s)}`)}finally{pe=!1}}u(S,"y"),a(S,"recyclePod");let C,N=!1,z=0;function P(){if(C){N=!0;return}C=(async()=>{do{N=!1;const e=ie;for(;pe&&!k;)await new Promise(n=>{setTimeout(n,100).unref?.()});let t=!1;for(const n of Y().filter(i=>i.bootReloadSeq<e)){if(k)break;if(!(!v.includes(n)||!n.healthy)){pe=!0;try{ee(),console.log(`[parent] A new build \u2014 starting a fresh pod for it; Child#${n.id} keeps serving the previous build until it is ready.`);const i=await h(n,{superseded:a(()=>ie!==e&&(0,swap_mode_1.abandonSuperseded)(z),"superseded")});if("why"in i){if(i.superseded){z+=1,console.log(`[parent] ${i.why} \u2014 abandoned; one fresh pod for the newest build instead (${z} in a row). Child#${n.id} keeps serving.`),t=!0;break}i.why!=="shutting down"&&console.error(`[parent] Child#${n.id} keeps serving the previous build \u2014 ${i.why}`);continue}z=0,console.log(`[parent] Child#${i.fresh.id} took over from Child#${n.id} with the new build (pid ${n.proc.pid} \u2192 ${i.fresh.proc.pid}, ready in ${(i.readyMs/1e3).toFixed(1)}s while Child#${n.id} served)`),m.publish((0,service_build_events_1.buildServiceSwapEvent)(W(i.fresh),{generation:1,swaps:0,swapMs:i.readyMs,draining:q.size,handoff:{fromPid:n.proc.pid??0}},X,{root:process.cwd()}))}catch(i){console.error(`[parent] Child#${n.id} keeps serving the previous build \u2014 could not start a successor: ${i?.message??String(i)}`)}finally{pe=!1}}}t&&(N=!0)}while(N&&!k)})().finally(()=>{C=void 0})}u(P,"A"),a(P,"handoffForReload");function ee(){const e=(0,swap_mode_1.maxRetiring)(),t=[...q].filter(n=>!D(n));for(;t.length>=e;){const n=t.shift();console.error(`[parent] Child#${n.id} (pid ${n.proc.pid}) was still finishing its work when a newer build replaced its successor too \u2014 stopping it (LENSMCP_SWAP_MAX_RETIRING=${e})`);try{n.proc.kill("SIGTERM")}catch{}}}u(ee,"X"),a(ee,"capRetiring");const G=[],He=new Map,Ue=a(e=>{let t=He.get(e);return t||He.set(e,t={crashes:0,restarts:0}),t},"watchOf"),Xe=(0,worker_supervisor_1.workerBackoff)(),Ae=a((e,t)=>({project:f,service:SERVICE_NAME||f,worker:e,pid:t,podGeneration:POD_GENERATION}),"workerWho"),tt=[path.join(__dirname,"worker-guard.js"),path.join(__dirname,"worker-guard.ts")].find(e=>fs.existsSync(e));for(const e of WORKER_PROBLEMS)console.error(`[parent] ${e}`);function ze(e,t){const n=e.name,i=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH)),s=path.join(i,`${n}.js`),o=Ue(n);if(!fs.existsSync(s))return console.error(`[parent] Worker "${n}" bundle not found: ${s}`),o.missing=s,m.publish((0,worker_supervisor_1.buildWorkerExitedEvent)(Ae(n,0),{ranMs:0,reason:`its bundle was not built (${path.basename(s)} is not in ${i})`})),null;o.missing=void 0;const y=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&y.unshift("--require","@swc-node/register"),tt&&y.push("--require",tt);try{y.push("--require",require.resolve("@lensmcp/node-instrumentation/register"))}catch{}const d=inspectorPortFor(M||9229,$e+Math.max(0,WORKER_NAMES.indexOf(n)));y.push(M?`--inspect=127.0.0.1:${d}`:`--inspect-port=127.0.0.1:${d}`,...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const w=(0,node_child_process_1.fork)(s,{env:(0,worker_supervisor_1.workerEnv)(process.env,e),stdio:["inherit","pipe","pipe","ipc"],execArgv:y,execPath:fe(`w-${n}`)}),A={name:n,spec:e,proc:w,debugPort:d,startedAt:Date.now(),tail:new exit_reason_1.TailBuffer,stopping:!1};G.push(A),w.on("error",$=>console.error(`[parent] Worker "${n}": ${$.message}`)),se(w,`\x1B[35m[worker:${n}] \x1B[0m`,$=>{A.tail.push($);const Q=/Debugger listening on (wss?:\/\/\S+)/.exec($);Q&&(A.inspectorUrl=Q[1])});const T=setTimeout(()=>{if(!(Re(A)||A.stopping)){if(o.crashes>0){const $=Date.now()-A.startedAt;console.log(`[parent] Worker "${n}" (pid=${w.pid}) is up again \u2014 ${(0,worker_supervisor_1.spanOf)($)} without a crash, after ${o.crashes} in a row`),m.publish((0,worker_supervisor_1.buildWorkerUpEvent)(Ae(n,w.pid??0),{ranMs:$,afterCrashes:o.crashes}))}o.crashes=0}},Xe.stableMs);return T.unref?.(),w.on("exit",($,Q)=>{clearTimeout(T);const ve=G.indexOf(A);ve>=0&&G.splice(ve,1),rt(A,$,Q)}),console.log(`[parent] Worker "${n}" started (pid=${w.pid}, PORT=${(0,worker_supervisor_1.workerEnv)(process.env,e).PORT}${t==="respawn"?`, restart ${o.restarts}`:""})`),m.publish((0,worker_supervisor_1.buildWorkerStartedEvent)(Ae(n,w.pid??0),{why:t,port:e.port,restarts:o.restarts})),A}u(ze,"Ze"),a(ze,"spawnWorkerProcess");function rt(e,t,n){const{name:i}=e,s=e.proc.pid??0,o=Date.now()-e.startedAt,y=(0,worker_supervisor_1.workerExitVerdict)(t,n,e.stopping||k);if(y.kind==="stopped")return;const d=Ue(i);if(y.kind==="exited"){d.lastEnd={at:Date.now(),pid:s,code:t,signal:n,ranMs:o,verdict:"exited"},console.warn(`[parent] Worker "${i}" (pid=${s}) exited on its own (code 0) after ${(0,worker_supervisor_1.spanOf)(o)} \u2014 not started again until the next build: a worker that ends is taken to have finished its work`),m.publish((0,worker_supervisor_1.buildWorkerExitedEvent)(Ae(i,s),{ranMs:o}));return}d.crashes+=1,d.lastEnd={at:Date.now(),pid:s,code:t,signal:n,ranMs:o,verdict:"crashed"};const w=(0,worker_supervisor_1.respawnDelay)(d.crashes,Xe),A=d.crashes>=worker_supervisor_1.CRASH_LOOP_AFTER;console.error((0,exit_reason_1.crashReport)(`[parent] Worker "${i}" crashed (code=${t}, signal=${n??"none"}, pid=${s}, after ${(0,worker_supervisor_1.spanOf)(o)})${y.external?" \u2014 stopped by a signal from outside its devserver":""}; starting it again in ${(0,worker_supervisor_1.spanOf)(w)}${A?` \u2014 ${d.crashes} crashes in a row: it is crash-looping (the wait doubles, up to ${(0,worker_supervisor_1.spanOf)(Xe.maxMs)})`:""}`,t,n,e.tail.snapshot())),m.publish((0,worker_supervisor_1.buildWorkerCrashedEvent)(Ae(i,s),{code:t,signal:n,ranMs:o,crashes:d.crashes,restarts:d.restarts,nextInMs:w,external:y.external,lines:e.tail.snapshot()})),clearTimeout(d.pending),d.nextAt=Date.now()+w,d.pending=setTimeout(()=>{d.pending=void 0,d.nextAt=void 0,!(k||G.some(T=>T.name===i))&&(d.restarts+=1,qe(e.spec,"respawn"))},w),d.pending.unref?.()}u(rt,"ct"),a(rt,"workerEnded");function qe(e,t){const n=Ue(e.name);n.waiting=void 0;const i=e.port>0?[...te].find(o=>o.name===e.name&&!Re(o)):void 0;if(!i){ze(e,t);return}console.log(`[parent] Worker "${e.name}" starts once its predecessor (pid=${i.proc.pid}) has finished its work \u2014 it holds port ${e.port}`);const s=a(()=>{n.waiting===s&&(n.waiting=void 0),!k&&!G.some(o=>o.name===e.name)&&ze(e,t)},"go");n.waiting=s,i.proc.once("exit",s)}u(qe,"Ve"),a(qe,"startWorker");const ot=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(e)&&e>=0?e:15*6e4})(),nt=(()=>{const e=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(e)&&e>=1?Math.floor(e):1})(),te=new Set,Re=a(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"workerExited");function Be(e,t){if(te.delete(e),!Re(e)){console.error(`[parent] Worker "${e.name}" (pid=${e.proc.pid}) ${t} \u2014 killing it. A worker that returns from its SIGTERM handler but leaves a handle open (a Redis client handed to BullMQ is not closed by worker.close()) never exits on its own: close what it opened, or call process.exit().`);try{e.proc.kill("SIGKILL")}catch{}}}u(Be,"Je"),a(Be,"killDrainingWorker");function Qe(e){e.stopping=!0;try{e.proc.kill("SIGTERM")}catch{}if(Re(e))return;const t=[...te].filter(i=>i.name===e.name);for(;t.length>=nt;)Be(t.shift(),`was still running when a later reload replaced its successor (cap ${nt})`);te.add(e);const n=setTimeout(()=>Be(e,`was still running ${ot}ms after SIGTERM`),ot);n.unref?.(),e.proc.once("exit",()=>{clearTimeout(n),te.delete(e)})}u(Qe,"rt"),a(Qe,"retireWorker");function je(){for(const e of He.values())clearTimeout(e.pending),e.pending=void 0,e.nextAt=void 0,e.waiting=void 0}u(je,"Xe"),a(je,"cancelWorkerStarts");function st(){for(const e of[...G])Qe(e);G.length=0,je();for(const e of WORKER_SPECS)Ue(e.name).crashes=0,qe(e,"reload")}u(st,"lt"),a(st,"restartWorkers");function it(){const e=Date.now();return{workers:WORKER_SPECS.map(t=>{const n=G.find(o=>o.name===t.name),i=He.get(t.name),s=n?"running":i?.pending?(i.crashes??0)>=worker_supervisor_1.CRASH_LOOP_AFTER?"crash-looping":"restarting":i?.waiting?"waiting":i?.missing?"missing":i?.lastEnd?.verdict==="exited"?"exited":"stopped";return{name:t.name,state:s,port:t.port,env:Object.keys(t.env),...n?{pid:n.proc.pid,upMs:e-n.startedAt}:{},crashes:i?.crashes??0,restarts:i?.restarts??0,...i?.nextAt?{nextInMs:Math.max(0,i.nextAt-e)}:{},...i?.lastEnd?{lastEnd:i.lastEnd}:{},...i?.missing?{missing:i.missing}:{}}}),draining:[...te].filter(t=>!Re(t)).map(t=>({name:t.name,pid:t.proc.pid}))}}u(it,"dt"),a(it,"workersView");const ht=debounce(async()=>{ie+=1;const e=Y();if(e.length>0)if(Oe==="process")P();else{console.log(`[parent] Forwarding reload to ${e.length} child(ren)`);for(const t of e)tell(t.proc,{type:"reload"})}await Me(),WORKER_NAMES.length>0&&st()},200),at=a((e,t)=>{const n=(0,notice_generation_1.noticeGeneration)(e.headers);return n===void 0||n===POD_GENERATION?!1:(e.resume(),t.writeHead(409,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!1,generation:POD_GENERATION,sentFor:n})),e.url==="/webpack/reload"&&console.log(`[parent] a build of generation g${n} reached generation g${POD_GENERATION} \u2014 not reloaded: it is not this generation's build`),!0)},"refusedForAnotherGeneration"),Ie=a(async(e,t)=>{if(e.method==="POST"&&e.url==="/webpack/reload"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);if(at(e,t))return;t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0})),ce(e).then(s=>{const o=s;X=(0,service_build_events_1.buildAccountOf)(o?.build),be=0,ye(o?.watcher)}),ht();return}if(e.method==="POST"&&e.url==="/webpack/watching"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);if(at(e,t))return;const s=await ce(e);ye(s),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,relayed:ae!==void 0}));return}if(e.method==="POST"&&e.url==="/webpack/scale"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);let 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 Se(o),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,pods:o}))});return}if(e.method==="GET"&&e.url?.startsWith("/webpack/logs")){const s=new URL(e.url,"http://localhost").searchParams,o=Math.min(Math.max(Number(s.get("tail")??"100")||0,0),Z),y=s.get("follow")!=="0",d=s.get("plain")==="1",w=!(0,devserver_transport_1.isOwnerOnlyTransport)(e);t.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-cache"});const A=o===0?"":V.slice(-o).join(""),T=d?A.replace(F,""):A;if(t.write(w?(0,inspector_secret_1.redactInspectorUrls)(T):T),!y){t.end();return}const $={res:t,plain:d,redact:w};oe.add($),e.on("close",()=>oe.delete($));return}if(e.method==="POST"&&e.url?.startsWith("/webpack/debug")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const s=Number(new URL(e.url,"http://localhost").searchParams.get("port")||"");Number.isInteger(s)&&s>1024&&(M=s),M||(M=9229);const o=v.filter(d=>d.proc.exitCode===null&&d.proc.signalCode===null);for(const d of o)d.debugSlot<0&&(d.debugSlot=x()),tell(d.proc,{type:"debug-open",port:inspectorPortFor(M,d.debugSlot)});for(const d of G)try{d.proc.kill("SIGUSR1")}catch{}const y=Date.now()+2e3;for(;Date.now()<y&&o.some(d=>!d.inspectorUrl);)await new Promise(d=>setTimeout(d,50));t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,basePort:M,fixedPorts:usesFixedInspectorPorts(),pods:o.map(d=>({id:d.id,inspectorUrl:d.inspectorUrl??null})),workers:G.map(d=>({name:d.name,port:d.debugPort||(0,inspector_secret_1.inspectorPortOf)(d.inspectorUrl),inspectorUrl:d.inspectorUrl??null}))},null,2)+`
|
|
12
|
+
})()`),(0,bundle_parent_1.routeBundleRequires)(requested,resolved);const exports=eval(`require(${JSON.stringify(resolved)})`);try{const mod=eval("require.cache")[resolved];lastImportedModule=mod&&typeof mod=="object"?mod:void 0}catch{}return exports}u(importFresh,"importFresh"),a(importFresh,"importFresh");function debounce(d,_){let f=null;return(...m)=>{f&&clearTimeout(f),f=setTimeout(()=>d(...m),_)}}if(u(debounce,"debounce"),a(debounce,"debounce"),process.env.APP_RUNNER==="1"){(0,stdio_guard_1.guardBrokenStdio)();const d=a(f=>{if(!inspector.url())try{inspector.open(f,"127.0.0.1",!1)}catch(W){console.warn(`[child] inspector.open(${f}) failed (port taken by another devserver?) \u2014 falling back to a random port:`,W.message);try{inspector.open(0,"127.0.0.1",!1)}catch{}}const m=inspector.url();m&&tell(process,{type:"inspector-url",url:m})},"openInspector"),_=process.env.CHILD_DEBUG_PORT;if(_!==void 0&&_!==""){const f=Number(_);Number.isInteger(f)&&(f===0||f>1024)&&d(f)}try{require("@lensmcp/node-instrumentation/register")}catch{}(async()=>{let f=null,m=!1,W,re=!1;const Ve=(0,hot_swap_registries_1.registryPruningEnabled)(),fe=a((r,c)=>{const l=(0,hot_swap_registries_1.describePrune)(r,c);l&&console.log(l)},"logPrune");let j={app:null,handler:a((r,c)=>{c.statusCode=503,c.end("starting")},"handler"),inflight:0};const _e=(()=>{const r=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(r)&&r>=0?r:15*6e4})(),C=a(r=>{const c=globalThis.__lensmcpActiveWork;if(typeof c!="function")return{count:0};try{const l=c(r);return{count:Number(l?.count??0),...l?.oldestStartedAt?{oldestStartedAt:l.oldestStartedAt}:{}}}catch{return{count:0}}},"activeWork"),$e=a(r=>{const c=globalThis.__lensmcpStopWorkIntake;if(typeof c=="function")try{return c(r)}catch{return}},"stopWorkIntake"),ge=a(r=>{const c=globalThis.__lensmcpWorkIntakeReport;if(!(r===void 0||typeof c!="function"))try{return c(r)??void 0}catch{return}},"workIntakeReport"),ke=(()=>{const r=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(r)&&r>=1?Math.floor(r):1})(),F=new Set,Z=(()=>{const r=Number(process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS);return process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS!==void 0&&process.env.LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS!==""&&Number.isFinite(r)&&r>=0?r:3e4})(),V=a(r=>{if(!r.abandoned?.size)return 0;const c=Date.now();for(const[l,h]of r.abandoned)(l.writableEnded||c-h>=Z)&&r.abandoned.delete(l);return r.abandoned.size},"abandonedRunning"),oe=a(r=>{let c=0;for(const l of r.open??[])l.headersSent||(c+=1);return{unanswered:c+V(r),streams:Math.max(0,r.inflight-c),work:C(r.workGen).count}},"owedBy"),ne=a((r,c,l=`${c}s`)=>`${r} ${r===1?c:l}`,"plural");async function We(){if(Z<=0)return;const r=Date.now();let c=!1;for(;!(F.size<ke);){const l=F.values().next().value;if(!l||l.closed)break;const h=oe(l);if(h.unanswered===0&&h.work===0)break;const E=(l.drainingSince??r)+Z-Date.now();if(E<=0)break;c||(c=!0,console.log(`[child] swap held \u2014 the app replaced ${Math.round((Date.now()-(l.drainingSince??r))/100)/10}s ago is still `+[h.unanswered?`answering ${ne(h.unanswered,"request")}`:"",h.work?`running ${ne(h.work,"background job")}`:""].filter(Boolean).join(" and ")+`, and this pod keeps at most ${ke} replaced app(s) alive (LENSMCP_SWAP_MAX_DRAINING). The new build is applied when it is done \u2014 in ${Math.ceil(E/1e3)}s at the latest (LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS).`)),await new Promise(S=>{setTimeout(S,Math.min(100,E)).unref?.()})}c&&console.log(`[child] swap resumed after ${Date.now()-r}ms`)}u(We,"He"),a(We,"holdForOwedWork");const O=(0,swap_recycle_1.swapRecyclePolicy)();let we,se=0;const Je=(()=>{const r=Number(process.env.LENSMCP_POD_RETIRE_NOTICE_MS);return Number.isFinite(r)&&r>=0?r:3500})();let g=!1,b=!1;const v=(0,pod_memory_1.podMemoryPolicy)();let K=0;const x=new Set;let me=!1;const B=a(()=>{if(!me)return;let r=0;for(const c of x)c.deref()===void 0?x.delete(c):r+=1;return r},"liveContainers"),k=(0,pod_memory_1.createPodMemoryMonitor)({policy:v,state:a(()=>({gen:j.gen??0,swaps:se,...we===void 0?{}:{baseline:we},busy:m||re||J.size>0,lastBusyAt:D}),"state"),send:a(r=>{tell(process,r)},"send"),containers:B,counter:(0,pod_memory_1.createLiveObjectCounter)(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH)),onRetained:a(()=>Oe(),"onRetained"),gc:a(()=>(0,gc_notice_1.withGcNotice)(N,pod_memory_1.fullGc),"gc")}),H=a(()=>((0,gc_notice_1.withGcNotice)(N,pod_memory_1.fullGc)&&k.tracker.noteGc(),process.memoryUsage().heapUsed),"liveHeap"),U=(()=>{if(!(0,error_stack_release_1.errorFrameReleaseEnabled)())return null;try{const r=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH))+path.sep,c=`${path.sep}node_modules${path.sep}`,l=new Set(Object.keys(require.cache));return(0,error_stack_release_1.createErrorFrameReleaser)(require.cache,{skip:a(h=>l.has(h)||h.startsWith(r)&&!h.slice(r.length).includes(c)&&!h.slice(r.length).startsWith(`node_modules${path.sep}`),"skip")})}catch{return null}})();let ie=!1;function Te(){if(!(!U||ie))try{const r=U();r.errors>0&&console.log(`[child] read the stack of ${r.errors} Error object(s) that libraries created while loading and keep for good \u2014 unread, each held the functions that were on its stack, this bundle's included`)}catch(r){console.error("[child] could not release library error frames:",r),ie=!0}}u(Te,"De"),a(Te,"releaseLibraryErrorFrames");const J=new Map;let D=Date.now();const Fe=a(()=>O.settleMs<=0||!m&&!re&&J.size===0&&Date.now()-D>=O.settleMs,"settled");let Y;function ae(r){if(!(!O.enabled||g||b)){if(O.settleMs<=0){X(r);return}Y&&clearTimeout(Y),Y=setTimeout(()=>{Y=void 0,Fe()?X(r):ae(r)},O.settleMs),Y.unref?.()}}u(ae,"he"),a(ae,"recycleCheckWhenSettled");const be=a(()=>{if(O.stuckCloseMs<=0)return 0;const r=Date.now();let c=0;for(const l of J.values())r-l>=O.stuckCloseMs&&(c+=1);return c},"stuckCloses");function X(r){if(!O.enabled||g||b||!process.send)return;const c=v8.getHeapStatistics().heap_size_limit,l=a(E=>{const S=k.oldestRetained();return{swaps:se,usedBytes:E,limitBytes:c,stuckCloses:be(),settled:Fe(),...we===void 0?{}:{baselineBytes:we},...S?{retained:{generation:S.gen,ageMs:Date.now()-S.closedAt,gcs:S.gcs}}:{}}},"state");if(!(0,swap_recycle_1.recycleReason)(O,l(process.memoryUsage().heapUsed)))return;const h=(0,swap_recycle_1.recycleReason)(O,l(H()));h&&(g=!0,console.log(`[child] asking for a fresh pod ${r} \u2014 ${h}. This pod keeps serving until its successor is ready. Size the bound with LENSMCP_SWAP_RECYCLE_HEAP_FACTOR / _HEAP_RATIO / _MIN_MB / _RETAINED_MS, or turn it off with LENSMCP_SWAP_RECYCLE=0.`),tell(process,{type:"recycle-request",reason:h}))}u(X,"Q"),a(X,"considerRecycle");let ye;function Oe(){if(!O.enabled||O.retainedMs<=0||g||b)return;const r=k.oldestRetained();if(!r)return;const c=r.closedAt+O.retainedMs-Date.now();if(c<=0){X("with a closed generation still in memory");return}ye||(ye=setTimeout(()=>{ye=void 0,k.measure("retention-check").catch(()=>{})},c),ye.unref?.())}u(Oe,"je"),a(Oe,"retainedRecycleCheck");function Ee(r,c){const l={};c&&(l.module=c),r&&(l.app=r);try{const h=r?.app;if(h&&typeof h=="object"&&(l.nestApp=h,h.container&&typeof h.container=="object")){l.container=h.container;const E=rootModuleOf(h.container);E&&(l.rootModule=E)}}catch{}return l}u(Ee,"Ne"),a(Ee,"generationTargets");async function ce(r,c){if(r.closed||(r.closed=!0,F.delete(r),c&&console.error(`[child] ${c}`),!r.app))return;J.set(r,Date.now());const l=O.enabled&&O.stuckCloseMs>0?setTimeout(()=>{J.has(r)&&(console.error(`[child] a previous app has been closing for ${Math.round(O.stuckCloseMs/1e3)}s and its close() has not returned \u2014 one of its shutdown hooks is waiting on something that does not end (a queue worker, a connection, a stream). It stays in memory until this pod is replaced.`),X("with a previous app stuck in close()"))},O.stuckCloseMs):void 0;l?.unref?.();const h=r.app;try{await r.app.close()}catch(E){console.error("[child] error closing a previous app:",E)}finally{J.delete(r),D=Date.now(),l&&clearTimeout(l),r.app=null,r.abandoned=void 0,r.handler=(E,S)=>{S.statusCode=503,S.end("closed")},r.gen!==void 0&&k.closed(r.gen,se,Ee(h,r.module)),r.module=void 0}if(r.superseded){try{fe((0,hot_swap_registries_1.pruneRegistries)(r.superseded,"serve"),"after closing the previous app")}catch(E){console.error("[child] could not release the previous app's class registrations:",E)}r.superseded=void 0}ae("after closing the previous app")}u(ce,"me"),a(ce,"closeGeneration");async function le(r){const c=Date.now();r.drainingSince=c;const l=a(()=>({inflight:r.inflight+V(r),work:C(r.workGen).count}),"busy"),h=l();if(h.inflight>0||h.work>0){for(;F.size>=ke;){const I=F.values().next().value;if(!I)break;const $=oe(I),z=Math.round((Date.now()-(I.drainingSince??c))/1e3);if($.unanswered===0&&$.streams===0&&$.work===0){await ce(I);continue}await ce(I,`closing a still-draining generation early \u2014 ${F.size} were pending and the cap is ${ke} (each holds a whole app: DI container, DB pool, queue workers). `+($.unanswered>0||$.work>0?`It was replaced ${z}s ago and had still not answered ${ne($.unanswered,"request")}`+($.work?` or finished ${ne($.work,"background job")}`:"")+` \u2014 those fail now (a queue job keeps its lock until the TTL lapses). Raise LENSMCP_SWAP_EARLY_CLOSE_GRACE_MS (currently ${Z}ms) to wait longer for them. `:`It held only ${ne($.streams,"open stream")}; their clients reconnect to the new app. `)+"Raise LENSMCP_SWAP_MAX_DRAINING if this pod legitimately needs more.")}F.add(r)}for(;_e>0&&Date.now()-c<_e;){if(r.closed)return;const I=l();if(I.inflight===0&&I.work===0)break;await new Promise($=>{setTimeout($,250).unref?.()})}if(r.closed)return;const E=l(),S=ge(r.workGen);E.inflight>0||E.work>0?console.error(`[child] swap drain expired after ${Date.now()-c}ms \u2014 closing the previous app with ${E.inflight} in-flight request(s) and ${E.work} background job(s) still running. `+(S?`Previous app still processing ${S.running} queue job(s); ${S.takenAfterStop} were taken after the swap. `:"")+`A queue job killed here keeps its lock until the TTL lapses. Raise LENSMCP_SWAP_DRAIN_MS (currently ${_e}ms) if this is legitimate work.`):(Date.now()-c>250||S?.runningAtStop||S?.takenAfterStop)&&console.log(`[child] previous app drained in ${Date.now()-c}ms \u2014 closing it`+(S?` (it finished ${S.finishedAfterStop} queue job(s) after the swap; ${S.takenAfterStop} were taken after the swap)`:"")),await ce(r)}u(le,"ye"),a(le,"drainThenClose");async function de(){if(m)return re=!0,console.log("[child] Reload deferred \u2014 will re-swap after current swap completes"),f;m=!0,D=Date.now(),await We(),process.removeAllListeners("uncaughtException"),process.removeAllListeners("unhandledRejection"),process.on("uncaughtException",(P,ee)=>{console.error(`[child] uncaughtException (${ee}):`,P)}),process.on("unhandledRejection",P=>{const ee=P instanceof Error?P.stack||P.message:String(P);ee.includes("FronteggContextScope")||ee.includes("populateLoggerMetadata")||console.error("[child] unhandledRejection:",P)});let r;if(Ve)try{r=(0,hot_swap_registries_1.captureRegistries)()}catch{r=void 0}const c=global.__lensmcpBeginWorkGeneration,l=typeof c=="function"?c():void 0;try{try{await importFresh(BUNDLE_PATH)}catch(P){if(!(P instanceof SyntaxError))throw P;console.warn(`[child] bundle was unreadable mid-write (${P.message}) \u2014 retrying the swap once`),await new Promise(ee=>setTimeout(ee,400)),await importFresh(BUNDLE_PATH)}}catch(P){throw m=!1,D=Date.now(),P}if(typeof global.createChildApp!="function")throw m=!1,D=Date.now(),new Error(`Bundle '${BUNDLE_PATH}' does not export createChildApp() and the zero-touch bridge is not active. Either install @lensmcp/node-instrumentation (a plain NestFactory.create + app.listen main.ts then just works) or set global.createChildApp in main.ts when DEVSERVER_MODE === '1'.`);let h;if(r)try{h=(0,hot_swap_registries_1.supersededSince)(r),fe((0,hot_swap_registries_1.pruneRegistries)(h,"build"),"at the swap")}catch(P){console.error("[child] could not release superseded class registrations:",P)}let E;try{E=await global.createChildApp()}catch(P){throw m=!1,D=Date.now(),takeImportedModule(),P}const S=j;h?.size&&(S.app?S.superseded=h:fe((0,hot_swap_registries_1.pruneRegistries)(h,"serve"),"at the swap")),f=E;const I=takeImportedModule();j={app:E,handler:E.handler,inflight:0,gen:++K,...I?{module:I}:{},...l===void 0?{}:{workGen:l}};const $=Ee(E,void 0).container;$&&(x.add(new WeakRef($)),me=!0);const z=S.app&&l!==void 0?$e(l):void 0;return console.log("[child] Swapped to fresh app (previous draining in background)"+(z?.workers?`; its ${z.workers} queue worker(s) stopped taking new jobs, previous app still processing ${z.runningAtStop} job(s)`:"")),Te(),S.app&&(se+=1,le(S).catch(P=>console.error("[child] background close error:",P)),setTimeout(()=>X("30s after a hot swap"),3e4).unref?.(),k.swapped(S.gen,()=>S.closed===!0&&!J.has(S))),m=!1,D=Date.now(),re?(re=!1,de()):E}u(de,"Ee"),a(de,"swapNow");const Pe=debounce(async()=>{try{console.log("[child] /webpack/reload"),await de()}catch(r){console.error("[child] reload failed:",r)}},250),pe=http.createServer((r,c)=>{if(r.method==="POST"&&r.url==="/webpack/reload"){c.writeHead(200,{"content-type":"application/json"}),c.end(JSON.stringify({ok:!0})),Pe();return}if(r.method==="GET"&&r.url==="/__lensmcp/alive"){const h=r.headers["x-internal-token"],E=process.env.LENSMCP_SERVICE_KEY;if(E&&h!==E){c.writeHead(404,{"content-type":"text/plain"}),c.end("not found");return}const S=C();c.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),c.end(JSON.stringify({ok:!0,pid:process.pid,swapping:m,inflight:j.inflight,oldestInflightAt:j.oldestAt,activeWork:S.count,oldestWorkAt:S.oldestStartedAt,keyFingerprint:serviceKeyFingerprint(),...W?{watcher:W}:{},...Number.isFinite(Number(process.env.LENSMCP_POD_GENERATION))&&process.env.LENSMCP_POD_GENERATION?{podGeneration:Number(process.env.LENSMCP_POD_GENERATION)}:{}}));return}const l=j;l.inflight+=1,(l.open??=new Set).add(c),l.oldestAt===void 0&&(l.oldestAt=Date.now()),c.on("close",()=>{l.inflight-=1,l.open?.delete(c),Z>0&&!l.closed&&!c.headersSent&&!c.writableEnded&&((l.abandoned??=new Map).set(c,Date.now()),l.abandoned.size>256&&V(l)),l.inflight===0&&(l.oldestAt=void 0),k.activity()}),l.handler(r,c)});pe.keepAliveTimeout=0;const N=process.env.CHILD_SOCK_PATH;process.on("disconnect",()=>{cleanupSock(N),process.exit(0)});try{const r=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.join(__dirname,BUNDLE_PATH);if((0,schema_first_instance_1.schemaPrewarmEnabled)())try{const l=(0,schema_first_instance_1.prewarmZodFor)(r);l?.created&&console.log(`[child] zod${l.version?` ${l.version}`:""}: built ${l.created} throwaway schemas first, so none of the bundle's own is the first of its class`)}catch{}if((0,redis_disconnect_fix_1.redisDisconnectFixEnabled)())try{const l=(0,redis_disconnect_fix_1.finishStrandedDisconnectsFor)(r);l?.patched&&console.log(`[child] ioredis${l.versions.length?` ${l.versions.join(", ")}`:""}: a disconnect() between reconnect attempts now ends the client \u2014 it used to leave a queue worker's close() waiting for good`)}catch{}await de(),we=(await k.booted()).live,console.log(`[child] Using bundle: ${r}`),claimSock(N);let c=!1;pe.on("error",l=>{if(c){console.error("[child] server error:",l);return}console.error(`[child] could not listen on ${N} (${l.code??l.message}) \u2014 exiting; the devserver starts another pod`),tell(process,{type:"boot-error",error:`could not listen on ${N}: ${String(l?.stack||l)}`}),cleanupSock(N),process.exitCode=1,setTimeout(()=>process.exit(1),100)}),pe.listen(N,()=>{c=!0,console.log(`[child] Listening on ${N}`),tell(process,{type:"ready",socketPath:N})})}catch(r){console.error("[child] Startup error:",r),tell(process,{type:"boot-error",error:String(r?.stack||r)}),process.exitCode=1;return}process.on("message",async r=>{if(!(!r||typeof r!="object")){if(r.type==="debug-open"){const c=Number(r.port);d(Number.isInteger(c)&&c>1024?c:0);return}if(r.type==="watcher"){const c=r.testimony;c&&typeof c=="object"&&(W=c);return}if(r.type==="heap-snapshot"){Me(r);return}if(r.type==="recycle-declined"){g=!1;return}if(r.type==="retire"){q();return}if(r.type==="reload"){if(b)return;try{const c=Date.now();await de(),tell(process,{type:"reloaded",socketPath:N,swap:{generation:K,swaps:se,swapMs:Date.now()-c,draining:F.size}})}catch(c){console.error("[child] reload error:",c),tell(process,{type:"reload-error",error:String(c?.stack||c)})}}}});let Se=!1;async function Me(r){const c=a(l=>{tell(process,{type:"heap-snapshot-result",id:r.id,...l})},"reply");if(Se)return c({ok:!1,refused:"a snapshot of this pod is already being written"});Se=!0;try{const l=H(),h=k.tracker.views().map($=>$.gen),E=(0,heap_snapshot_1.heapSnapshotPolicy)();r.maxHeapBytes&&(E.maxHeapBytes=r.maxHeapBytes);const S=(0,heap_snapshot_1.heapSnapshotRefusal)(E,{live:l,...r.available?{available:r.available}:{}});if(S)return c({ok:!1,refused:S,live:l});console.log(`[child] writing a heap snapshot (${Math.round(l/1048576)} MB live) \u2014 the pod pauses while V8 serialises it`);const I=await(0,heap_snapshot_1.writeHeapSnapshot)(r.file);c({ok:!0,file:r.file,bytes:I.bytes,ms:I.ms,live:l,gen:j.gen??0,closedAlive:h})}catch(l){c({ok:!1,error:l?.message??String(l)})}finally{Se=!1}}u(Me,"Ye"),a(Me,"takeHeapSnapshot");async function q(r="a fresh pod has taken over"){if(b)return;b=!0,k.stop(),console.log(`[child] retiring \u2014 ${r}; ${path.basename(N,".sock")} (pid ${process.pid}) is finishing in-flight work, then exiting`);const c=$e(Number.POSITIVE_INFINITY);c?.workers&&console.log(`[child] its ${c.workers} queue worker(s) stopped taking new jobs, still processing ${c.runningAtStop} job(s)`);try{fs.writeFileSync(sockRetiringPath(N),String(process.pid),{flag:"w",mode:384})}catch{}await new Promise(h=>{setTimeout(h,Je).unref?.()}),cleanupSock(N),pe.close();const l=Date.now();for(;Date.now()-l<_e;){pe.closeIdleConnections?.();let h=0;for(const E of F)h+=oe(E).unanswered;if(j.inflight+V(j)===0&&h===0&&C().count===0)break;await new Promise(E=>{setTimeout(E,250).unref?.()})}setTimeout(()=>process.exit(0),3e4).unref?.();try{await f?.close()}catch(h){console.error("[child] close error while retiring:",h)}process.exit(0)}u(q,"B"),a(q,"retire"),process.on("beforeExit",()=>{try{inspector?.close?.()}catch{}});const ue=a(async r=>{console.log(`[child ${r}] shutting down\u2026`);const c=f?.close().catch(h=>console.error("[child] close error:",h)),l=new Promise(h=>pe.close(()=>h()));cleanupSock(N),setTimeout(()=>process.exit(0),700).unref(),await Promise.all([c,l]),process.exit(0)},"shutdown");["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(r=>{process.on(r,()=>{if(r==="SIGTERM"&&!b&&(0,handoff_retire_1.handoffRetireRequested)(SOCK_DIR,POD_GENERATION)){q("this generation was handed over to a newer one");return}inspector?.close?.(),ue(r)})})})()}else{let d=u(function(g){V.push(g),V.length>Z&&V.splice(0,V.length-Z),ke?.write((0,inspector_secret_1.redactInspectorUrls)(g.replace(F,"")));for(const b of oe)try{const v=b.plain?g.replace(F,""):g;b.res.write(b.redact?(0,inspector_secret_1.redactInspectorUrls)(v):v)}catch{oe.delete(b)}},"we");a(d,"emitLogLine");const _=12,f=process.env.LENSMCP_PROJECT||SERVICE_NAME||"service",m=(0,pod_memory_events_1.createPodMemoryPublisher)(process.env.LENSMCP_EVENT_FILE),W=a(g=>({project:f,service:SERVICE_NAME||f,pod:g.id,pid:g.proc.pid??0,podGeneration:POD_GENERATION}),"podIdentity"),re=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[31m"],Ve="\x1B[0m",fe=Math.max(1,Number(process.env.CHILD_COUNT||1)),j=LENSMCP_WS_KEY||path.basename(process.cwd()),_e=a(g=>(0,process_name_1.namedExecPath)((0,process_name_1.processName)(j,SERVICE_NAME||"service",g)),"execPathFor");let C=(()=>{const g=Number(process.env.LENSMCP_DEBUG_PORT||"");return Number.isInteger(g)&&g>1024?g:0})();const $e=20;C&&(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 (${C}+slot, workers ${C}+${$e}+i). Any account on this host can connect to 127.0.0.1:${C} 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 ge=process.env.LENSMCP_LOG_FILE||"",ke=ge?(()=>{try{fs.mkdirSync(path.dirname(ge),{recursive:!0});const g=fs.createWriteStream(ge,{flags:"a",mode:384});try{fs.chmodSync(ge,384)}catch{}return g}catch(g){return console.warn(`[parent] cannot open log file ${ge}:`,g.message),null}})():null,F=/\x1b\[[0-9;]*m/g,Z=2e3,V=[],oe=new Set,ne=(0,devserver_transport_1.gatewayManaged)();for(const g of["log","info","warn","error"]){const b=console[g].bind(console),v=g==="log"||g==="info"?process.stdout:process.stderr;console[g]=(...K)=>{b(...K.map(x=>typeof x=="string"?(0,inspector_secret_1.forStream)(v,ne,x):x)),d(K.map(x=>typeof x=="string"?x:util.inspect(x)).join(" ")+`
|
|
13
|
+
`)}}const We=a(g=>re[(g-1)%re.length],"colorFor"),O=a(g=>{if(fe===1)return"";const b=`[child#${g}] `;return`${We(g)}${b}${Ve}`},"tagFor"),we=a(g=>g.startsWith("{")&&g.endsWith("}"),"isJsonLog"),se=a((g,b,v)=>{const K=prettyFactory({sync:!0,colorize:!0,crlf:!0,messageKey:"message",errorLikeObjectKeys:["err","error"],errorProps:"type,message,stack",ignore:["logContext","context","hostname","req","res","err.driverError","module","cloudEnvironment","frontegg-application-id","frontegg-tenant-id","frontegg-trace-id","frontegg-vendor-id","host","service","version","err","error"].join(","),messageFormat:"{if module}[{module}] {end}{if context}[{context}] {end}{if logContext}[{logContext}] {end}{message}",customPrettifiers:{stack:a(B=>`
|
|
14
|
+
`+String(B),"stack")}}),x=a((B,k)=>{const H=B==="stdout"?process.stdout:process.stderr;try{v?.(k)}catch{}const U=we(k)?K(k):`${k}
|
|
15
|
+
`;H.write((0,inspector_secret_1.forStream)(H,ne,`${b}${U}`)),d(`${b}${U}`)},"write"),me=a((B,k)=>{if(!B)return;const H=readline.createInterface({input:B});H.on("line",U=>x(k,U)),H.on("close",()=>{})},"attach");me(g.stdout,"stdout"),me(g.stderr,"stderr")},"wireProcLogging"),Je=a(g=>se(g.proc,O(g.id),b=>g.tail.push(b)),"wireChildLogging");(async()=>{ensureOwnerOnlyDir(SOCK_DIR);const g=httpProxy.createProxyServer({});let b=Number(process.env.PORT)||0;b||(b=9090);const v=[],K=new Set;function x(){let e=0;for(;K.has(e);)e++;return K.add(e),e}u(x,"D"),a(x,"allocDebugSlot");let me=1,B=0,k=!1,H=fe,U=[],ie=0;const Te=(0,swap_mode_1.swapMode)(),J=(()=>{const e=Number(process.env.LENSMCP_POD_BOOT_GRACE_MS);return Number.isFinite(e)&&e>=0?e:12e4})(),D=a(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"childExited"),Fe=a(e=>e.booting&&!D(e)&&Date.now()-e.spawnedAt<J,"stillBooting");function Y(){return v.filter(e=>e.healthy&&typeof e.socketPath=="string")}u(Y,"J"),a(Y,"healthyChildren");let ae,be=0,X;const ye={project:f,service:SERVICE_NAME||f,podGeneration:POD_GENERATION};function Oe(e){const t=(0,service_build_events_1.buildAccountOf)(e.building);t&&t.startedAt!==be&&(be=t.startedAt,m.publish((0,service_build_events_1.buildServiceBuildEvent)(ye,"started",t,{root:process.cwd()})));const n=(0,service_build_events_1.buildAccountOf)(e.failed);n&&(be=0,m.publish((0,service_build_events_1.buildServiceBuildEvent)(ye,"failed",n,{root:process.cwd()})))}u(Oe,"je"),a(Oe,"recordBuildProgress");function Ee(e){if(!e||typeof e!="object")return;const t=e;if(t.schemaVersion===1){Oe(t),"failed"in t&&delete t.failed,ae=t;for(const n of v)tell(n.proc,{type:"watcher",testimony:t})}}u(Ee,"Ne"),a(Ee,"recordWatcherTestimony");function ce(e,t=256*1024){return new Promise(n=>{let i="",s=!1;e.on("data",o=>{s||(i+=o,i.length>t&&(s=!0))}),e.on("end",()=>{if(s||!i)return n(void 0);try{n(JSON.parse(i))}catch{n(void 0)}}),e.on("error",()=>n(void 0))})}u(ce,"me"),a(ce,"readJsonBody");function le(){const e=Y();if(e.length===0)return null;const t=B%e.length;return B=(B+1)%e.length,e[t]}u(le,"ye"),a(le,"pickChild");function de(e,t){const n=`Child#${e.id}`,i=SERVICE_NAME||f,s=Date.now();if(t.type==="pod-memory"){const o=t.report;if(!o||typeof o.live!="number")return;e.memory.latest=o,e.memory.history.push(o),e.memory.history.length>12&&e.memory.history.splice(0,e.memory.history.length-12),console.log(`[parent] ${(0,pod_memory_1.describePodMemory)(n,o)}`),m.publish((0,pod_memory_events_1.buildPodMemoryEvent)(W(e),o))}else if(t.type==="pod-memory-retained"){const o=t.retained;if(!o||typeof o.gen!="number")return;e.memory.retained.set(o.gen,{...o,at:s}),console.warn(`[parent] ${(0,pod_memory_1.describeRetained)(n,i,o)}`),m.publish((0,pod_memory_events_1.buildPodRetainedEvent)(W(e),o,s))}else{const o=t.released;if(!o||typeof o.gen!="number")return;e.memory.retained.delete(o.gen),console.log(`[parent] ${(0,pod_memory_1.describeReleased)(n,i,o)}`),m.publish((0,pod_memory_events_1.buildPodReleasedEvent)(W(e),o,s))}}u(de,"Ee"),a(de,"recordPodMemory");const Pe=new Map;let pe=0;async function N(){const e=me++,t=childSockPath(e);cleanupSock(t);const n=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&n.unshift("--require","@swc-node/register"),n.push(...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const i=C?x():-1,s=(0,node_child_process_1.fork)(__filename,{env:(0,child_process_env_1.childProcessEnv)({...process.env,APP_RUNNER:"1",CHILD_SOCK_PATH:t,...i>=0&&{CHILD_DEBUG_PORT:String(inspectorPortFor(C,i))}}),stdio:["inherit","pipe","pipe","ipc"],execArgv:n,execPath:_e("pod")}),o={id:e,proc:s,healthy:!1,lastError:null,debugSlot:i,tail:new exit_reason_1.TailBuffer,booting:!0,spawnedAt:Date.now(),bootReloadSeq:ie,memory:{history:[],retained:new Map}};return s.on("error",y=>console.error(`[parent] Child#${e}: ${y.message}`)),s.on("message",y=>{if(!y||typeof y!="object")return;const p=y;if(p.type==="ready")o.socketPath=String(p.socketPath),o.healthy=!0,o.booting=!1,console.log(`[parent] Child#${o.id} ready on socket ${o.socketPath}`),ae&&tell(s,{type:"watcher",testimony:ae}),ie!==o.bootReloadSeq&&(Te==="process"?P():tell(s,{type:"reload"}));else if(p.type==="recycle-request")S(o,String(p.reason||"it has outgrown its bound"));else if(p.type==="inspector-url")o.inspectorUrl=String(p.url),console.log(`[parent] Child#${o.id} Debugger listening on ${p.url}`);else if(p.type==="reloaded"){if(q.has(o)){console.log(`[parent] Child#${o.id} finished a swap it began before it was retired \u2014 not serving it: a fresh pod has taken over`);return}o.socketPath=String(p.socketPath),o.healthy=!0,console.log(`[parent] Child#${o.id} hot-swapped on socket ${o.socketPath}`);const w=p.swap;w&&typeof w.generation=="number"&&typeof w.swaps=="number"&&m.publish((0,service_build_events_1.buildServiceSwapEvent)(W(o),{generation:w.generation,swaps:w.swaps,swapMs:typeof w.swapMs=="number"?w.swapMs:0,draining:typeof w.draining=="number"?w.draining:0},X,{root:process.cwd()}))}else p.type==="reload-error"?(o.lastError=String(p.error||"unknown reload error"),console.error(`[parent] Child#${o.id} reload error: ${o.lastError}`),o.healthy=!1):p.type==="boot-error"?(o.lastError=String(p.error||"unknown boot error"),console.error(`[parent] Child#${o.id} boot error: ${o.lastError}`),o.healthy=!1,o.booting=!1):p.type==="pod-memory"||p.type==="pod-memory-retained"||p.type==="pod-memory-released"?de(o,p):p.type==="heap-snapshot-result"&&Pe.get(Number(p.id))?.(p)}),s.on("exit",(y,p)=>{o.booting=!1;for(const A of o.memory.retained.values()){const M={gen:A.gen,closedAt:A.closedAt,ageMs:Date.now()-A.closedAt,reason:"pod-exited"};console.log(`[parent] ${(0,pod_memory_1.describeReleased)(`Child#${o.id}`,SERVICE_NAME||f,M)}`),m.publish((0,pod_memory_events_1.buildPodReleasedEvent)(W(o),M,Date.now()))}o.memory.retained.clear(),o.memory.latest&&m.publish((0,pod_memory_events_1.buildPodExitedEvent)(W(o),{code:y,signal:p},Date.now())),o.debugSlot>=0&&(K.delete(o.debugSlot),o.debugSlot=-1);const w=p==="SIGINT"||p==="SIGTERM"||y===0;if(w?console.log(`[parent] Child#${o.id} exited cleanly (code=${y}, signal=${p??"none"})`):(console.error((0,exit_reason_1.crashReport)(`[parent] Child#${o.id} crashed (code=${y}, signal=${p??"none"}, pid=${o.proc.pid}, ${o.healthy?"was serving":"was not ready"})`,y,p,o.tail.snapshot())),o.lastError||(o.lastError=`Child exited abnormally (code=${y}, signal=${p??"none"})`)),o.healthy=!1,cleanupSock(o.socketPath,o.proc.pid),o.socketPath=void 0,!w&&!k){const A=v.indexOf(o);A>=0&&v.splice(A,1);const M=Date.now();if(U=U.filter(T=>M-T<3e4),U.length>=5){console.error(`[parent] crash-loop detected (${U.length} respawns/30s) \u2014 pausing auto-respawn; POST /webpack/reload to retry`);return}U.push(M),setTimeout(()=>{const T=v.filter(Q=>Q.proc.killed===!1).length;!k&&T<H&&(console.log(`[parent] respawning a crashed pod (${T}/${H} live)`),N().catch(()=>{}))},1500).unref?.()}}),v.push(o),Je(o),o}u(N,"N"),a(N,"spawnChild");async function Se(e){H=Math.max(H,e);const t=v.filter(i=>i.proc.killed===!1),n=e-t.length;for(let i=0;i<n;i++)await N()}u(Se,"be"),a(Se,"ensurePoolSize");async function Me(){const e=v.filter(t=>(!t.healthy||typeof t.socketPath!="string")&&!Fe(t));await Promise.all(e.map(async t=>{try{t.proc.kill("SIGTERM")}catch{}cleanupSock(t.socketPath,t.proc.pid),t.socketPath=void 0;const n=v.indexOf(t);n>=0&&v.splice(n,1),await N()}))}u(Me,"Ye"),a(Me,"respawnUnhealthy");const q=new Set;let ue=!1,r=0;const c=3e4,l=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return(Number.isFinite(e)&&e>=0?e:15*6e4)+6e4})();async function h(e,t={}){const n=Date.now(),i=await N(),s=Date.now()+J;for(;!i.healthy&&!i.lastError&&!D(i)&&Date.now()<s;){if(t.superseded?.()){const o=v.indexOf(i);o>=0&&v.splice(o,1);try{i.proc.kill("SIGTERM")}catch{}return{why:`a newer build landed while Child#${i.id} booted`,superseded:!0}}await new Promise(o=>{setTimeout(o,100).unref?.()})}if(k)return{why:"shutting down"};if(!i.healthy){const o=v.indexOf(i);o>=0&&v.splice(o,1);try{i.proc.kill("SIGTERM")}catch{}return{why:`its successor Child#${i.id} did not come up (${i.lastError??"no answer in time"})`}}return E(e),{fresh:i,readyMs:Date.now()-n}}u(h,"_"),a(h,"replacePod");function E(e){const t=v.indexOf(e);if(t>=0&&v.splice(t,1),e.healthy=!1,D(e))return;q.add(e),postRetiringNotice(e.socketPath,e.proc.pid);const n=setTimeout(()=>{if(!D(e)){console.error(`[parent] Child#${e.id} was still running ${l}ms after it was retired \u2014 killing it`);try{e.proc.kill("SIGKILL")}catch{}}},l);if(n.unref?.(),e.proc.once("exit",()=>{clearTimeout(n),q.delete(e)}),!tell(e.proc,{type:"retire"}))try{e.proc.kill("SIGTERM")}catch{}}u(E,"m"),a(E,"retirePod");async function S(e,t){const n=a(s=>{console.log(`[parent] Child#${e.id} asked for a fresh pod (${t}) \u2014 not now: ${s}`),tell(e.proc,{type:"recycle-declined"})},"decline");if(k||!v.includes(e))return;if(ue)return n("another pod is already being replaced");const i=Date.now()-r;if(i<c)return n(`a pod was replaced ${Math.round(i/1e3)}s ago`);ue=!0,console.log(`[parent] Child#${e.id} asked for a fresh pod \u2014 ${t}. Starting one; Child#${e.id} keeps serving until it is ready.`);try{const s=await h(e);if("why"in s){s.why!=="shutting down"&&n(s.why);return}r=Date.now(),console.log(`[parent] Child#${s.fresh.id} took over from Child#${e.id} (pid ${e.proc.pid} \u2192 ${s.fresh.proc.pid})`)}catch(s){n(`could not start a successor: ${s?.message??String(s)}`)}finally{ue=!1}}u(S,"y"),a(S,"recyclePod");let I,$=!1,z=0;function P(){if(I){$=!0;return}I=(async()=>{do{$=!1;const e=ie;for(;ue&&!k;)await new Promise(n=>{setTimeout(n,100).unref?.()});let t=!1;for(const n of Y().filter(i=>i.bootReloadSeq<e)){if(k)break;if(!(!v.includes(n)||!n.healthy)){ue=!0;try{ee(),console.log(`[parent] A new build \u2014 starting a fresh pod for it; Child#${n.id} keeps serving the previous build until it is ready.`);const i=await h(n,{superseded:a(()=>ie!==e&&(0,swap_mode_1.abandonSuperseded)(z),"superseded")});if("why"in i){if(i.superseded){z+=1,console.log(`[parent] ${i.why} \u2014 abandoned; one fresh pod for the newest build instead (${z} in a row). Child#${n.id} keeps serving.`),t=!0;break}i.why!=="shutting down"&&console.error(`[parent] Child#${n.id} keeps serving the previous build \u2014 ${i.why}`);continue}z=0,console.log(`[parent] Child#${i.fresh.id} took over from Child#${n.id} with the new build (pid ${n.proc.pid} \u2192 ${i.fresh.proc.pid}, ready in ${(i.readyMs/1e3).toFixed(1)}s while Child#${n.id} served)`),m.publish((0,service_build_events_1.buildServiceSwapEvent)(W(i.fresh),{generation:1,swaps:0,swapMs:i.readyMs,draining:q.size,handoff:{fromPid:n.proc.pid??0}},X,{root:process.cwd()}))}catch(i){console.error(`[parent] Child#${n.id} keeps serving the previous build \u2014 could not start a successor: ${i?.message??String(i)}`)}finally{ue=!1}}}t&&($=!0)}while($&&!k)})().finally(()=>{I=void 0})}u(P,"A"),a(P,"handoffForReload");function ee(){const e=(0,swap_mode_1.maxRetiring)(),t=[...q].filter(n=>!D(n));for(;t.length>=e;){const n=t.shift();console.error(`[parent] Child#${n.id} (pid ${n.proc.pid}) was still finishing its work when a newer build replaced its successor too \u2014 stopping it (LENSMCP_SWAP_MAX_RETIRING=${e})`);try{n.proc.kill("SIGTERM")}catch{}}}u(ee,"X"),a(ee,"capRetiring");const G=[],He=new Map,Ue=a(e=>{let t=He.get(e);return t||He.set(e,t={crashes:0,restarts:0}),t},"watchOf"),Xe=(0,worker_supervisor_1.workerBackoff)(),Ae=a((e,t)=>({project:f,service:SERVICE_NAME||f,worker:e,pid:t,podGeneration:POD_GENERATION}),"workerWho"),tt=[path.join(__dirname,"worker-guard.js"),path.join(__dirname,"worker-guard.ts")].find(e=>fs.existsSync(e));for(const e of WORKER_PROBLEMS)console.error(`[parent] ${e}`);function ze(e,t){const n=e.name,i=path.dirname(path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH)),s=path.join(i,`${n}.js`),o=Ue(n);if(!fs.existsSync(s))return console.error(`[parent] Worker "${n}" bundle not found: ${s}`),o.missing=s,m.publish((0,worker_supervisor_1.buildWorkerExitedEvent)(Ae(n,0),{ranMs:0,reason:`its bundle was not built (${path.basename(s)} is not in ${i})`})),null;o.missing=void 0;const y=(0,dev_devtool_1.sourceMapExecArgv)();__filename.endsWith(".ts")&&y.unshift("--require","@swc-node/register"),tt&&y.push("--require",tt);try{y.push("--require",require.resolve("@lensmcp/node-instrumentation/register"))}catch{}const p=inspectorPortFor(C||9229,$e+Math.max(0,WORKER_NAMES.indexOf(n)));y.push(C?`--inspect=127.0.0.1:${p}`:`--inspect-port=127.0.0.1:${p}`,...(0,inspector_secret_1.inspectorPublishExecArgv)(usesFixedInspectorPorts()));const w=(0,node_child_process_1.fork)(s,{env:(0,worker_supervisor_1.workerEnv)(process.env,e),stdio:["inherit","pipe","pipe","ipc"],execArgv:y,execPath:_e(`w-${n}`)}),A={name:n,spec:e,proc:w,debugPort:p,startedAt:Date.now(),tail:new exit_reason_1.TailBuffer,stopping:!1};G.push(A),w.on("error",T=>console.error(`[parent] Worker "${n}": ${T.message}`)),se(w,`\x1B[35m[worker:${n}] \x1B[0m`,T=>{A.tail.push(T);const Q=/Debugger listening on (wss?:\/\/\S+)/.exec(T);Q&&(A.inspectorUrl=Q[1])});const M=setTimeout(()=>{if(!(Re(A)||A.stopping)){if(o.crashes>0){const T=Date.now()-A.startedAt;console.log(`[parent] Worker "${n}" (pid=${w.pid}) is up again \u2014 ${(0,worker_supervisor_1.spanOf)(T)} without a crash, after ${o.crashes} in a row`),m.publish((0,worker_supervisor_1.buildWorkerUpEvent)(Ae(n,w.pid??0),{ranMs:T,afterCrashes:o.crashes}))}o.crashes=0}},Xe.stableMs);return M.unref?.(),w.on("exit",(T,Q)=>{clearTimeout(M);const ve=G.indexOf(A);ve>=0&&G.splice(ve,1),rt(A,T,Q)}),console.log(`[parent] Worker "${n}" started (pid=${w.pid}, PORT=${(0,worker_supervisor_1.workerEnv)(process.env,e).PORT}${t==="respawn"?`, restart ${o.restarts}`:""})`),m.publish((0,worker_supervisor_1.buildWorkerStartedEvent)(Ae(n,w.pid??0),{why:t,port:e.port,restarts:o.restarts})),A}u(ze,"Ze"),a(ze,"spawnWorkerProcess");function rt(e,t,n){const{name:i}=e,s=e.proc.pid??0,o=Date.now()-e.startedAt,y=(0,worker_supervisor_1.workerExitVerdict)(t,n,e.stopping||k);if(y.kind==="stopped")return;const p=Ue(i);if(y.kind==="exited"){p.lastEnd={at:Date.now(),pid:s,code:t,signal:n,ranMs:o,verdict:"exited"},console.warn(`[parent] Worker "${i}" (pid=${s}) exited on its own (code 0) after ${(0,worker_supervisor_1.spanOf)(o)} \u2014 not started again until the next build: a worker that ends is taken to have finished its work`),m.publish((0,worker_supervisor_1.buildWorkerExitedEvent)(Ae(i,s),{ranMs:o}));return}p.crashes+=1,p.lastEnd={at:Date.now(),pid:s,code:t,signal:n,ranMs:o,verdict:"crashed"};const w=(0,worker_supervisor_1.respawnDelay)(p.crashes,Xe),A=p.crashes>=worker_supervisor_1.CRASH_LOOP_AFTER;console.error((0,exit_reason_1.crashReport)(`[parent] Worker "${i}" crashed (code=${t}, signal=${n??"none"}, pid=${s}, after ${(0,worker_supervisor_1.spanOf)(o)})${y.external?" \u2014 stopped by a signal from outside its devserver":""}; starting it again in ${(0,worker_supervisor_1.spanOf)(w)}${A?` \u2014 ${p.crashes} crashes in a row: it is crash-looping (the wait doubles, up to ${(0,worker_supervisor_1.spanOf)(Xe.maxMs)})`:""}`,t,n,e.tail.snapshot())),m.publish((0,worker_supervisor_1.buildWorkerCrashedEvent)(Ae(i,s),{code:t,signal:n,ranMs:o,crashes:p.crashes,restarts:p.restarts,nextInMs:w,external:y.external,lines:e.tail.snapshot()})),clearTimeout(p.pending),p.nextAt=Date.now()+w,p.pending=setTimeout(()=>{p.pending=void 0,p.nextAt=void 0,!(k||G.some(M=>M.name===i))&&(p.restarts+=1,qe(e.spec,"respawn"))},w),p.pending.unref?.()}u(rt,"ct"),a(rt,"workerEnded");function qe(e,t){const n=Ue(e.name);n.waiting=void 0;const i=e.port>0?[...te].find(o=>o.name===e.name&&!Re(o)):void 0;if(!i){ze(e,t);return}console.log(`[parent] Worker "${e.name}" starts once its predecessor (pid=${i.proc.pid}) has finished its work \u2014 it holds port ${e.port}`);const s=a(()=>{n.waiting===s&&(n.waiting=void 0),!k&&!G.some(o=>o.name===e.name)&&ze(e,t)},"go");n.waiting=s,i.proc.once("exit",s)}u(qe,"Ve"),a(qe,"startWorker");const ot=(()=>{const e=Number(process.env.LENSMCP_SWAP_DRAIN_MS);return Number.isFinite(e)&&e>=0?e:15*6e4})(),nt=(()=>{const e=Number(process.env.LENSMCP_SWAP_MAX_DRAINING);return Number.isFinite(e)&&e>=1?Math.floor(e):1})(),te=new Set,Re=a(e=>e.proc.exitCode!==null||e.proc.signalCode!==null,"workerExited");function Be(e,t){if(te.delete(e),!Re(e)){console.error(`[parent] Worker "${e.name}" (pid=${e.proc.pid}) ${t} \u2014 killing it. A worker that returns from its SIGTERM handler but leaves a handle open (a Redis client handed to BullMQ is not closed by worker.close()) never exits on its own: close what it opened, or call process.exit().`);try{e.proc.kill("SIGKILL")}catch{}}}u(Be,"Je"),a(Be,"killDrainingWorker");function Qe(e){e.stopping=!0;try{e.proc.kill("SIGTERM")}catch{}if(Re(e))return;const t=[...te].filter(i=>i.name===e.name);for(;t.length>=nt;)Be(t.shift(),`was still running when a later reload replaced its successor (cap ${nt})`);te.add(e);const n=setTimeout(()=>Be(e,`was still running ${ot}ms after SIGTERM`),ot);n.unref?.(),e.proc.once("exit",()=>{clearTimeout(n),te.delete(e)})}u(Qe,"rt"),a(Qe,"retireWorker");function je(){for(const e of He.values())clearTimeout(e.pending),e.pending=void 0,e.nextAt=void 0,e.waiting=void 0}u(je,"Xe"),a(je,"cancelWorkerStarts");function st(){for(const e of[...G])Qe(e);G.length=0,je();for(const e of WORKER_SPECS)Ue(e.name).crashes=0,qe(e,"reload")}u(st,"lt"),a(st,"restartWorkers");function it(){const e=Date.now();return{workers:WORKER_SPECS.map(t=>{const n=G.find(o=>o.name===t.name),i=He.get(t.name),s=n?"running":i?.pending?(i.crashes??0)>=worker_supervisor_1.CRASH_LOOP_AFTER?"crash-looping":"restarting":i?.waiting?"waiting":i?.missing?"missing":i?.lastEnd?.verdict==="exited"?"exited":"stopped";return{name:t.name,state:s,port:t.port,env:Object.keys(t.env),...n?{pid:n.proc.pid,upMs:e-n.startedAt}:{},crashes:i?.crashes??0,restarts:i?.restarts??0,...i?.nextAt?{nextInMs:Math.max(0,i.nextAt-e)}:{},...i?.lastEnd?{lastEnd:i.lastEnd}:{},...i?.missing?{missing:i.missing}:{}}}),draining:[...te].filter(t=>!Re(t)).map(t=>({name:t.name,pid:t.proc.pid}))}}u(it,"dt"),a(it,"workersView");const ht=debounce(async()=>{ie+=1;const e=Y();if(e.length>0)if(Te==="process")P();else{console.log(`[parent] Forwarding reload to ${e.length} child(ren)`);for(const t of e)tell(t.proc,{type:"reload"})}await Me(),WORKER_NAMES.length>0&&st()},200),at=a((e,t)=>{const n=(0,notice_generation_1.noticeGeneration)(e.headers);return n===void 0||n===POD_GENERATION?!1:(e.resume(),t.writeHead(409,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!1,generation:POD_GENERATION,sentFor:n})),e.url==="/webpack/reload"&&console.log(`[parent] a build of generation g${n} reached generation g${POD_GENERATION} \u2014 not reloaded: it is not this generation's build`),!0)},"refusedForAnotherGeneration"),Ce=a(async(e,t)=>{if(e.method==="POST"&&e.url==="/webpack/reload"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);if(at(e,t))return;t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0})),ce(e).then(s=>{const o=s;X=(0,service_build_events_1.buildAccountOf)(o?.build),be=0,Ee(o?.watcher)}),ht();return}if(e.method==="POST"&&e.url==="/webpack/watching"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);if(at(e,t))return;const s=await ce(e);Ee(s),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,relayed:ae!==void 0}));return}if(e.method==="POST"&&e.url==="/webpack/scale"){if(!(0,devserver_transport_1.mayDriveThePool)(e))return refusePoolCommand(e,t);let 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 Se(o),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,pods:o}))});return}if(e.method==="GET"&&e.url?.startsWith("/webpack/logs")){const s=new URL(e.url,"http://localhost").searchParams,o=Math.min(Math.max(Number(s.get("tail")??"100")||0,0),Z),y=s.get("follow")!=="0",p=s.get("plain")==="1",w=!(0,devserver_transport_1.isOwnerOnlyTransport)(e);t.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-cache"});const A=o===0?"":V.slice(-o).join(""),M=p?A.replace(F,""):A;if(t.write(w?(0,inspector_secret_1.redactInspectorUrls)(M):M),!y){t.end();return}const T={res:t,plain:p,redact:w};oe.add(T),e.on("close",()=>oe.delete(T));return}if(e.method==="POST"&&e.url?.startsWith("/webpack/debug")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const s=Number(new URL(e.url,"http://localhost").searchParams.get("port")||"");Number.isInteger(s)&&s>1024&&(C=s),C||(C=9229);const o=v.filter(p=>p.proc.exitCode===null&&p.proc.signalCode===null);for(const p of o)p.debugSlot<0&&(p.debugSlot=x()),tell(p.proc,{type:"debug-open",port:inspectorPortFor(C,p.debugSlot)});for(const p of G)try{p.proc.kill("SIGUSR1")}catch{}const y=Date.now()+2e3;for(;Date.now()<y&&o.some(p=>!p.inspectorUrl);)await new Promise(p=>setTimeout(p,50));t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,basePort:C,fixedPorts:usesFixedInspectorPorts(),pods:o.map(p=>({id:p.id,inspectorUrl:p.inspectorUrl??null})),workers:G.map(p=>({name:p.name,port:p.debugPort||(0,inspector_secret_1.inspectorPortOf)(p.inspectorUrl),inspectorUrl:p.inspectorUrl??null}))},null,2)+`
|
|
16
16
|
`);return}if(e.method==="GET"&&e.url==="/webpack/workers"){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(it(),null,2)+`
|
|
17
17
|
`);return}if(e.method==="GET"&&e.url==="/webpack/memory"){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const s=path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),o=[...v,...q].map(y=>({id:y.id,pid:y.proc.pid??0,podGeneration:POD_GENERATION,healthy:y.healthy,retiring:q.has(y),latest:y.memory.latest??null,history:y.memory.history,retained:[...y.memory.retained.values()]}));t.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),t.end(JSON.stringify({ok:!0,service:SERVICE_NAME,project:f,bundle:{path:s},pods:o},null,2)+`
|
|
18
18
|
`);return}if(e.method==="POST"&&e.url?.startsWith("/webpack/heap")){if(!(0,devserver_transport_1.isOwnerOnlyTransport)(e)){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not found"}));return}const s=a((L,Le)=>{t.writeHead(L,{"content-type":"application/json"}),t.end(JSON.stringify(Le,null,2)+`
|
|
19
|
-
`)},"reply"),o=new URL(e.url,"http://localhost").searchParams,y=Number(o.get("pod")||""),
|
|
19
|
+
`)},"reply"),o=new URL(e.url,"http://localhost").searchParams,y=Number(o.get("pod")||""),p=o.has("maxMb")?Number(o.get("maxMb")):void 0;if(p!==void 0&&!(Number.isFinite(p)&&p>0)){s(400,{ok:!1,error:"maxMb takes a positive number of MB"});return}const w=Number.isInteger(y)&&y>0?v.find(L=>L.id===y):Y()[0];if(!w||D(w)){s(404,{ok:!1,error:y?`no pod #${y} \u2014 running: ${v.map(L=>`#${L.id}`).join(", ")||"none"}`:"no pod is serving"});return}if(Pe.size>0){s(409,{ok:!1,refused:"a heap snapshot is already being written for this service"});return}const A=(0,heap_snapshot_1.heapSnapshotPolicy)(),M=(0,heap_snapshot_1.heapSnapshotDir)();let T;try{(0,heap_snapshot_1.ensureHeapDir)(M);const L=(0,heap_snapshot_1.pruneHeapSnapshots)(M,A);L.length&&console.log(`[parent] removed ${L.length} older heap snapshot(s) from ${M}`),T=path.join(M,(0,heap_snapshot_1.heapSnapshotFileName)(SERVICE_NAME||f,w.id,w.proc.pid??0,w.memory.latest?.gen??0,Date.now()))}catch(L){s(500,{ok:!1,error:`cannot prepare ${M}: ${L.message}`});return}const Q=++pe,ve=(0,heap_snapshot_1.availableSystemMemory)();let Ge;const R=await new Promise(L=>{const Le=setTimeout(()=>L(void 0),6e5);Le.unref?.(),Pe.set(Q,mt=>{clearTimeout(Le),L(mt)}),Ge=a(()=>{clearTimeout(Le),L(void 0)},"onExit"),w.proc.once("exit",Ge);const wt={type:"heap-snapshot",id:Q,file:T,...ve?{available:ve}:{},...p!==void 0?{maxHeapBytes:Math.floor(p*1048576)}:{}};tell(w.proc,wt)||Ge()}).finally(()=>{Pe.delete(Q),Ge&&w.proc.off("exit",Ge)});if(!R){s(504,{ok:!1,pod:w.id,error:"the pod did not finish the snapshot (it exited, or took longer than 10 minutes)"});return}R.ok?console.log(`[parent] Child#${w.id} wrote a ${Math.round((R.bytes??0)/1048576)} MB heap snapshot in ${R.ms} ms \u2192 ${R.file}`):console.warn(`[parent] Child#${w.id} heap snapshot not taken: ${R.refused??R.error}`),s(R.ok?200:R.refused?409:500,{ok:R.ok,pod:w.id,pid:w.proc.pid??0,service:SERVICE_NAME,bundle:path.isAbsolute(BUNDLE_PATH)?BUNDLE_PATH:path.resolve(BUNDLE_PATH),...ve?{available:ve}:{},...R.file?{file:R.file,bytes:R.bytes,ms:R.ms}:{},...R.live!==void 0?{live:R.live}:{},...R.gen!==void 0?{gen:R.gen,closedAlive:R.closedAlive??[]}:{},...R.refused?{refused:R.refused}:{},...R.error?{error:R.error}:{}});return}const n=matchGatewayRoute(e);if(n?.prependPrefix&&!e.url?.startsWith(n.prependPrefix)&&(e.url=n.prependPrefix+(e.url??"/")),n?.target){applyGatewayMiddleware(e),g.web(e,t,{target:n.target,autoRewrite:typeof n.target=="string",changeOrigin:!0},s=>{console.error(`[parent] proxy error to ${n.target}:`,s),t.statusCode=502,t.setHeader("content-type","text/plain; charset=utf-8"),t.end(`Upstream error from ${n.target}.`)});return}if(SERVICE_PREFIX){if(!e.url?.startsWith(SERVICE_PREFIX)){t.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),t.end(`Not found. This service is mounted at ${SERVICE_PREFIX}/`);return}e.url=e.url.slice(SERVICE_PREFIX.length)||"/"}applyGatewayMiddleware(e);const i=le();if(!i){t.statusCode=503,t.setHeader("content-type","text/plain; charset=utf-8");const s=v.map(o=>`#${o.id}: ${o.lastError??"no error recorded"}`).join(`
|
|
20
20
|
`);t.end(`No healthy children available. POST /webpack/reload to recover.
|
|
21
21
|
|
|
22
22
|
Last errors:
|
|
23
23
|
${s}`);return}g.web(e,t,{target:{socketPath:i.socketPath},headers:{"x-proxy-child-id":String(i.id)}},s=>{console.error(`[parent] proxy error to Child#${i.id}:`,s),i.healthy=!1,i.lastError=String(s?.stack||s),t.statusCode=502,t.setHeader("content-type","text/plain; charset=utf-8"),t.end(`Upstream error from Child#${i.id}. Try /webpack/reload.
|
|
24
|
-
${i.lastError}`)})},"requestHandler");let
|
|
24
|
+
${i.lastError}`)})},"requestHandler");let he,Ie,Ze;const xe=[];if(GATEWAY_HTTPS){const e=require("./basic-ssl"),t=GATEWAY_ROUTES.map(i=>i.host).filter(i=>!!i),n=(0,checkout_cache_1.checkoutCacheDir)(process.cwd(),"davnx-webpack");Ie=e.getCertificateSync(n,SERVICE_NAME||"lensmcp.dev",t),Ze=e.caCertPath(),he=require("node:https").createServer({key:Ie,cert:Ie},Ce)}else he=http.createServer(Ce);const ct=a((e,t,n)=>{const i=matchGatewayRoute(e);if(i?.prependPrefix&&!e.url?.startsWith(i.prependPrefix)&&(e.url=i.prependPrefix+(e.url??"/")),i?.target){g.ws(e,t,n,{target:i.target,changeOrigin:!0},()=>t.destroy());return}const s=le();if(!s){t.destroy();return}g.ws(e,t,n,{target:{socketPath:s.socketPath}},()=>t.destroy())},"upgradeHandler");he.on("upgrade",ct);const lt=2e3;let dt=!1;he.on("error",e=>{if(e.code==="EADDRINUSE"){dt||(dt=!0,console.warn(`[parent] public port ${b} already in use \u2014 continuing on the unix-socket pool only (gateway routing is unaffected) and retrying the bind every ${lt/1e3}s. Give this service a distinct cluster.port if this is not a rolling handoff.`)),setTimeout(()=>{!k&&!he.listening&&he.listen(b)},lt).unref?.();return}console.error("[parent] public server error:",e)}),await Se(fe);for(const e of WORKER_SPECS)qe(e,"boot");SOCKET_ONLY?console.log(`[parent] socket-only: no TCP listener (port ${b} is not bound \u2014 the gateway reaches this service through its socket pool)`):he.listen(b,()=>{const e=GATEWAY_HTTPS?"https":"http";console.log(`[parent] Listening on ${e}://localhost:${b}`),SERVICE_PREFIX&&console.log(`[parent] Service prefix: "${SERVICE_PREFIX}" (enforced \u2014 requests without it will get 404)`),gatewayMiddleware&&console.log(`[parent] Gateway middleware: ACTIVE (${GATEWAY_MIDDLEWARE_PATH})`),GATEWAY_ROUTES.length>0&&console.log(`[parent] Gateway routes: ${GATEWAY_ROUTES.map(t=>`${t.host??"*"}${t.prefix??"/"}\u2192${t.target??"children"}`).join(" ")}`),Ze&&(console.log("[parent] HTTPS dev CA (trust ONCE, then rotations/new hostnames stay green):"),console.log(`[parent] sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${Ze}`)),console.log(`POST ${e}://localhost:${b}/webpack/reload to trigger rolling swap/respawn`)});const Ke=Number(process.env.INTERNAL_PORT||0);if(Ke>0&&!SOCKET_ONLY){const e=a((n,i)=>{const s=le();if(!s){i.statusCode=503,i.setHeader("content-type","text/plain; charset=utf-8"),i.end("No healthy children available.");return}g.web(n,i,{target:{socketPath:s.socketPath}},o=>{s.healthy=!1,s.lastError=String(o?.stack||o),i.statusCode=502,i.end(`Upstream error from Child#${s.id}.`)})},"internalHandler"),t=http.createServer(e);t.on("upgrade",(n,i,s)=>{const o=le();if(!o){i.destroy();return}g.ws(n,i,s,{target:{socketPath:o.socketPath}},()=>i.destroy())}),t.on("error",n=>{console.warn(`[parent] internal port ${Ke} unavailable (${n.code}).`)}),t.listen(Ke,()=>{console.log(`[parent] Internal (service-to-service, no gateway middleware) on http://localhost:${Ke}`)}),xe.push(t)}const ft=SOCKET_ONLY?[]:(()=>{try{return JSON.parse(process.env.GATEWAY_EXTRA_PORTS||"[]")}catch{return[]}})();for(const e of ft){if(!Number.isInteger(e)||e===Number(b))continue;const t=GATEWAY_HTTPS?require("node:https").createServer({key:Ie,cert:Ie},Ce):http.createServer(Ce);t.on("upgrade",ct),t.on("error",n=>{console.warn(`[parent] extra port ${e} unavailable (${n.code}) \u2014 main port still up.`)}),t.listen(e,()=>{console.log(`[parent] Also listening on ${GATEWAY_HTTPS?"https":"http"}://localhost:${e}`)}),xe.push(t)}const Ne=path.join(SOCK_DIR,"parent.sock");claimSock(Ne),(0,handoff_retire_1.clearHandoffRetire)(SOCK_DIR,POD_GENERATION);const De=http.createServer(Ce);De.on("error",e=>{console.warn(`[parent] control socket unavailable (${e.code}) \u2014 lensmcp logs/debug attach disabled.`)}),De.listen(Ne),xe.push(De);function pt(){k=!0;const e=[...v,...q];console.log(`[SIGTERM] [parent] generation g${POD_GENERATION} was handed over to a newer one \u2014 ${e.length} pod(s) finish their in-flight work, then it exits`);const t=sockOwnedByAnother(Ne);cleanupSock(Ne);for(const s of xe)if(!(s===De&&t))try{s.close()}catch{}try{he.close()}catch{}je();for(const s of[...G])Qe(s);G.length=0;for(const s of v)if(!tell(s.proc,{type:"retire"}))try{s.proc.kill("SIGTERM")}catch{}const n=setTimeout(()=>{for(const s of e)if(!D(s)){console.error(`[parent] Child#${s.id} was still running ${l}ms after its generation was retired \u2014 killing it`);try{s.proc.kill("SIGKILL")}catch{}}},l);n.unref?.();const i=a(()=>{if(!(e.some(s=>!D(s))||[...te].some(s=>!Re(s)))){clearTimeout(n);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",i);for(const s of te)s.proc.once("exit",i);i()}u(pt,"ht"),a(pt,"retireGeneration");const ut=a(async e=>{k=!0,console.log(`[${e}] [parent] shutting down\u2026`);const t=sockOwnedByAnother(Ne);cleanupSock(Ne);for(const n of xe)if(!(n===De&&t))try{n.close()}catch{}je();for(const n of G){n.stopping=!0;try{n.proc.kill("SIGTERM")}catch{}}for(const n of WORKER_SPECS){const i=G.find(s=>s.name===n.name)?.proc.pid??0;m.publish((0,worker_supervisor_1.buildWorkerStoppedEvent)(Ae(n.name,i),{reason:`its devserver stopped (${e})`}))}for(const n of[...te])Be(n,"was still draining when its devserver shut down");for(const n of q)try{n.proc.kill("SIGTERM")}catch{}for(const n of v){try{n.proc.kill("SIGTERM")}catch{}n.socketPath&&cleanupSock(n.socketPath,n.proc.pid)}try{fs.rmdirSync(SOCK_DIR)}catch{}setTimeout(()=>process.exit(0),700).unref()},"shutdown");let et=0;const _t=2e3;["SIGINT","SIGTERM","SIGHUP","SIGQUIT","SIGUSR2"].forEach(e=>process.on(e,()=>{if(e==="SIGTERM"){if(!k&&(0,handoff_retire_1.handoffRetireRequested)(SOCK_DIR,POD_GENERATION)){et=Date.now(),pt();return}if(et>0&&Date.now()-et<_t)return}ut(e)}));const Ye=Number(process.env.LENSMCP_GATEWAY_PID??0);if(Number.isInteger(Ye)&&Ye>0){const e=setInterval(()=>{try{process.kill(Ye,0)}catch(t){if(t.code==="EPERM")return;clearInterval(e),console.error(`[parent] gateway (pid ${Ye}) is gone \u2014 shutting the pod down to avoid an orphan tree.`),ut("gateway-gone")}},5e3);e.unref()}})()}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lensmcp/cluster",
|
|
3
|
-
"version": "1.25.
|
|
3
|
+
"version": "1.25.27",
|
|
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",
|
|
@@ -58,9 +58,9 @@
|
|
|
58
58
|
}
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@lensmcp/core": "1.25.
|
|
62
|
-
"@lensmcp/node-instrumentation": "1.25.
|
|
63
|
-
"@lensmcp/nx-plugin": "1.25.
|
|
61
|
+
"@lensmcp/core": "1.25.27",
|
|
62
|
+
"@lensmcp/node-instrumentation": "1.25.27",
|
|
63
|
+
"@lensmcp/nx-plugin": "1.25.27",
|
|
64
64
|
"fastify": "^5.8.5",
|
|
65
65
|
"@fastify/reply-from": "^12.6.2",
|
|
66
66
|
"@typescript/native-preview": "^7.0.0-dev.20260707.2",
|
package/process-name.d.ts
CHANGED
|
@@ -9,10 +9,19 @@ export declare const SWEEP_DELAY_MS = 60000;
|
|
|
9
9
|
/** Links one sweep removes at most. One batch costs one wait however long it is; this bounds the work. */
|
|
10
10
|
export declare const SWEEP_MAX_REMOVALS = 512;
|
|
11
11
|
/**
|
|
12
|
-
* `processName('foodguard', 'knowledge', 'pod')` → `foodguard-knowledge-pod`. The LAST part is the role
|
|
13
|
-
*
|
|
12
|
+
* `processName('foodguard', 'knowledge', 'pod')` → `foodguard-knowledge-pod`. The LAST part is the role and is kept
|
|
13
|
+
* whole. When the name is too long the parts before it are shortened, the EARLIER ones first: the first is the
|
|
14
|
+
* workspace (a worktree's key is long — `foodguard-onboarding-stream`) and the one before the role is the service,
|
|
15
|
+
* which is what tells one process from the next. It used to be cut away whole, so every service of that worktree was
|
|
16
|
+
* `foodguard-onboarding-stream-nx` (issues/closed/foodguard-93). Each part keeps at least {@link MIN_PART_CHARS}
|
|
17
|
+
* characters while there is room; the room left goes to the service, then to the parts before it.
|
|
14
18
|
*/
|
|
15
19
|
export declare function processName(...parts: Array<string | undefined>): string;
|
|
20
|
+
/**
|
|
21
|
+
* The name {@link processName} gave before 1.25.26: the head joined and cut from its END, so a long workspace label
|
|
22
|
+
* took the service's place. Only to recognise a process an older gateway started (the orphan reaper, foodguard-93).
|
|
23
|
+
*/
|
|
24
|
+
export declare function legacyProcessName(...parts: Array<string | undefined>): string;
|
|
16
25
|
/** Where the links may live, in order — the first on the node binary's volume wins. */
|
|
17
26
|
export declare function defaultLinkDirs(env?: NodeJS.ProcessEnv): string[];
|
|
18
27
|
export declare function processNamesEnabled(env?: NodeJS.ProcessEnv): boolean;
|
package/process-name.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var _=Object.defineProperty;var p=(t,e)=>_(t,"name",{value:e,configurable:!0});var d=Object.defineProperty,a=p((t,e)=>d(t,"name",{value:e,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0}),exports.SWEEP_MAX_REMOVALS=exports.SWEEP_DELAY_MS=exports.SWEEP_INTERVAL_MS=exports.STALE_AFTER_MS=exports.PROCESS_NAME_MAX=void 0,exports.processName=processName,exports.legacyProcessName=legacyProcessName,exports.defaultLinkDirs=defaultLinkDirs,exports.processNamesEnabled=processNamesEnabled,exports.namedExecPath=namedExecPath,exports.prelinkProcessNames=prelinkProcessNames,exports.sweepProcessNames=sweepProcessNames;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path"));exports.PROCESS_NAME_MAX=31,exports.STALE_AFTER_MS=336*60*6e4,exports.SWEEP_INTERVAL_MS=1440*6e4,exports.SWEEP_DELAY_MS=6e4,exports.SWEEP_MAX_REMOVALS=512;const USED_DIR=".used",SWEPT_STAMP=".swept",sanitize=a(t=>(t??"").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,""),"sanitize"),MIN_PART_CHARS=4;function processName(...t){const e=t.map(sanitize).filter(Boolean),r=e.pop();if(r===void 0)return"";if(e.length===0)return r.slice(0,exports.PROCESS_NAME_MAX);const s=r.slice(0,exports.PROCESS_NAME_MAX-2),l=exports.PROCESS_NAME_MAX-s.length-1,c=e.map(()=>0);let S=0;for(let n=e.length-1;n>=0;n-=1){const i=Math.min(e[n].length,MIN_PART_CHARS),o=i+(S>0?1:0);if(S+o>l)break;c[n]=i,S+=o}for(let n=e.length-1;n>=0&&c[n]>0;n-=1){const i=Math.min(e[n].length-c[n],l-S);c[n]=c[n]+i,S+=i}const u=e.map((n,i)=>n.slice(0,c[i]).replace(/-+$/,"")).filter(Boolean).join("-");return u?`${u}-${s}`:s}p(processName,"processName"),a(processName,"processName");function legacyProcessName(...t){const e=t.map(sanitize).filter(Boolean),r=e.pop();if(r===void 0)return"";if(e.length===0)return r.slice(0,exports.PROCESS_NAME_MAX);const s=r.slice(0,exports.PROCESS_NAME_MAX-2),l=e.join("-").slice(0,exports.PROCESS_NAME_MAX-s.length-1).replace(/-+$/,"");return l?`${l}-${s}`:s}p(legacyProcessName,"legacyProcessName"),a(legacyProcessName,"legacyProcessName");function defaultLinkDirs(t=process.env){const e=t.LENSMCP_HOME||os.homedir();return[path.join(os.tmpdir(),"lensmcp-process-names"),path.join(e,".lensmcp","process-names")]}p(defaultLinkDirs,"defaultLinkDirs"),a(defaultLinkDirs,"defaultLinkDirs");function processNamesEnabled(t=process.env){const e=(t.LENSMCP_PROCESS_NAMES??"").trim().toLowerCase();return!(e==="0"||e==="false"||e==="no"||e==="off")}p(processNamesEnabled,"processNamesEnabled"),a(processNamesEnabled,"processNamesEnabled");const ownedByMe=a(t=>typeof process.getuid!="function"||t.uid===process.getuid(),"ownedByMe");function privateDir(t){try{fs.mkdirSync(t,{recursive:!0,mode:448});const e=fs.lstatSync(t);return!e.isDirectory()||!ownedByMe(e)?!1:((e.mode&63)!==0&&fs.chmodSync(t,448),!0)}catch{return!1}}p(privateDir,"privateDir"),a(privateDir,"privateDir");function isPrivateDir(t){try{const e=fs.lstatSync(t);return e.isDirectory()&&ownedByMe(e)&&(e.mode&18)===0}catch{return!1}}p(isPrivateDir,"isPrivateDir"),a(isPrivateDir,"isPrivateDir");function isSameFile(t,e){try{const r=fs.lstatSync(t);return r.isFile()&&r.dev===e.dev&&r.ino===e.ino}catch{return!1}}p(isSameFile,"isSameFile"),a(isSameFile,"isSameFile");function noteUse(t,e,r=new Date){const s=path.join(t,USED_DIR,e);try{fs.utimesSync(s,r,r)}catch{try{fs.mkdirSync(path.dirname(s),{recursive:!0,mode:448}),fs.writeFileSync(s,"",{mode:384})}catch{}}}p(noteUse,"noteUse"),a(noteUse,"noteUse");const resolved=new Map;function namedExecPath(t,e={}){const r=e.execPath??process.execPath,s=e.env??process.env,l=e.platform??process.platform,c=processName(t);if(!c||l==="win32"||!processNamesEnabled(s))return r;const S=e.dirs??defaultLinkDirs(s),u=`${r}|${c}|${S.join("|")}`;scheduleSweep(S);let n,i;try{n=fs.realpathSync(r),i=fs.statSync(n)}catch{return r}const o=resolved.get(u);if(o&&isSameFile(o.link,i))return noteUse(o.dir,o.name),o.link;for(const m of S){if(!privateDir(m))continue;const f=path.join(m,`${i.dev}-${i.ino}`);if(!privateDir(f))continue;const E=path.join(f,c);if(!isSameFile(E,i)){try{fs.unlinkSync(E)}catch{}try{fs.linkSync(n,E)}catch{}}if(isSameFile(E,i))return resolved.set(u,{link:E,dir:f,name:c}),noteUse(f,c),E}return r}p(namedExecPath,"namedExecPath"),a(namedExecPath,"namedExecPath");function prelinkProcessNames(t,e={}){const r=[];for(const s of new Set([...t].filter(Boolean)))r.push(namedExecPath(s,e));return r}p(prelinkProcessNames,"prelinkProcessNames"),a(prelinkProcessNames,"prelinkProcessNames");function sweepProcessNames(t={}){const e={removed:[],adopted:0,skipped:0},r=t.now??Date.now(),s=t.staleAfterMs??exports.STALE_AFTER_MS,l=t.maxRemovals??exports.SWEEP_MAX_REMOVALS;for(const c of t.dirs??defaultLinkDirs()){if(!isPrivateDir(c))continue;const S=path.join(c,SWEPT_STAMP);if(!t.force)try{if(r-fs.statSync(S).mtimeMs<exports.SWEEP_INTERVAL_MS){e.skipped+=1;continue}}catch{}try{fs.writeFileSync(S,"",{mode:384}),fs.utimesSync(S,new Date(r),new Date(r))}catch{continue}let u;try{u=fs.readdirSync(c).filter(n=>/^\d+-\d+$/.test(n)).map(n=>path.join(c,n))}catch{continue}for(const n of u){if(!isPrivateDir(n))continue;let i;try{i=fs.readdirSync(n).filter(o=>o!==USED_DIR)}catch{continue}for(const o of i){const m=path.join(n,o);try{if(!fs.lstatSync(m).isFile())continue}catch{continue}let f;try{f=fs.statSync(path.join(n,USED_DIR,o)).mtimeMs}catch{noteUse(n,o,new Date(r)),e.adopted+=1;continue}if(!(r-f<s||e.removed.length>=l))try{fs.unlinkSync(m),e.removed.push(m),fs.rmSync(path.join(n,USED_DIR,o),{force:!0})}catch{}}try{for(const o of fs.readdirSync(path.join(n,USED_DIR)))fs.existsSync(path.join(n,o))||fs.rmSync(path.join(n,USED_DIR,o),{force:!0})}catch{}try{fs.readdirSync(n).every(o=>o===USED_DIR)&&(fs.rmSync(path.join(n,USED_DIR),{recursive:!0,force:!0}),fs.rmdirSync(n))}catch{}}}return e}p(sweepProcessNames,"sweepProcessNames"),a(sweepProcessNames,"sweepProcessNames");const sweepScheduled=new Set;function scheduleSweep(t){const e=t.join("|");sweepScheduled.has(e)||(sweepScheduled.add(e),setTimeout(()=>{try{sweepProcessNames({dirs:t})}catch{}},exports.SWEEP_DELAY_MS).unref?.())}p(scheduleSweep,"scheduleSweep"),a(scheduleSweep,"scheduleSweep");
|
|
@@ -21,6 +21,8 @@ export interface BuildAccount {
|
|
|
21
21
|
endedAt?: number;
|
|
22
22
|
changedFiles: string[];
|
|
23
23
|
moreChanged?: number;
|
|
24
|
+
/** A build that failed because the COMPILER did (not a module error): why — `ENOSPC: no space left on device…`. */
|
|
25
|
+
error?: string;
|
|
24
26
|
}
|
|
25
27
|
/** What a pod says of the swap it just made (the `reloaded` IPC message). */
|
|
26
28
|
export interface SwapReport {
|
package/service-build-events.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var f=Object.defineProperty;var c=(r,e)=>f(r,"name",{value:e,configurable:!0});var p=Object.defineProperty,i=c((r,e)=>p(r,"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,MAX_ERROR_CHARS=500;let idCounter=0;function makeId(){return idCounter=(idCounter+1)%65535,`${Date.now().toString(36)}${idCounter.toString(36)}${Math.random().toString(36).slice(2,8)}`}c(makeId,"makeId"),i(makeId,"makeId");function workspaceRelative(r,e){return r.slice(0,MAX_FILES).map(t=>{if(!e||!path.isAbsolute(t))return t;const o=path.relative(e,t);return o&&!o.startsWith("..")&&!path.isAbsolute(o)?o.split(path.sep).join("/"):t})}c(workspaceRelative,"workspaceRelative"),i(workspaceRelative,"workspaceRelative");function buildAccountOf(r){if(!r||typeof r!="object")return;const e=r;if(typeof e.startedAt!="number"||!Number.isFinite(e.startedAt)||e.startedAt<=0)return;const t=Array.isArray(e.changedFiles)?e.changedFiles.filter(o=>typeof o=="string"&&o.length>0&&o.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)}:{},...typeof e.error=="string"&&e.error.trim()?{error:e.error.trim().slice(0,MAX_ERROR_CHARS)}:{}}}c(buildAccountOf,"buildAccountOf"),i(buildAccountOf,"buildAccountOf");function envelope(r,e,t,o,s,n,a){const d="pending";return{id:a(),sessionId:d,timestamp:e,source:"gateway",category:"cluster",severity:t,context:{sessionId:d,projectName:r.project},fingerprint:`cluster:${r.project}:${o}`,title:s,raw:{kind:o,...n,project:r.project,service:r.service,podGeneration:r.podGeneration}}}c(envelope,"envelope"),i(envelope,"envelope");const filesText=i((r,e)=>{const t=r+e;return t===0?"no source change":`${t} file${t===1?"":"s"}`},"filesText"),seconds=i(r=>r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`,"seconds");function buildServiceBuildEvent(r,e,t,o={}){const s=workspaceRelative(t.changedFiles,o.root),n=t.moreChanged??0,a=o.at??(e==="failed"?t.endedAt??Date.now():t.startedAt),d=t.endedAt!==void 0?Math.max(0,t.endedAt-t.startedAt):void 0,l=e==="failed"&&t.error?t.error.split(`
|
|
2
|
+
`)[0].slice(0,160):void 0,u=e==="started"?`build started: ${r.project} \u2014 ${filesText(s.length,n)}`:`build failed: ${r.project} \u2014 ${l??filesText(s.length,n)}${d!==void 0?` \xB7 ${seconds(d)}`:""} \xB7 nothing was swapped, the pod serves the last good build`;return envelope(r,a,e==="failed"?"warning":"info","service-build",u,{phase:e,startedAt:t.startedAt,...t.endedAt!==void 0?{endedAt:t.endedAt,compileMs:d}:{},changedFiles:s,...n>0?{moreChanged:n}:{},...e==="failed"&&t.error?{error:t.error}:{}},o.id??makeId)}c(buildServiceBuildEvent,"buildServiceBuildEvent"),i(buildServiceBuildEvent,"buildServiceBuildEvent");function buildServiceSwapEvent(r,e,t,o={}){const s=o.at??Date.now(),n=workspaceRelative(t?.changedFiles??[],o.root),a=t?.moreChanged??0,d=t?.endedAt!==void 0?Math.max(0,t.endedAt-t.startedAt):void 0,l=e.handoff?`swap: ${r.project} \u2014 a fresh pod on the new build`+(t?` \xB7 ${filesText(n.length,a)}`:"")+(d!==void 0?` \xB7 compiled in ${seconds(d)}`:"")+` \xB7 ready in ${seconds(e.swapMs)} while the previous pod served`:`swap: ${r.project} \u2014 generation ${e.generation} (${e.swaps} swap${e.swaps===1?"":"s"})`+(t?` \xB7 ${filesText(n.length,a)}`:"")+(d!==void 0?` \xB7 compiled in ${seconds(d)}`:"")+` \xB7 swapped in ${seconds(e.swapMs)}`;return envelope(r,s,"info","service-swap",l,{pod:r.pod,pid:r.pid,generation:e.generation,swaps:e.swaps,swappedAt:s,swapMs:e.swapMs,draining:e.draining,...e.handoff?{handoff:{fromPid:e.handoff.fromPid}}:{},...t?{compile:{startedAt:t.startedAt,...t.endedAt!==void 0?{endedAt:t.endedAt,ms:d}:{}},changedFiles:n,...a>0?{moreChanged:a}:{}}:{}},o.id??makeId)}c(buildServiceSwapEvent,"buildServiceSwapEvent"),i(buildServiceSwapEvent,"buildServiceSwapEvent");
|
package/shared-build/host.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export interface BuildHostOptions {
|
|
|
11
11
|
webpack?: WebpackFactory;
|
|
12
12
|
/** Default {@link DEFAULT_PAUSE_MS}. */
|
|
13
13
|
pauseMs?: number;
|
|
14
|
+
/** The waits before compiling again after the compiler failed outright. Default {@link RETRY_AFTER_FAILURE_MS}. */
|
|
15
|
+
retryDelaysMs?: readonly number[];
|
|
14
16
|
}
|
|
15
17
|
/** Run `fn` with `process.env` replaced by `env` — synchronously, and restored whatever happens. */
|
|
16
18
|
export declare function withEnv<T>(env: Record<string, string | undefined>, fn: () => T): T;
|
|
@@ -43,6 +45,11 @@ export declare class BuildHost {
|
|
|
43
45
|
private kick;
|
|
44
46
|
private createGroup;
|
|
45
47
|
private membersOf;
|
|
48
|
+
/**
|
|
49
|
+
* The compile after a failure: webpack's watcher stopped watching when the compiler failed, and only a new compile
|
|
50
|
+
* (with what changed meanwhile) watches again (compile-retry.ts, issues/closed/foodguard-91).
|
|
51
|
+
*/
|
|
52
|
+
private compileAgain;
|
|
46
53
|
private onBuild;
|
|
47
54
|
private tellBuilt;
|
|
48
55
|
private closeGroup;
|
package/shared-build/host.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)[0]})`;return this.opts.log(`${t.project}: compiles on its own \u2014 ${
|
|
3
|
-
`)[0]})`;return this.opts.log(`${t.project}: compiles on its own \u2014 ${
|
|
4
|
-
`)),a=e.toldFiles.get(t)!==n;e.toldFiles.set(t,n),this.tell(t,{type:"built",ok:
|
|
1
|
+
"use strict";var j=Object.defineProperty;var f=(p,e)=>j(p,"name",{value:e,configurable:!0});var v=Object.defineProperty,h=f((p,e)=>v(p,"name",{value:e,configurable:!0}),"h");Object.defineProperty(exports,"__esModule",{value:!0}),exports.BuildHost=exports.DEFAULT_PAUSE_MS=void 0,exports.withEnv=withEnv,exports.buildTargetString=buildTargetString;const tslib_1=require("tslib"),node_crypto_1=require("node:crypto"),path=tslib_1.__importStar(require("node:path")),checkout_cache_1=require("../checkout-cache"),compile_retry_1=require("../compile-retry"),dev_devtool_1=require("../dev-devtool"),create_webpack_dev_1=require("../create-webpack-dev"),perf_rules_plugin_1=require("../perf/perf-rules-plugin"),signature_1=require("./signature"),shared_compilation_1=require("./shared-compilation");exports.DEFAULT_PAUSE_MS=5e3;function withEnv(p,e){const t={...process.env};for(const r of Object.keys(process.env))delete process.env[r];for(const[r,o]of Object.entries(p))o!==void 0&&(process.env[r]=o);try{return e()}finally{for(const r of Object.keys(process.env))delete process.env[r];Object.assign(process.env,t)}}f(withEnv,"withEnv"),h(withEnv,"withEnv");function buildTargetString(p){return`${p.project}:${p.target}${p.configuration?`:${p.configuration}`:""}`}f(buildTargetString,"buildTargetString"),h(buildTargetString,"buildTargetString");const shortHash=h(p=>(0,node_crypto_1.createHash)("sha256").update(p).digest("hex").slice(0,16),"shortHash");class BuildHost{static{f(this,"BuildHost")}static{h(this,"BuildHost")}constructor(e){this.opts=e,this.groups=new Map,this.members=new Map,this.stopped=!1,this.pauseMs=e.pauseMs??exports.DEFAULT_PAUSE_MS,this.webpack=e.webpack??require("webpack")}tell(e,t){this.opts.send({type:"member",member:e,event:t})}describe(){return[...this.groups.values()].map(e=>({group:e.key,projects:e.registry.projects()}))}evaluate(e){const t=e.options;if(t.webpackConfigPath)try{delete require.cache[require.resolve(path.resolve(t.appRoot,t.webpackConfigPath))]}catch{}const r={...e.env,NODE_ENV:"development",NX_BUILD_TARGET:buildTargetString(e),NX_WORKSPACE_ROOT:this.opts.root,LENSMCP_TYPECHECK:"off"},o=withEnv(r,()=>(0,create_webpack_dev_1.createDevWebpackConfig)(t)),s=(0,signature_1.transpileCompilerOptions)(t.tsConfig,this.opts.root),n=(0,signature_1.memberSignature)({join:e,devtool:o.devtool,config:o,compilerOptions:s});return{config:o,signature:n}}join(e,t){if(this.stopped)return this.tell(e,{type:"refused",reason:"the build host is stopping"});this.leave(e,{quiet:!0});const r=(0,signature_1.refusalOf)(t,this.opts.root);if(r)return this.opts.log(`${t.project}: compiles on its own \u2014 ${r}`),this.tell(e,{type:"refused",reason:r});let o;try{o=this.evaluate(t)}catch(c){const i=`its webpack config could not be built here (${(c?.message??String(c)).split(`
|
|
2
|
+
`)[0]})`;return this.opts.log(`${t.project}: compiles on its own \u2014 ${i}`),this.tell(e,{type:"refused",reason:i})}let s=this.groups.get(o.signature.key);if(!s){for(const c of this.groups.values()){const i=(0,signature_1.describeDifference)(o.signature,c.signature);this.opts.log(`${t.project}: compiled apart from ${c.registry.projects().sort().join(", ")||"the other group"} \u2014 ${i??"its compile signature differs"}`);break}try{s=this.createGroup(o,t)}catch(c){const i=`the shared compiler could not be created (${(c?.message??String(c)).split(`
|
|
3
|
+
`)[0]})`;return this.opts.log(`${t.project}: compiles on its own \u2014 ${i}`),this.tell(e,{type:"refused",reason:i})}this.groups.set(s.key,s)}this.members.set(e,{project:t.project,group:s});const n=s.projects.get(t.project)??new Set;n.add(e);const a=!s.projects.has(t.project);s.projects.set(t.project,n);const l=s.pausing.get(t.project);if(l&&(clearTimeout(l),s.pausing.delete(t.project)),this.tell(e,{type:"accepted",group:s.key,projects:[...s.projects.keys()]}),a)s.registry.set(t.project,(0,shared_compilation_1.memberEntries)(t.project,t.options)),this.opts.log(`shared compilation ${s.key.slice(0,8)}: ${s.registry.projects().sort().join(", ")}`),this.kick(s);else{const c=s.last.get(t.project);c&&this.tellBuilt(s,e,c)}}leave(e,t={}){const r=this.members.get(e);if(!r)return;this.members.delete(e);const{project:o,group:s}=r;s.told.delete(e),s.toldFiles.delete(e);const n=s.projects.get(o);if(n?.delete(e),n&&n.size>0)return;t.quiet||this.opts.log(`${o}: no member left \u2014 its entries pause in ${Math.round(this.pauseMs/1e3)} s`);const a=setTimeout(()=>this.pause(s,o),this.pauseMs);a.unref?.(),s.pausing.set(o,a)}pause(e,t){if(e.pausing.delete(t),!((e.projects.get(t)?.size??0)>0)){if(e.projects.delete(t),e.registry.delete(t),e.last.delete(t),e.projects.size===0){this.opts.log(`shared compilation ${e.key.slice(0,8)}: no service left \u2014 closed`),this.groups.delete(e.key),this.closeGroup(e);return}this.opts.log(`shared compilation ${e.key.slice(0,8)}: ${t} paused \u2014 ${e.registry.projects().sort().join(", ")}`),this.kick(e)}}kick(e){if(e.watching){e.watching.invalidate();return}e.watching=e.compiler.watch(e.watchOptions,(t,r)=>this.onBuild(e,t,r))}createGroup(e,t){const r=e.signature.key,o=new shared_compilation_1.EntryRegistry,s=t.options,n=e.config,a=n.devtool,l=path.join((0,checkout_cache_1.checkoutCacheDir)(this.opts.root,"lensmcp-build"),r,"out"),c=(0,create_webpack_dev_1.devCacheOptions)(s,a),i={key:r,signature:e.signature,registry:o,projects:new Map,pausing:new Map,last:new Map,told:new Map,toldFiles:new Map,compiler:void 0,watching:void 0,watchOptions:{},sourceMaps:!1,webpackVersion:"",retry:(0,compile_retry_1.createFailureRetry)(()=>this.compileAgain(i),this.opts.retryDelaysMs??compile_retry_1.RETRY_AFTER_FAILURE_MS)},u=n.plugins.filter(m=>!signature_1.PER_SERVICE_PLUGINS.has(m?.constructor?.name));u.push(new perf_rules_plugin_1.PerfRulesPlugin({project:t.project,workspaceRoot:this.opts.root,tsConfig:s.tsConfig,entries:h(()=>o.entryProjects(),"entries")}),new shared_compilation_1.SharedEntriesPlugin({registry:o,workspaceRoot:this.opts.root,outputPath:l,cache:{...c,name:`shared-${r}`,version:`${c.version}-${r}`}}),{apply:h(m=>{m.hooks.watchRun.tap("LensmcpSharedBuild",y=>{const w=[...y.modifiedFiles??[],...y.removedFiles??[]].filter(b=>typeof b=="string").slice(-32);for(const b of this.membersOf(i))this.tell(b,{type:"watch-run",paths:w})}),m.hooks.watchClose.tap("LensmcpSharedBuild",()=>{for(const y of this.membersOf(i))this.tell(y,{type:"watch-closed"})})},"apply")});const g={...n,plugins:u};delete g.watch,i.watchOptions=n.watchOptions??{};const d={...t.env,NODE_ENV:"development",NX_BUILD_TARGET:buildTargetString(t),NX_WORKSPACE_ROOT:this.opts.root,LENSMCP_TYPECHECK:"off"};return i.compiler=withEnv(d,()=>this.webpack(g)),i.sourceMaps=(0,dev_devtool_1.bundleCarriesSourceMaps)(i.compiler.options.devtool),i.webpackVersion=String(i.compiler.webpack?.version??"5"),i}membersOf(e){const t=[];for(const r of e.projects.values())t.push(...r);return t}compileAgain(e){this.stopped||this.groups.get(e.key)!==e||!e.watching||(this.opts.log(`shared compilation ${e.key.slice(0,8)}: compiling again after the failure`),e.watching.invalidate())}onBuild(e,t,r){if(this.stopped)return;if(t){const i=t?.message??String(t),{delayMs:u,retry:g}=e.retry.failed();this.opts.log(`shared compilation ${e.key.slice(0,8)} failed: ${i} \u2014 compiling again in ${Math.round(u/1e3)} s (retry ${g})`);for(const d of this.membersOf(e))this.tell(d,{type:"failed",message:i});return}const o=e.retry.succeeded();o>0&&this.opts.log(`shared compilation ${e.key.slice(0,8)}: compiled again after ${o} failure${o===1?"":"s"} \u2014 watching again`);const s=r,n=Math.max(0,(s.endTime??0)-(s.startTime??0)),a=(0,shared_compilation_1.attributeCompilation)(s.compilation,e.registry),l=[];for(const[i,u]of a){e.last.get(i)?.attribution.hash!==u.hash&&l.push(i);const g={attribution:u,durationMs:n};e.last.set(i,g);for(const d of e.projects.get(i)??[])this.tellBuilt(e,d,g)}const c=[...a.values()].filter(i=>i.errorCount>0).map(i=>i.project);this.opts.log(`built ${[...a.keys()].sort().join(", ")||"nothing"} in ${n} ms \u2014 ${l.length?`changed: ${l.sort().join(", ")}`:"no bundle changed"}${c.length?`; errors in: ${c.sort().join(", ")}`:""}`)}tellBuilt(e,t,r){const o=r.attribution,s=e.told.get(t)!==o.hash;e.told.set(t,o.hash);const n=shortHash([...o.files].sort().join(`
|
|
4
|
+
`)),a=e.toldFiles.get(t)!==n;e.toldFiles.set(t,n),this.tell(t,{type:"built",ok:o.errorCount===0,changed:s,hash:o.hash,text:(0,shared_compilation_1.describeBuild)(o,{webpackVersion:e.webpackVersion,durationMs:r.durationMs,changed:s}),errors:o.errorCount,warnings:o.warningCount,durationMs:r.durationMs,sourceMaps:e.sourceMaps,...a?{files:o.files}:{}})}closeGroup(e){e.retry.dispose();for(const s of e.pausing.values())clearTimeout(s);e.pausing.clear();const t=e.compiler,r=e.watching;e.watching=void 0;const o=h(()=>{try{t?.close?.(()=>{})}catch{}},"closeCompiler");r?r.close(o):o()}stop(e=5e3){this.stopped=!0;const t=[...this.groups.values()];return this.groups.clear(),this.members.clear(),new Promise(r=>{let o=t.length;if(o===0)return r();const s=setTimeout(r,e);s.unref?.();for(const n of t){n.retry.dispose();for(const i of n.pausing.values())clearTimeout(i);const a=h(()=>{--o===0&&(clearTimeout(s),r())},"done"),l=n.compiler,c=h(()=>{try{l.close(()=>a())}catch{a()}},"closeCompiler");n.watching?n.watching.close(c):c()}})}}exports.BuildHost=BuildHost;
|