@zuzjs/pm 0.0.9 → 0.0.10

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.
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkI6PNOIS2_cjs=require('./chunk-I6PNOIS2.cjs'),v=require('events'),child_process=require('child_process'),y=require('http'),W=require('https'),C=require('net'),M=require('chokidar'),_=require('fs'),k=require('os'),m=require('path'),P=require('ws'),E=require('pidusage');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var v__default=/*#__PURE__*/_interopDefault(v);var y__default=/*#__PURE__*/_interopDefault(y);var W__default=/*#__PURE__*/_interopDefault(W);var C__default=/*#__PURE__*/_interopDefault(C);var M__default=/*#__PURE__*/_interopDefault(M);var ___default=/*#__PURE__*/_interopDefault(_);var k__default=/*#__PURE__*/_interopDefault(k);var m__default=/*#__PURE__*/_interopDefault(m);var P__default=/*#__PURE__*/_interopDefault(P);var E__default=/*#__PURE__*/_interopDefault(E);/* ZuzJS Process Manager */
2
+ var d=class extends v__default.default{map=new Map;set(t,e){this.map.set(t,e),this.emit("change",t,e);}get(t){return this.map.get(t)}has(t){return this.map.has(t)}delete(t){this.map.delete(t),this.emit("delete",t);}all(){return new Map(this.map)}onchange(t){return this.on("change",t)}offchange(t){return this.off("change",t)}},c=new d;function $(n,t){return new Promise(e=>{let o=(n.startsWith("https")?W__default.default:y__default.default).get(n,{timeout:t},i=>{e((i.statusCode??500)<500);});o.on("error",()=>e(false)),o.on("timeout",()=>{o.destroy(),e(false);});})}function F(n,t){let[e,r]=n.split(":"),o=Number(r);return new Promise(i=>{let a=C__default.default.createConnection({host:e,port:o},()=>{a.destroy(),i(true);});a.setTimeout(t),a.on("timeout",()=>{a.destroy(),i(false);}),a.on("error",()=>i(false));})}function x(n,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);child_process.exec(n,o=>{clearTimeout(r),e(!o);});})}async function b(n){let t=(n.timeoutSeconds??5)*1e3;switch(n.type){case "http":return $(n.target,t);case "tcp":return F(n.target,t);case "exec":return x(n.target,t);default:return false}}var u=5e3,A=16e3,w=1e3,N=5e3;async function D(n){return new Promise(t=>{C__default.default.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(n);})}async function K(n){if(await D(n))return;let t=k__default.default.platform()==="darwin"?`lsof -ti :${n} | xargs kill -9 2>/dev/null || true`:`fuser -k -9 ${n}/tcp 2>/dev/null; true`;await new Promise(e=>child_process.exec(t,()=>e())),await new Promise(e=>setTimeout(e,800));}async function p(n,t){let e=n.process?.pid??n.pid;if(e)return new Promise(r=>{let o=false,i=()=>{o||(o=true,clearTimeout(a),r());};n.once?.("exit",i),n.once?.("exit",i);try{process.kill(e,"SIGTERM");}catch{return i()}let a=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(i,100);}catch{i();}},t),l=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(l),i();}},500);})}var f=class{cfg;name;watcher=null;constructor(t){this.cfg={mode:"fork",instances:1,...t},this.name=t.name,this.initStore();}async start(){let t=this.mp();if(t.status==="running"||t.status==="starting"){chunkI6PNOIS2_cjs.d.warn(this.name,"Already running \u2013 ignoring start()");return}this.patch({status:"starting",isRestarting:false,children:[],restartCount:0,backoffTime:w,probeFailures:0,startTime:null}),this.clearTimers(),this.stopProbe(),chunkI6PNOIS2_cjs.d.info(this.name,"Initializing fresh start...");try{await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}catch(e){this.patch({status:"errored"}),chunkI6PNOIS2_cjs.d.error(this.name,`Start failed: ${e.message}`);}}async stop(){let t=this.mp();if(t.status!=="stopping"){this.patch({status:"stopping",isRestarting:false}),chunkI6PNOIS2_cjs.d.info(this.name,`Stopping ${t.children.length} instances...`),this.clearTimers(),this.stopProbe(),this.stopWatcher();try{await Promise.race([Promise.all(t.children.map(e=>p(e,this.cfg.killTimeout??u))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){chunkI6PNOIS2_cjs.d.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),chunkI6PNOIS2_cjs.d.success(this.name,"Stopped.");}}async _stop(){let t=this.mp();this.patch({status:"stopping",isRestarting:false}),this.clearTimers(),this.stopProbe();for(let e of t.children)p(e,this.cfg.killTimeout??u);this.stopWatcher(),this.patch({children:[],status:"stopped",startTime:null}),chunkI6PNOIS2_cjs.d.info(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(chunkI6PNOIS2_cjs.d.info(this.name,"Restarting..."),this.patch({isRestarting:true,status:"stopping"}),this.clearTimers(),this.stopProbe(),await Promise.all(t.children.map(e=>p(e,this.cfg.killTimeout??u))),this.patch({isRestarting:false,children:[]}));}async _restart(){chunkI6PNOIS2_cjs.d.info(this.name,"Restarting...");let t=this.mp();this.patch({isRestarting:true}),this.clearTimers(),this.stopProbe();for(let e of t.children)p(e,this.cfg.killTimeout??u);}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,o=null,i=null;if(e&&t.status==="running")try{let a=await E__default.default(e);r=a.cpu,o=a.memory;}catch{}return {name:this.name,status:t.status,pid:e,uptime:t.startTime?Date.now()-t.startTime:null,restartCount:t.restartCount,cpu:r,memoryRss:o,memoryHeap:i,mode:this.cfg.mode??"fork",instances:t.children.length}}async spawnAll(){if(!___default.default.existsSync(this.cfg.scriptPath)){chunkI6PNOIS2_cjs.d.error(this.name,`Script not found: ${this.cfg.scriptPath}. Waiting for build...`),this.patch({status:"errored"});return}this.cfg.port&&await K(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??k__default.default.cpus().length:1,r=[];for(let i=0;i<e;i++){let a=this.forkChild();a&&r.push(a);}if(r.length===0){chunkI6PNOIS2_cjs.d.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),chunkI6PNOIS2_cjs.d.success(this.name,`Started ${r.length} instance(s) [${t}]`);let o=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:w,restartCount:0}),chunkI6PNOIS2_cjs.d.success(this.name,"Process is stable."));},N);this.patch({stabilityTimer:o}),this.cfg.probe&&this.startProbe();}forkChild(){try{let t=this.cfg.scriptPath.endsWith(".js")?"node":this.cfg.scriptPath,e=this.cfg.scriptPath.endsWith(".js")?[this.cfg.scriptPath,...this.cfg.args??[]]:[...this.cfg.args??[]],r=child_process.spawn(t,e,{cwd:m__default.default.dirname(m__default.default.resolve(this.cfg.scriptPath,"..")),stdio:["ignore","pipe","pipe"],env:{...process.env,...this.cfg.env??{},NODE_ENV:this.cfg.devMode?"development":"production"},detached:!1,shell:!1});this.setupLogging(r);let o=Date.now();return r.on("error",i=>{chunkI6PNOIS2_cjs.d.error(this.name,"Spawn error:",i);}),r.on("exit",(i,a)=>{let l=Date.now()-o;this.onChildExit(r,i,a,l);}),r}catch(t){return chunkI6PNOIS2_cjs.d.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,o){let i=this.mp(),a=i.children.filter(l=>l!==t);if(this.patch({children:a}),i.status!=="stopping"){if(chunkI6PNOIS2_cjs.d.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${o}ms)`),i.isRestarting){a.length===0&&(this.patch({isRestarting:false}),this.spawnAll());return}if(e!==0&&e!==null){if(this.patch({status:"crashed"}),o<1500){chunkI6PNOIS2_cjs.d.error(this.name,`Immediate crash (${o}ms) \u2013 likely a syntax/build error. Waiting for next file change.`);return}this.scheduleRestart();}}}scheduleRestart(){let t=this.mp(),e=t.backoffTime,r=this.cfg.maxBackoff??A;chunkI6PNOIS2_cjs.d.warn(this.name,`Scheduling restart in ${e}ms (attempt #${t.restartCount+1})`);let o=setTimeout(async()=>{this.patch({restartCount:t.restartCount+1,backoffTime:Math.min(e*2,r)}),await this.spawnAll();},e);this.patch({restartTimer:o});}startProbe(){let t=this.cfg.probe,e=(t.intervalSeconds??10)*1e3,r=t.failureThreshold??3,i=setInterval(async()=>{let a=this.mp();if(a.status!=="running")return;if(await b(t)){a.probeFailures>0&&this.patch({probeFailures:0});return}let h=a.probeFailures+1;this.patch({probeFailures:h}),chunkI6PNOIS2_cjs.d.warn(this.name,`Liveness probe failed (${h}/${r})`),h>=r&&(chunkI6PNOIS2_cjs.d.error(this.name,"Liveness probe threshold exceeded \u2013 restarting."),this.patch({probeFailures:0}),await this.restart());},e);this.patch({probeTimer:i});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}watchFiles(){this.stopWatcher();let t=m__default.default.dirname(this.cfg.scriptPath);this.watcher=M__default.default.watch(t,{ignored:[/node_modules/,/\.pid$/],persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:1500,pollInterval:500}}),this.watcher.on("all",(e,r)=>{(e==="change"||e==="add")&&(chunkI6PNOIS2_cjs.d.info(this.name,`File ${e}: ${m__default.default.basename(r)} \u2013 restarting`),this.restart());}),this.watcher.on("error",e=>chunkI6PNOIS2_cjs.d.error(this.name,"Watcher error:",e)),this.watcher.on("ready",()=>chunkI6PNOIS2_cjs.d.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){c.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:w,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return c.get(this.name)}_patch(t){c.set(this.name,{...this.mp(),...t});}patch(t){let e=this.mp();t.status&&t.status!==e.status&&chunkI6PNOIS2_cjs.d.info(this.name,`[STATE] ${e.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),c.set(this.name,{...e,...t});}clearTimers(){let{restartTimer:t,stabilityTimer:e}=this.mp();t&&clearTimeout(t),e&&clearTimeout(e),this.patch({restartTimer:null,stabilityTimer:null});}setupLogging(t){let e=this.cfg.logs?.wsUrl,r=null;e&&(r=new P__default.default(e),r.on("open",()=>chunkI6PNOIS2_cjs.d.debug(this.name,"Connected to log collector")),r.on("error",i=>chunkI6PNOIS2_cjs.d.error(this.name,"Log Collector WS Error",i.message)));let o=i=>{let a=i.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${a}`),r&&r.readyState===P__default.default.OPEN&&r.send(JSON.stringify({app:this.name,timestamp:Date.now(),log:a}));};t.stdout?.on("data",o),t.stderr?.on("data",o);}};var T=class{workers=new Map;async start(t){if(this.workers.has(t.name)){chunkI6PNOIS2_cjs.d.warn("PM",`Worker "${t.name}" already registered \u2013 use restart()`);return}let e=new f(t);this.workers.set(t.name,e),await e.start();}async stop(t){let e=this.require(t);e&&await e.stop();}async restart(t){let e=this.require(t);e&&await e.restart();}async delete(t){let e=this.require(t);e&&(await e.stop(),this.workers.delete(t),c.delete(t),chunkI6PNOIS2_cjs.d.info("PM",`Deleted worker "${t}"`));}async getStats(t){if(t){let r=this.require(t);return r?[await r.getStats()]:[]}return await Promise.all([...this.workers.values()].map(r=>r.getStats()))}list(){return [...this.workers.keys()]}async stopAll(){chunkI6PNOIS2_cjs.d.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),chunkI6PNOIS2_cjs.d.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||(chunkI6PNOIS2_cjs.d.error(t,"Worker Not Found"),null)}require(t){let e=this.workers.get(t);return e||(chunkI6PNOIS2_cjs.d.error(t,"Worker Not Found"),null)}};exports.a=c;exports.b=b;exports.c=f;exports.d=T;
@@ -0,0 +1 @@
1
+ import {d as d$1}from'./chunk-2PXF47OQ.js';import S from'events';import {spawn,exec}from'child_process';import W from'http';import C from'https';import $ from'net';import R from'chokidar';import L from'fs';import T from'os';import m from'path';import k from'ws';import A from'pidusage';var d=class extends S{map=new Map;set(t,e){this.map.set(t,e),this.emit("change",t,e);}get(t){return this.map.get(t)}has(t){return this.map.has(t)}delete(t){this.map.delete(t),this.emit("delete",t);}all(){return new Map(this.map)}onchange(t){return this.on("change",t)}offchange(t){return this.off("change",t)}},c=new d;function F(n,t){return new Promise(e=>{let o=(n.startsWith("https")?C:W).get(n,{timeout:t},i=>{e((i.statusCode??500)<500);});o.on("error",()=>e(false)),o.on("timeout",()=>{o.destroy(),e(false);});})}function x(n,t){let[e,r]=n.split(":"),o=Number(r);return new Promise(i=>{let a=$.createConnection({host:e,port:o},()=>{a.destroy(),i(true);});a.setTimeout(t),a.on("timeout",()=>{a.destroy(),i(false);}),a.on("error",()=>i(false));})}function M(n,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);exec(n,o=>{clearTimeout(r),e(!o);});})}async function P(n){let t=(n.timeoutSeconds??5)*1e3;switch(n.type){case "http":return F(n.target,t);case "tcp":return x(n.target,t);case "exec":return M(n.target,t);default:return false}}var u=5e3,N=16e3,b=1e3,D=5e3;async function K(n){return new Promise(t=>{$.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(n);})}async function O(n){if(await K(n))return;let t=T.platform()==="darwin"?`lsof -ti :${n} | xargs kill -9 2>/dev/null || true`:`fuser -k -9 ${n}/tcp 2>/dev/null; true`;await new Promise(e=>exec(t,()=>e())),await new Promise(e=>setTimeout(e,800));}async function p(n,t){let e=n.process?.pid??n.pid;if(e)return new Promise(r=>{let o=false,i=()=>{o||(o=true,clearTimeout(a),r());};n.once?.("exit",i),n.once?.("exit",i);try{process.kill(e,"SIGTERM");}catch{return i()}let a=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(i,100);}catch{i();}},t),l=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(l),i();}},500);})}var f=class{cfg;name;watcher=null;constructor(t){this.cfg={mode:"fork",instances:1,...t},this.name=t.name,this.initStore();}async start(){let t=this.mp();if(t.status==="running"||t.status==="starting"){d$1.warn(this.name,"Already running \u2013 ignoring start()");return}this.patch({status:"starting",isRestarting:false,children:[],restartCount:0,backoffTime:b,probeFailures:0,startTime:null}),this.clearTimers(),this.stopProbe(),d$1.info(this.name,"Initializing fresh start...");try{await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}catch(e){this.patch({status:"errored"}),d$1.error(this.name,`Start failed: ${e.message}`);}}async stop(){let t=this.mp();if(t.status!=="stopping"){this.patch({status:"stopping",isRestarting:false}),d$1.info(this.name,`Stopping ${t.children.length} instances...`),this.clearTimers(),this.stopProbe(),this.stopWatcher();try{await Promise.race([Promise.all(t.children.map(e=>p(e,this.cfg.killTimeout??u))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){d$1.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),d$1.success(this.name,"Stopped.");}}async _stop(){let t=this.mp();this.patch({status:"stopping",isRestarting:false}),this.clearTimers(),this.stopProbe();for(let e of t.children)p(e,this.cfg.killTimeout??u);this.stopWatcher(),this.patch({children:[],status:"stopped",startTime:null}),d$1.info(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(d$1.info(this.name,"Restarting..."),this.patch({isRestarting:true,status:"stopping"}),this.clearTimers(),this.stopProbe(),await Promise.all(t.children.map(e=>p(e,this.cfg.killTimeout??u))),this.patch({isRestarting:false,children:[]}));}async _restart(){d$1.info(this.name,"Restarting...");let t=this.mp();this.patch({isRestarting:true}),this.clearTimers(),this.stopProbe();for(let e of t.children)p(e,this.cfg.killTimeout??u);}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,o=null,i=null;if(e&&t.status==="running")try{let a=await A(e);r=a.cpu,o=a.memory;}catch{}return {name:this.name,status:t.status,pid:e,uptime:t.startTime?Date.now()-t.startTime:null,restartCount:t.restartCount,cpu:r,memoryRss:o,memoryHeap:i,mode:this.cfg.mode??"fork",instances:t.children.length}}async spawnAll(){if(!L.existsSync(this.cfg.scriptPath)){d$1.error(this.name,`Script not found: ${this.cfg.scriptPath}. Waiting for build...`),this.patch({status:"errored"});return}this.cfg.port&&await O(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??T.cpus().length:1,r=[];for(let i=0;i<e;i++){let a=this.forkChild();a&&r.push(a);}if(r.length===0){d$1.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),d$1.success(this.name,`Started ${r.length} instance(s) [${t}]`);let o=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:b,restartCount:0}),d$1.success(this.name,"Process is stable."));},D);this.patch({stabilityTimer:o}),this.cfg.probe&&this.startProbe();}forkChild(){try{let t=this.cfg.scriptPath.endsWith(".js")?"node":this.cfg.scriptPath,e=this.cfg.scriptPath.endsWith(".js")?[this.cfg.scriptPath,...this.cfg.args??[]]:[...this.cfg.args??[]],r=spawn(t,e,{cwd:m.dirname(m.resolve(this.cfg.scriptPath,"..")),stdio:["ignore","pipe","pipe"],env:{...process.env,...this.cfg.env??{},NODE_ENV:this.cfg.devMode?"development":"production"},detached:!1,shell:!1});this.setupLogging(r);let o=Date.now();return r.on("error",i=>{d$1.error(this.name,"Spawn error:",i);}),r.on("exit",(i,a)=>{let l=Date.now()-o;this.onChildExit(r,i,a,l);}),r}catch(t){return d$1.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,o){let i=this.mp(),a=i.children.filter(l=>l!==t);if(this.patch({children:a}),i.status!=="stopping"){if(d$1.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${o}ms)`),i.isRestarting){a.length===0&&(this.patch({isRestarting:false}),this.spawnAll());return}if(e!==0&&e!==null){if(this.patch({status:"crashed"}),o<1500){d$1.error(this.name,`Immediate crash (${o}ms) \u2013 likely a syntax/build error. Waiting for next file change.`);return}this.scheduleRestart();}}}scheduleRestart(){let t=this.mp(),e=t.backoffTime,r=this.cfg.maxBackoff??N;d$1.warn(this.name,`Scheduling restart in ${e}ms (attempt #${t.restartCount+1})`);let o=setTimeout(async()=>{this.patch({restartCount:t.restartCount+1,backoffTime:Math.min(e*2,r)}),await this.spawnAll();},e);this.patch({restartTimer:o});}startProbe(){let t=this.cfg.probe,e=(t.intervalSeconds??10)*1e3,r=t.failureThreshold??3,i=setInterval(async()=>{let a=this.mp();if(a.status!=="running")return;if(await P(t)){a.probeFailures>0&&this.patch({probeFailures:0});return}let h=a.probeFailures+1;this.patch({probeFailures:h}),d$1.warn(this.name,`Liveness probe failed (${h}/${r})`),h>=r&&(d$1.error(this.name,"Liveness probe threshold exceeded \u2013 restarting."),this.patch({probeFailures:0}),await this.restart());},e);this.patch({probeTimer:i});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}watchFiles(){this.stopWatcher();let t=m.dirname(this.cfg.scriptPath);this.watcher=R.watch(t,{ignored:[/node_modules/,/\.pid$/],persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:1500,pollInterval:500}}),this.watcher.on("all",(e,r)=>{(e==="change"||e==="add")&&(d$1.info(this.name,`File ${e}: ${m.basename(r)} \u2013 restarting`),this.restart());}),this.watcher.on("error",e=>d$1.error(this.name,"Watcher error:",e)),this.watcher.on("ready",()=>d$1.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){c.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:b,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return c.get(this.name)}_patch(t){c.set(this.name,{...this.mp(),...t});}patch(t){let e=this.mp();t.status&&t.status!==e.status&&d$1.info(this.name,`[STATE] ${e.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),c.set(this.name,{...e,...t});}clearTimers(){let{restartTimer:t,stabilityTimer:e}=this.mp();t&&clearTimeout(t),e&&clearTimeout(e),this.patch({restartTimer:null,stabilityTimer:null});}setupLogging(t){let e=this.cfg.logs?.wsUrl,r=null;e&&(r=new k(e),r.on("open",()=>d$1.debug(this.name,"Connected to log collector")),r.on("error",i=>d$1.error(this.name,"Log Collector WS Error",i.message)));let o=i=>{let a=i.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${a}`),r&&r.readyState===k.OPEN&&r.send(JSON.stringify({app:this.name,timestamp:Date.now(),log:a}));};t.stdout?.on("data",o),t.stderr?.on("data",o);}};var v=class{workers=new Map;async start(t){if(this.workers.has(t.name)){d$1.warn("PM",`Worker "${t.name}" already registered \u2013 use restart()`);return}let e=new f(t);this.workers.set(t.name,e),await e.start();}async stop(t){let e=this.require(t);e&&await e.stop();}async restart(t){let e=this.require(t);e&&await e.restart();}async delete(t){let e=this.require(t);e&&(await e.stop(),this.workers.delete(t),c.delete(t),d$1.info("PM",`Deleted worker "${t}"`));}async getStats(t){if(t){let r=this.require(t);return r?[await r.getStats()]:[]}return await Promise.all([...this.workers.values()].map(r=>r.getStats()))}list(){return [...this.workers.keys()]}async stopAll(){d$1.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),d$1.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||(d$1.error(t,"Worker Not Found"),null)}require(t){let e=this.workers.get(t);return e||(d$1.error(t,"Worker Not Found"),null)}};export{c as a,P as b,f as c,v as d};
package/dist/daemon.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkQZATTCNB_cjs=require('./chunk-QZATTCNB.cjs'),chunkI6PNOIS2_cjs=require('./chunk-I6PNOIS2.cjs'),r=require('fs'),m=require('os'),p=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var r__default=/*#__PURE__*/_interopDefault(r);var m__default=/*#__PURE__*/_interopDefault(m);var p__default=/*#__PURE__*/_interopDefault(p);/* ZuzJS Process Manager */
2
- var i=p__default.default.join(m__default.default.tmpdir(),"zuz-pm.pid");function d(){r__default.default.writeFileSync(i,String(process.pid));}function u(){r__default.default.existsSync(i)&&r__default.default.unlinkSync(i);}var f=p__default.default.join(m__default.default.tmpdir(),"zuz-pm.snapshot.json");function l(o){try{let s=o.list();r__default.default.writeFileSync(f,JSON.stringify(s,null,2));}catch{}}async function S(){chunkI6PNOIS2_cjs.d.success("daemon",`Booting ZPM daemon (PID ${process.pid})`),d();let o=new chunkQZATTCNB_cjs.d,s=chunkI6PNOIS2_cjs.f(o);async function t(e){chunkI6PNOIS2_cjs.d.info("daemon",`Received ${e} \u2013 shutting down\u2026`),l(o),s.close(),await o.stopAll(),u(),process.exit(0);}process.on("SIGINT",()=>t("SIGINT")),process.on("SIGTERM",()=>t("SIGTERM")),process.on("uncaughtException",e=>chunkI6PNOIS2_cjs.d.error("daemon","Uncaught exception:",e)),process.on("unhandledRejection",e=>chunkI6PNOIS2_cjs.d.error("daemon","Unhandled rejection:",e)),chunkI6PNOIS2_cjs.d.success("daemon","Ready \u2013 waiting for IPC commands.");}S().catch(o=>{chunkI6PNOIS2_cjs.d.error("daemon","Fatal startup error:",o),process.exit(1);});
1
+ 'use strict';var chunkE7SMWEX5_cjs=require('./chunk-E7SMWEX5.cjs'),chunkI6PNOIS2_cjs=require('./chunk-I6PNOIS2.cjs'),r=require('fs'),m=require('os'),p=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var r__default=/*#__PURE__*/_interopDefault(r);var m__default=/*#__PURE__*/_interopDefault(m);var p__default=/*#__PURE__*/_interopDefault(p);/* ZuzJS Process Manager */
2
+ var i=p__default.default.join(m__default.default.tmpdir(),"zuz-pm.pid");function d(){r__default.default.writeFileSync(i,String(process.pid));}function u(){r__default.default.existsSync(i)&&r__default.default.unlinkSync(i);}var f=p__default.default.join(m__default.default.tmpdir(),"zuz-pm.snapshot.json");function l(o){try{let s=o.list();r__default.default.writeFileSync(f,JSON.stringify(s,null,2));}catch{}}async function S(){chunkI6PNOIS2_cjs.d.success("daemon",`Booting ZPM daemon (PID ${process.pid})`),d();let o=new chunkE7SMWEX5_cjs.d,s=chunkI6PNOIS2_cjs.f(o);async function t(e){chunkI6PNOIS2_cjs.d.info("daemon",`Received ${e} \u2013 shutting down\u2026`),l(o),s.close(),await o.stopAll(),u(),process.exit(0);}process.on("SIGINT",()=>t("SIGINT")),process.on("SIGTERM",()=>t("SIGTERM")),process.on("uncaughtException",e=>chunkI6PNOIS2_cjs.d.error("daemon","Uncaught exception:",e)),process.on("unhandledRejection",e=>chunkI6PNOIS2_cjs.d.error("daemon","Unhandled rejection:",e)),chunkI6PNOIS2_cjs.d.success("daemon","Ready \u2013 waiting for IPC commands.");}S().catch(o=>{chunkI6PNOIS2_cjs.d.error("daemon","Fatal startup error:",o),process.exit(1);});
package/dist/daemon.js CHANGED
@@ -1 +1 @@
1
- import {d as d$2}from'./chunk-DMPZOTJB.js';import {d as d$1,f as f$1}from'./chunk-2PXF47OQ.js';import r from'fs';import m from'os';import p from'path';var i=p.join(m.tmpdir(),"zuz-pm.pid");function d(){r.writeFileSync(i,String(process.pid));}function u(){r.existsSync(i)&&r.unlinkSync(i);}var f=p.join(m.tmpdir(),"zuz-pm.snapshot.json");function l(o){try{let s=o.list();r.writeFileSync(f,JSON.stringify(s,null,2));}catch{}}async function S(){d$1.success("daemon",`Booting ZPM daemon (PID ${process.pid})`),d();let o=new d$2,s=f$1(o);async function t(e){d$1.info("daemon",`Received ${e} \u2013 shutting down\u2026`),l(o),s.close(),await o.stopAll(),u(),process.exit(0);}process.on("SIGINT",()=>t("SIGINT")),process.on("SIGTERM",()=>t("SIGTERM")),process.on("uncaughtException",e=>d$1.error("daemon","Uncaught exception:",e)),process.on("unhandledRejection",e=>d$1.error("daemon","Unhandled rejection:",e)),d$1.success("daemon","Ready \u2013 waiting for IPC commands.");}S().catch(o=>{d$1.error("daemon","Fatal startup error:",o),process.exit(1);});
1
+ import {d as d$2}from'./chunk-TWBMLO4J.js';import {d as d$1,f as f$1}from'./chunk-2PXF47OQ.js';import r from'fs';import m from'os';import p from'path';var i=p.join(m.tmpdir(),"zuz-pm.pid");function d(){r.writeFileSync(i,String(process.pid));}function u(){r.existsSync(i)&&r.unlinkSync(i);}var f=p.join(m.tmpdir(),"zuz-pm.snapshot.json");function l(o){try{let s=o.list();r.writeFileSync(f,JSON.stringify(s,null,2));}catch{}}async function S(){d$1.success("daemon",`Booting ZPM daemon (PID ${process.pid})`),d();let o=new d$2,s=f$1(o);async function t(e){d$1.info("daemon",`Received ${e} \u2013 shutting down\u2026`),l(o),s.close(),await o.stopAll(),u(),process.exit(0);}process.on("SIGINT",()=>t("SIGINT")),process.on("SIGTERM",()=>t("SIGTERM")),process.on("uncaughtException",e=>d$1.error("daemon","Uncaught exception:",e)),process.on("unhandledRejection",e=>d$1.error("daemon","Unhandled rejection:",e)),d$1.success("daemon","Ready \u2013 waiting for IPC commands.");}S().catch(o=>{d$1.error("daemon","Fatal startup error:",o),process.exit(1);});
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunkUVQRIGIE_cjs=require('./chunk-UVQRIGIE.cjs'),chunkQZATTCNB_cjs=require('./chunk-QZATTCNB.cjs'),chunkI6PNOIS2_cjs=require('./chunk-I6PNOIS2.cjs');Object.defineProperty(exports,"ZPMClient",{enumerable:true,get:function(){return chunkUVQRIGIE_cjs.a}});Object.defineProperty(exports,"zpm",{enumerable:true,get:function(){return chunkUVQRIGIE_cjs.b}});Object.defineProperty(exports,"ProcessManager",{enumerable:true,get:function(){return chunkQZATTCNB_cjs.d}});Object.defineProperty(exports,"Worker",{enumerable:true,get:function(){return chunkQZATTCNB_cjs.c}});Object.defineProperty(exports,"processStore",{enumerable:true,get:function(){return chunkQZATTCNB_cjs.a}});Object.defineProperty(exports,"runProbe",{enumerable:true,get:function(){return chunkQZATTCNB_cjs.b}});Object.defineProperty(exports,"WorkerMode",{enumerable:true,get:function(){return chunkI6PNOIS2_cjs.b}});Object.defineProperty(exports,"WorkerStatus",{enumerable:true,get:function(){return chunkI6PNOIS2_cjs.c}});Object.defineProperty(exports,"getSocketPath",{enumerable:true,get:function(){return chunkI6PNOIS2_cjs.e}});Object.defineProperty(exports,"logger",{enumerable:true,get:function(){return chunkI6PNOIS2_cjs.d}});
1
+ 'use strict';var chunkUVQRIGIE_cjs=require('./chunk-UVQRIGIE.cjs'),chunkE7SMWEX5_cjs=require('./chunk-E7SMWEX5.cjs'),chunkI6PNOIS2_cjs=require('./chunk-I6PNOIS2.cjs');Object.defineProperty(exports,"ZPMClient",{enumerable:true,get:function(){return chunkUVQRIGIE_cjs.a}});Object.defineProperty(exports,"zpm",{enumerable:true,get:function(){return chunkUVQRIGIE_cjs.b}});Object.defineProperty(exports,"ProcessManager",{enumerable:true,get:function(){return chunkE7SMWEX5_cjs.d}});Object.defineProperty(exports,"Worker",{enumerable:true,get:function(){return chunkE7SMWEX5_cjs.c}});Object.defineProperty(exports,"processStore",{enumerable:true,get:function(){return chunkE7SMWEX5_cjs.a}});Object.defineProperty(exports,"runProbe",{enumerable:true,get:function(){return chunkE7SMWEX5_cjs.b}});Object.defineProperty(exports,"WorkerMode",{enumerable:true,get:function(){return chunkI6PNOIS2_cjs.b}});Object.defineProperty(exports,"WorkerStatus",{enumerable:true,get:function(){return chunkI6PNOIS2_cjs.c}});Object.defineProperty(exports,"getSocketPath",{enumerable:true,get:function(){return chunkI6PNOIS2_cjs.e}});Object.defineProperty(exports,"logger",{enumerable:true,get:function(){return chunkI6PNOIS2_cjs.d}});
package/dist/index.d.cts CHANGED
@@ -142,6 +142,7 @@ declare class Worker {
142
142
  private stopWatcher;
143
143
  private initStore;
144
144
  mp(): ManagedProcess;
145
+ private _patch;
145
146
  private patch;
146
147
  private clearTimers;
147
148
  private setupLogging;
package/dist/index.d.ts CHANGED
@@ -142,6 +142,7 @@ declare class Worker {
142
142
  private stopWatcher;
143
143
  private initStore;
144
144
  mp(): ManagedProcess;
145
+ private _patch;
145
146
  private patch;
146
147
  private clearTimers;
147
148
  private setupLogging;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export{a as ZPMClient,b as zpm}from'./chunk-3VIK6Q3M.js';export{d as ProcessManager,c as Worker,a as processStore,b as runProbe}from'./chunk-DMPZOTJB.js';export{b as WorkerMode,c as WorkerStatus,e as getSocketPath,d as logger}from'./chunk-2PXF47OQ.js';
1
+ export{a as ZPMClient,b as zpm}from'./chunk-3VIK6Q3M.js';export{d as ProcessManager,c as Worker,a as processStore,b as runProbe}from'./chunk-TWBMLO4J.js';export{b as WorkerMode,c as WorkerStatus,e as getSocketPath,d as logger}from'./chunk-2PXF47OQ.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuzjs/pm",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
4
4
  "keywords": [
5
5
  "core",
6
6
  "zuz",
@@ -1 +0,0 @@
1
- import {d as d$1}from'./chunk-2PXF47OQ.js';import S from'events';import {spawn,exec}from'child_process';import C from'http';import W from'https';import F from'net';import I from'chokidar';import _ from'fs';import T from'os';import m from'path';import P from'ws';import A from'pidusage';var d=class extends S{map=new Map;set(t,e){this.map.set(t,e),this.emit("change",t,e);}get(t){return this.map.get(t)}has(t){return this.map.has(t)}delete(t){this.map.delete(t),this.emit("delete",t);}all(){return new Map(this.map)}onchange(t){return this.on("change",t)}offchange(t){return this.off("change",t)}},h=new d;function $(n,t){return new Promise(e=>{let o=(n.startsWith("https")?W:C).get(n,{timeout:t},s=>{e((s.statusCode??500)<500);});o.on("error",()=>e(false)),o.on("timeout",()=>{o.destroy(),e(false);});})}function x(n,t){let[e,r]=n.split(":"),o=Number(r);return new Promise(s=>{let a=F.createConnection({host:e,port:o},()=>{a.destroy(),s(true);});a.setTimeout(t),a.on("timeout",()=>{a.destroy(),s(false);}),a.on("error",()=>s(false));})}function M(n,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);exec(n,o=>{clearTimeout(r),e(!o);});})}async function k(n){let t=(n.timeoutSeconds??5)*1e3;switch(n.type){case "http":return $(n.target,t);case "tcp":return x(n.target,t);case "exec":return M(n.target,t);default:return false}}var p=5e3,D=16e3,b=1e3,N=5e3;async function K(n){return new Promise(t=>{F.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(n);})}async function O(n){if(await K(n))return;let t=T.platform()==="darwin"?`lsof -ti :${n} | xargs kill -9 2>/dev/null || true`:`fuser -k -9 ${n}/tcp 2>/dev/null; true`;await new Promise(e=>exec(t,()=>e())),await new Promise(e=>setTimeout(e,800));}async function u(n,t){let e=n.process?.pid??n.pid;if(e)return new Promise(r=>{let o=false,s=()=>{o||(o=true,clearTimeout(a),r());};n.once?.("exit",s),n.once?.("exit",s);try{process.kill(e,"SIGTERM");}catch{return s()}let a=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(s,100);}catch{s();}},t),c=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(c),s();}},500);})}var f=class{cfg;name;watcher=null;constructor(t){this.cfg={mode:"fork",instances:1,...t},this.name=t.name,this.initStore();}async start(){let t=this.mp();if(t.status==="running"||t.status==="starting"){d$1.warn(this.name,"Already running \u2013 ignoring start()");return}this.patch({status:"starting",backoffTime:b,restartCount:0,probeFailures:0}),this.clearTimers(),await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}async stop(){let t=this.mp();if(t.status!=="stopping"){this.patch({status:"stopping",isRestarting:false}),d$1.info(this.name,`Stopping ${t.children.length} instances...`),this.clearTimers(),this.stopProbe(),this.stopWatcher();try{await Promise.race([Promise.all(t.children.map(e=>u(e,this.cfg.killTimeout??p))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){d$1.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),d$1.success(this.name,"Stopped.");}}async _stop(){let t=this.mp();this.patch({status:"stopping",isRestarting:false}),this.clearTimers(),this.stopProbe();for(let e of t.children)u(e,this.cfg.killTimeout??p);this.stopWatcher(),this.patch({children:[],status:"stopped",startTime:null}),d$1.info(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(d$1.info(this.name,"Restarting..."),this.patch({isRestarting:true,status:"stopping"}),this.clearTimers(),this.stopProbe(),await Promise.all(t.children.map(e=>u(e,this.cfg.killTimeout??p))),this.patch({isRestarting:false,children:[]}));}async _restart(){d$1.info(this.name,"Restarting...");let t=this.mp();this.patch({isRestarting:true}),this.clearTimers(),this.stopProbe();for(let e of t.children)u(e,this.cfg.killTimeout??p);}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,o=null,s=null;if(e&&t.status==="running")try{let a=await A(e);r=a.cpu,o=a.memory;}catch{}return {name:this.name,status:t.status,pid:e,uptime:t.startTime?Date.now()-t.startTime:null,restartCount:t.restartCount,cpu:r,memoryRss:o,memoryHeap:s,mode:this.cfg.mode??"fork",instances:t.children.length}}async spawnAll(){if(!_.existsSync(this.cfg.scriptPath)){d$1.error(this.name,`Script not found: ${this.cfg.scriptPath}. Waiting for build...`),this.patch({status:"errored"});return}this.cfg.port&&await O(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??T.cpus().length:1,r=[];for(let s=0;s<e;s++){let a=this.forkChild();a&&r.push(a);}if(r.length===0){d$1.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),d$1.success(this.name,`Started ${r.length} instance(s) [${t}]`);let o=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:b,restartCount:0}),d$1.success(this.name,"Process is stable."));},N);this.patch({stabilityTimer:o}),this.cfg.probe&&this.startProbe();}forkChild(){try{let t=this.cfg.scriptPath.endsWith(".js")?"node":this.cfg.scriptPath,e=this.cfg.scriptPath.endsWith(".js")?[this.cfg.scriptPath,...this.cfg.args??[]]:[...this.cfg.args??[]],r=spawn(t,e,{cwd:m.dirname(m.resolve(this.cfg.scriptPath,"..")),stdio:["ignore","pipe","pipe"],env:{...process.env,...this.cfg.env??{},NODE_ENV:this.cfg.devMode?"development":"production"},detached:!1,shell:!1});this.setupLogging(r);let o=Date.now();return r.on("error",s=>{d$1.error(this.name,"Spawn error:",s);}),r.on("exit",(s,a)=>{let c=Date.now()-o;this.onChildExit(r,s,a,c);}),r}catch(t){return d$1.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,o){let s=this.mp(),a=s.children.filter(c=>c!==t);if(this.patch({children:a}),s.status!=="stopping"){if(d$1.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${o}ms)`),s.isRestarting){a.length===0&&(this.patch({isRestarting:false}),this.spawnAll());return}if(e!==0&&e!==null){if(this.patch({status:"crashed"}),o<1500){d$1.error(this.name,`Immediate crash (${o}ms) \u2013 likely a syntax/build error. Waiting for next file change.`);return}this.scheduleRestart();}}}scheduleRestart(){let t=this.mp(),e=t.backoffTime,r=this.cfg.maxBackoff??D;d$1.warn(this.name,`Scheduling restart in ${e}ms (attempt #${t.restartCount+1})`);let o=setTimeout(async()=>{this.patch({restartCount:t.restartCount+1,backoffTime:Math.min(e*2,r)}),await this.spawnAll();},e);this.patch({restartTimer:o});}startProbe(){let t=this.cfg.probe,e=(t.intervalSeconds??10)*1e3,r=t.failureThreshold??3,s=setInterval(async()=>{let a=this.mp();if(a.status!=="running")return;if(await k(t)){a.probeFailures>0&&this.patch({probeFailures:0});return}let l=a.probeFailures+1;this.patch({probeFailures:l}),d$1.warn(this.name,`Liveness probe failed (${l}/${r})`),l>=r&&(d$1.error(this.name,"Liveness probe threshold exceeded \u2013 restarting."),this.patch({probeFailures:0}),await this.restart());},e);this.patch({probeTimer:s});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}watchFiles(){this.stopWatcher();let t=m.dirname(this.cfg.scriptPath);this.watcher=I.watch(t,{ignored:[/node_modules/,/\.pid$/],persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:1500,pollInterval:500}}),this.watcher.on("all",(e,r)=>{(e==="change"||e==="add")&&(d$1.info(this.name,`File ${e}: ${m.basename(r)} \u2013 restarting`),this.restart());}),this.watcher.on("error",e=>d$1.error(this.name,"Watcher error:",e)),this.watcher.on("ready",()=>d$1.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){h.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:b,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return h.get(this.name)}patch(t){h.set(this.name,{...this.mp(),...t});}clearTimers(){let{restartTimer:t,stabilityTimer:e}=this.mp();t&&clearTimeout(t),e&&clearTimeout(e),this.patch({restartTimer:null,stabilityTimer:null});}setupLogging(t){let e=this.cfg.logs?.wsUrl,r=null;e&&(r=new P(e),r.on("open",()=>d$1.debug(this.name,"Connected to log collector")),r.on("error",s=>d$1.error(this.name,"Log Collector WS Error",s.message)));let o=s=>{let a=s.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${a}`),r&&r.readyState===P.OPEN&&r.send(JSON.stringify({app:this.name,timestamp:Date.now(),log:a}));};t.stdout?.on("data",o),t.stderr?.on("data",o);}};var v=class{workers=new Map;async start(t){if(this.workers.has(t.name)){d$1.warn("PM",`Worker "${t.name}" already registered \u2013 use restart()`);return}let e=new f(t);this.workers.set(t.name,e),await e.start();}async stop(t){await this.require(t).stop();}async restart(t){await this.require(t).restart();}async delete(t){await this.require(t).stop(),this.workers.delete(t),h.delete(t),d$1.info("PM",`Deleted worker "${t}"`);}async getStats(t){return t?[await this.require(t).getStats()]:await Promise.all([...this.workers.values()].map(r=>r.getStats()))}list(){return [...this.workers.keys()]}async stopAll(){d$1.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),d$1.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||null}require(t){let e=this.workers.get(t);if(!e)throw new Error(`Worker "${t}" not found`);return e}};export{h as a,k as b,f as c,v as d};
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkI6PNOIS2_cjs=require('./chunk-I6PNOIS2.cjs'),v=require('events'),child_process=require('child_process'),y=require('http'),C=require('https'),W=require('net'),M=require('chokidar'),L=require('fs'),P=require('os'),m=require('path'),k=require('ws'),E=require('pidusage');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var v__default=/*#__PURE__*/_interopDefault(v);var y__default=/*#__PURE__*/_interopDefault(y);var C__default=/*#__PURE__*/_interopDefault(C);var W__default=/*#__PURE__*/_interopDefault(W);var M__default=/*#__PURE__*/_interopDefault(M);var L__default=/*#__PURE__*/_interopDefault(L);var P__default=/*#__PURE__*/_interopDefault(P);var m__default=/*#__PURE__*/_interopDefault(m);var k__default=/*#__PURE__*/_interopDefault(k);var E__default=/*#__PURE__*/_interopDefault(E);/* ZuzJS Process Manager */
2
- var d=class extends v__default.default{map=new Map;set(t,e){this.map.set(t,e),this.emit("change",t,e);}get(t){return this.map.get(t)}has(t){return this.map.has(t)}delete(t){this.map.delete(t),this.emit("delete",t);}all(){return new Map(this.map)}onchange(t){return this.on("change",t)}offchange(t){return this.off("change",t)}},h=new d;function F(n,t){return new Promise(e=>{let o=(n.startsWith("https")?C__default.default:y__default.default).get(n,{timeout:t},s=>{e((s.statusCode??500)<500);});o.on("error",()=>e(false)),o.on("timeout",()=>{o.destroy(),e(false);});})}function $(n,t){let[e,r]=n.split(":"),o=Number(r);return new Promise(s=>{let a=W__default.default.createConnection({host:e,port:o},()=>{a.destroy(),s(true);});a.setTimeout(t),a.on("timeout",()=>{a.destroy(),s(false);}),a.on("error",()=>s(false));})}function x(n,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);child_process.exec(n,o=>{clearTimeout(r),e(!o);});})}async function b(n){let t=(n.timeoutSeconds??5)*1e3;switch(n.type){case "http":return F(n.target,t);case "tcp":return $(n.target,t);case "exec":return x(n.target,t);default:return false}}var p=5e3,A=16e3,w=1e3,D=5e3;async function N(n){return new Promise(t=>{W__default.default.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(n);})}async function K(n){if(await N(n))return;let t=P__default.default.platform()==="darwin"?`lsof -ti :${n} | xargs kill -9 2>/dev/null || true`:`fuser -k -9 ${n}/tcp 2>/dev/null; true`;await new Promise(e=>child_process.exec(t,()=>e())),await new Promise(e=>setTimeout(e,800));}async function u(n,t){let e=n.process?.pid??n.pid;if(e)return new Promise(r=>{let o=false,s=()=>{o||(o=true,clearTimeout(a),r());};n.once?.("exit",s),n.once?.("exit",s);try{process.kill(e,"SIGTERM");}catch{return s()}let a=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(s,100);}catch{s();}},t),c=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(c),s();}},500);})}var f=class{cfg;name;watcher=null;constructor(t){this.cfg={mode:"fork",instances:1,...t},this.name=t.name,this.initStore();}async start(){let t=this.mp();if(t.status==="running"||t.status==="starting"){chunkI6PNOIS2_cjs.d.warn(this.name,"Already running \u2013 ignoring start()");return}this.patch({status:"starting",backoffTime:w,restartCount:0,probeFailures:0}),this.clearTimers(),await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}async stop(){let t=this.mp();if(t.status!=="stopping"){this.patch({status:"stopping",isRestarting:false}),chunkI6PNOIS2_cjs.d.info(this.name,`Stopping ${t.children.length} instances...`),this.clearTimers(),this.stopProbe(),this.stopWatcher();try{await Promise.race([Promise.all(t.children.map(e=>u(e,this.cfg.killTimeout??p))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){chunkI6PNOIS2_cjs.d.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),chunkI6PNOIS2_cjs.d.success(this.name,"Stopped.");}}async _stop(){let t=this.mp();this.patch({status:"stopping",isRestarting:false}),this.clearTimers(),this.stopProbe();for(let e of t.children)u(e,this.cfg.killTimeout??p);this.stopWatcher(),this.patch({children:[],status:"stopped",startTime:null}),chunkI6PNOIS2_cjs.d.info(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(chunkI6PNOIS2_cjs.d.info(this.name,"Restarting..."),this.patch({isRestarting:true,status:"stopping"}),this.clearTimers(),this.stopProbe(),await Promise.all(t.children.map(e=>u(e,this.cfg.killTimeout??p))),this.patch({isRestarting:false,children:[]}));}async _restart(){chunkI6PNOIS2_cjs.d.info(this.name,"Restarting...");let t=this.mp();this.patch({isRestarting:true}),this.clearTimers(),this.stopProbe();for(let e of t.children)u(e,this.cfg.killTimeout??p);}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,o=null,s=null;if(e&&t.status==="running")try{let a=await E__default.default(e);r=a.cpu,o=a.memory;}catch{}return {name:this.name,status:t.status,pid:e,uptime:t.startTime?Date.now()-t.startTime:null,restartCount:t.restartCount,cpu:r,memoryRss:o,memoryHeap:s,mode:this.cfg.mode??"fork",instances:t.children.length}}async spawnAll(){if(!L__default.default.existsSync(this.cfg.scriptPath)){chunkI6PNOIS2_cjs.d.error(this.name,`Script not found: ${this.cfg.scriptPath}. Waiting for build...`),this.patch({status:"errored"});return}this.cfg.port&&await K(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??P__default.default.cpus().length:1,r=[];for(let s=0;s<e;s++){let a=this.forkChild();a&&r.push(a);}if(r.length===0){chunkI6PNOIS2_cjs.d.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),chunkI6PNOIS2_cjs.d.success(this.name,`Started ${r.length} instance(s) [${t}]`);let o=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:w,restartCount:0}),chunkI6PNOIS2_cjs.d.success(this.name,"Process is stable."));},D);this.patch({stabilityTimer:o}),this.cfg.probe&&this.startProbe();}forkChild(){try{let t=this.cfg.scriptPath.endsWith(".js")?"node":this.cfg.scriptPath,e=this.cfg.scriptPath.endsWith(".js")?[this.cfg.scriptPath,...this.cfg.args??[]]:[...this.cfg.args??[]],r=child_process.spawn(t,e,{cwd:m__default.default.dirname(m__default.default.resolve(this.cfg.scriptPath,"..")),stdio:["ignore","pipe","pipe"],env:{...process.env,...this.cfg.env??{},NODE_ENV:this.cfg.devMode?"development":"production"},detached:!1,shell:!1});this.setupLogging(r);let o=Date.now();return r.on("error",s=>{chunkI6PNOIS2_cjs.d.error(this.name,"Spawn error:",s);}),r.on("exit",(s,a)=>{let c=Date.now()-o;this.onChildExit(r,s,a,c);}),r}catch(t){return chunkI6PNOIS2_cjs.d.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,o){let s=this.mp(),a=s.children.filter(c=>c!==t);if(this.patch({children:a}),s.status!=="stopping"){if(chunkI6PNOIS2_cjs.d.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${o}ms)`),s.isRestarting){a.length===0&&(this.patch({isRestarting:false}),this.spawnAll());return}if(e!==0&&e!==null){if(this.patch({status:"crashed"}),o<1500){chunkI6PNOIS2_cjs.d.error(this.name,`Immediate crash (${o}ms) \u2013 likely a syntax/build error. Waiting for next file change.`);return}this.scheduleRestart();}}}scheduleRestart(){let t=this.mp(),e=t.backoffTime,r=this.cfg.maxBackoff??A;chunkI6PNOIS2_cjs.d.warn(this.name,`Scheduling restart in ${e}ms (attempt #${t.restartCount+1})`);let o=setTimeout(async()=>{this.patch({restartCount:t.restartCount+1,backoffTime:Math.min(e*2,r)}),await this.spawnAll();},e);this.patch({restartTimer:o});}startProbe(){let t=this.cfg.probe,e=(t.intervalSeconds??10)*1e3,r=t.failureThreshold??3,s=setInterval(async()=>{let a=this.mp();if(a.status!=="running")return;if(await b(t)){a.probeFailures>0&&this.patch({probeFailures:0});return}let l=a.probeFailures+1;this.patch({probeFailures:l}),chunkI6PNOIS2_cjs.d.warn(this.name,`Liveness probe failed (${l}/${r})`),l>=r&&(chunkI6PNOIS2_cjs.d.error(this.name,"Liveness probe threshold exceeded \u2013 restarting."),this.patch({probeFailures:0}),await this.restart());},e);this.patch({probeTimer:s});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}watchFiles(){this.stopWatcher();let t=m__default.default.dirname(this.cfg.scriptPath);this.watcher=M__default.default.watch(t,{ignored:[/node_modules/,/\.pid$/],persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:1500,pollInterval:500}}),this.watcher.on("all",(e,r)=>{(e==="change"||e==="add")&&(chunkI6PNOIS2_cjs.d.info(this.name,`File ${e}: ${m__default.default.basename(r)} \u2013 restarting`),this.restart());}),this.watcher.on("error",e=>chunkI6PNOIS2_cjs.d.error(this.name,"Watcher error:",e)),this.watcher.on("ready",()=>chunkI6PNOIS2_cjs.d.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){h.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:w,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return h.get(this.name)}patch(t){h.set(this.name,{...this.mp(),...t});}clearTimers(){let{restartTimer:t,stabilityTimer:e}=this.mp();t&&clearTimeout(t),e&&clearTimeout(e),this.patch({restartTimer:null,stabilityTimer:null});}setupLogging(t){let e=this.cfg.logs?.wsUrl,r=null;e&&(r=new k__default.default(e),r.on("open",()=>chunkI6PNOIS2_cjs.d.debug(this.name,"Connected to log collector")),r.on("error",s=>chunkI6PNOIS2_cjs.d.error(this.name,"Log Collector WS Error",s.message)));let o=s=>{let a=s.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${a}`),r&&r.readyState===k__default.default.OPEN&&r.send(JSON.stringify({app:this.name,timestamp:Date.now(),log:a}));};t.stdout?.on("data",o),t.stderr?.on("data",o);}};var T=class{workers=new Map;async start(t){if(this.workers.has(t.name)){chunkI6PNOIS2_cjs.d.warn("PM",`Worker "${t.name}" already registered \u2013 use restart()`);return}let e=new f(t);this.workers.set(t.name,e),await e.start();}async stop(t){await this.require(t).stop();}async restart(t){await this.require(t).restart();}async delete(t){await this.require(t).stop(),this.workers.delete(t),h.delete(t),chunkI6PNOIS2_cjs.d.info("PM",`Deleted worker "${t}"`);}async getStats(t){return t?[await this.require(t).getStats()]:await Promise.all([...this.workers.values()].map(r=>r.getStats()))}list(){return [...this.workers.keys()]}async stopAll(){chunkI6PNOIS2_cjs.d.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),chunkI6PNOIS2_cjs.d.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||null}require(t){let e=this.workers.get(t);if(!e)throw new Error(`Worker "${t}" not found`);return e}};exports.a=h;exports.b=b;exports.c=f;exports.d=T;