@zuzjs/pm 0.0.18 → 0.0.19

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.
@@ -1,2 +1,2 @@
1
- import {d as d$1,e}from'./chunk-USJACDTS.js';import {spawn,exec}from'child_process';import F from'http';import x from'https';import E from'net';import M from'chokidar';import D from'fs';import T from'os';import l from'path';import p from'picocolors';import P from'ws';import L from'pidusage';function R(a,t){return new Promise(e=>{let i=(a.startsWith("https")?x:F).get(a,{timeout:t},o=>{e((o.statusCode??500)<500);});i.on("error",()=>e(false)),i.on("timeout",()=>{i.destroy(),e(false);});})}function A(a,t){let[e,r]=a.split(":"),i=Number(r);return new Promise(o=>{let n=E.createConnection({host:e,port:i},()=>{n.destroy(),o(true);});n.setTimeout(t),n.on("timeout",()=>{n.destroy(),o(false);}),n.on("error",()=>o(false));})}function _(a,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);exec(a,i=>{clearTimeout(r),e(!i);});})}async function w(a){let t=(a.timeoutSeconds??5)*1e3;switch(a.type){case "http":return R(a.target,t);case "tcp":return A(a.target,t);case "exec":return _(a.target,t);default:return false}}var k=5e3,B=16e3,d=1e3,O=5e3;async function q(a){return new Promise(t=>{E.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(a);})}async function H(a){if(await q(a))return;let t=T.platform()==="darwin"?`lsof -ti :${a} | xargs kill -9 2>/dev/null || true`:`fuser -k -9 ${a}/tcp 2>/dev/null; true`;await new Promise(e=>exec(t,()=>e())),await new Promise(e=>setTimeout(e,800));}async function v(a,t){let e=a.process?.pid??a.pid;if(e)return new Promise(r=>{let i=false,o=()=>{i||(i=true,clearTimeout(n),r());};a.once?.("exit",o),a.once?.("exit",o);try{process.kill(e,"SIGTERM");}catch{return o()}let n=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(o,100);}catch{o();}},t),h=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(h),o();}},500);})}var m=class{cfg;name;watcher=null;isBuilding=false;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:d,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"){d$1.info(this.name,"Already stopping...");return}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=>v(e,this.cfg.killTimeout??k))),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 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=>v(e,this.cfg.killTimeout??k))),this.patch({isRestarting:false,children:[]}));}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,i=null,o=null;if(e&&t.status==="running")try{let n=await L(e);r=n.cpu,i=n.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:i,memoryHeap:o,mode:this.cfg.mode??"fork",instances:t.children.length}}async spawnAll(){if(!D.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 H(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??T.cpus().length:1,r=[];for(let o=0;o<e;o++){let n=this.forkChild();n&&r.push(n);}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 i=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:d,restartCount:0}),d$1.success(this.name,"Process is stable."));},O);this.patch({stabilityTimer:i}),this.cfg.probe&&this.startProbe();}forkChild(){try{let t=this.cfg.scriptPath.endsWith(".js"),e=l.isAbsolute(this.cfg.scriptPath),r,i,o;t?(r=process.execPath,i=[this.cfg.scriptPath,...this.cfg.args??[]],o=l.dirname(l.resolve(this.cfg.scriptPath,".."))):(r=this.cfg.scriptPath,i=[...this.cfg.args??[]],o=e?l.dirname(this.cfg.scriptPath):process.cwd());let n=spawn(r,i,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,...this.cfg.env??{},NODE_ENV:this.cfg.devMode?"development":"production",PATH:`${l.resolve(process.cwd(),"node_modules/.bin")}${l.delimiter}${process.env.PATH}`},detached:!1,shell:!t});this.setupLogging(n);let h=Date.now();return n.on("error",c=>{d$1.error(this.name,`Spawn error (${r}):`,c.message);}),n.on("exit",(c,C)=>{let W=Date.now()-h;this.onChildExit(n,c,C,W);}),n}catch(t){return d$1.error(this.name,"Failed to fork child:",t.message),null}}_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:l.dirname(l.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 i=Date.now();return r.on("error",o=>{d$1.error(this.name,"Spawn error:",o);}),r.on("exit",(o,n)=>{let h=Date.now()-i;this.onChildExit(r,o,n,h);}),r}catch(t){return d$1.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,i){let o=this.mp(),n=o.children.filter(h=>h!==t);if(this.patch({children:n}),o.status!=="stopping"){if(d$1.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${i}ms)`),o.isRestarting){n.length===0&&(this.patch({isRestarting:false}),this.spawnAll());return}e!==0&&e!==null&&(this.patch({status:"crashed"}),i<1500&&d$1.error(this.name,`Immediate crash (${i}ms) \u2013 likely a syntax/build error. Waiting for next file change.`),this.scheduleRestart());}}scheduleRestart(){let t=this.mp(),e=t.backoffTime,r=this.cfg.maxBackoff??B;d$1.warn(this.name,`Scheduling restart in ${e}ms (attempt #${t.restartCount+1})`);let i=setTimeout(async()=>{this.patch({restartCount:t.restartCount+1,backoffTime:Math.min(e*2,r)}),await this.spawnAll();},e);this.patch({restartTimer:i});}startProbe(){let t=this.cfg.probe,e=(t.intervalSeconds??10)*1e3,r=t.failureThreshold??3,o=setInterval(async()=>{let n=this.mp();if(n.status!=="running")return;if(await w(t)){n.probeFailures>0&&this.patch({probeFailures:0});return}let c=n.probeFailures+1;this.patch({probeFailures:c}),d$1.warn(this.name,`Liveness probe failed (${c}/${r})`),c>=r&&(d$1.error(this.name,"Liveness probe threshold exceeded \u2013 restarting."),this.patch({probeFailures:0}),await this.restart());},e);this.patch({probeTimer:o});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}watchFiles(){this.stopWatcher();let t=process.cwd(),e=l.resolve(t,"src");d$1.info(this.name,p.gray(`Watcher active on: ${e}`)),this.watcher=M.watch(e,{ignored:[/node_modules/,/\.pid$/],persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:1500,pollInterval:500}}),this.watcher.on("all",async(r,i)=>{if(!this.isBuilding&&(r==="change"||r==="add"))if(d$1.info(this.name,p.yellow(`File ${r}: ${l.basename(i)} \u2013 restarting`)),this.cfg.reloadCommand){this.isBuilding=true,d$1.info(this.name,p.blue(`Executing: ${this.cfg.reloadCommand}`));let{exec:o}=await import('child_process');o(this.cfg.reloadCommand,{cwd:t,env:{...process.env,PATH:`${l.resolve(t,"node_modules/.bin")}${l.delimiter}${process.env.PATH}`}},(n,h,c)=>{if(this.isBuilding=false,n){d$1.error(this.name,`Build Failed:
2
- ${c||h||n.message}`);return}d$1.success(this.name,"Build successful. Triggering restart..."),this.restart();});}else this.restart();}),this.watcher.on("error",r=>d$1.error(this.name,"Watcher error:",r)),this.watcher.on("ready",()=>d$1.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){e.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:d,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return e.get(this.name)}_patch(t){e.set(this.name,{...this.mp(),...t});}patch(t){let e$1=this.mp();t.status&&t.status!==e$1.status&&d$1.info(this.name,`[STATE] ${e$1.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),t.lastError&&d$1.error(this.name,`[REASON] ${t.lastError}`),e.set(this.name,{...e$1,...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",o=>d$1.error(this.name,"Log Collector WS Error",o.message)));let i=o=>{let n=o.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${n}`),r&&r.readyState===P.OPEN&&r.send(JSON.stringify({app:this.name,timestamp:Date.now(),log:n}));};t.stdout?.on("data",i),t.stderr?.on("data",i);}};var S=class{workers=new Map;async start(t){let e$1=this.workers.get(t.name);if(e$1){let i=e.get(t.name);if(i?.status==="stopped"||i?.status==="crashed"||i?.status==="errored"){d$1.info("ZPM",`Resuming existing worker "${t.name}"`),await e$1.start();return}d$1.warn("ZPM",`Worker "${p.cyan(t.name)}" is ${p.cyan(i?.status)} - use restart()`);return}let r=new m(t);this.workers.set(t.name,r),await r.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$1=this.require(t);e$1&&(await e$1.stop(),this.workers.delete(t),e.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{w as a,m as b,S as c};
1
+ import {d as d$1,e}from'./chunk-USJACDTS.js';import {spawn,exec}from'child_process';import x from'http';import R from'https';import E from'net';import I from'chokidar';import m from'fs';import T from'os';import c from'path';import f from'picocolors';import k from'ws';import L from'pidusage';function A(a,t){return new Promise(e=>{let i=(a.startsWith("https")?R:x).get(a,{timeout:t},o=>{e((o.statusCode??500)<500);});i.on("error",()=>e(false)),i.on("timeout",()=>{i.destroy(),e(false);});})}function _(a,t){let[e,r]=a.split(":"),i=Number(r);return new Promise(o=>{let n=E.createConnection({host:e,port:i},()=>{n.destroy(),o(true);});n.setTimeout(t),n.on("timeout",()=>{n.destroy(),o(false);}),n.on("error",()=>o(false));})}function M(a,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);exec(a,i=>{clearTimeout(r),e(!i);});})}async function P(a){let t=(a.timeoutSeconds??5)*1e3;switch(a.type){case "http":return A(a.target,t);case "tcp":return _(a.target,t);case "exec":return M(a.target,t);default:return false}}var v=5e3,B=16e3,d=1e3,O=5e3;async function j(a){return new Promise(t=>{E.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(a);})}async function q(a){if(await j(a))return;let t=T.platform()==="darwin"?`lsof -ti :${a} | xargs kill -9 2>/dev/null || true`:`fuser -k -9 ${a}/tcp 2>/dev/null; true`;await new Promise(e=>exec(t,()=>e())),await new Promise(e=>setTimeout(e,800));}async function y(a,t){let e=a.process?.pid??a.pid;if(e)return new Promise(r=>{let i=false,o=()=>{i||(i=true,clearTimeout(n),r());};a.once?.("exit",o),a.once?.("exit",o);try{process.kill(e,"SIGTERM");}catch{return o()}let n=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(o,100);}catch{o();}},t),h=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(h),o();}},500);})}var p=class{cfg;name;watcher=null;isBuilding=false;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:d,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"){d$1.info(this.name,"Already stopping...");return}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=>y(e,this.cfg.killTimeout??v))),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 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=>y(e,this.cfg.killTimeout??v))),this.patch({isRestarting:false,children:[]}));}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,i=null,o=null;if(e&&t.status==="running")try{let n=await L(e);r=n.cpu,i=n.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:i,memoryHeap:o,mode:this.cfg.mode??"fork",instances:t.children.length}}async spawnAll(){if(!m.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 q(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??T.cpus().length:1,r=[];for(let o=0;o<e;o++){let n=this.forkChild();n&&r.push(n);}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 i=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:d,restartCount:0}),d$1.success(this.name,"Process is stable."));},O);this.patch({stabilityTimer:i}),this.cfg.probe&&this.startProbe();}forkChild(){try{let t=this.cfg.scriptPath.endsWith(".js"),e=c.isAbsolute(this.cfg.scriptPath),r,i,o;t?(r=process.execPath,i=[this.cfg.scriptPath,...this.cfg.args??[]],o=c.dirname(c.resolve(this.cfg.scriptPath,".."))):(r=this.cfg.scriptPath,i=[...this.cfg.args??[]],o=e?c.dirname(this.cfg.scriptPath):process.cwd());let n=spawn(r,i,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,...this.cfg.env??{},NODE_ENV:this.cfg.devMode?"development":"production",PATH:`${c.resolve(process.cwd(),"node_modules/.bin")}${c.delimiter}${process.env.PATH}`},detached:!1,shell:!t});this.setupLogging(n);let h=Date.now();return n.on("error",l=>{d$1.error(this.name,`Spawn error (${r}):`,l.message);}),n.on("exit",(l,W)=>{let $=Date.now()-h;this.onChildExit(n,l,W,$);}),n}catch(t){return d$1.error(this.name,"Failed to fork child:",t.message),null}}_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:c.dirname(c.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 i=Date.now();return r.on("error",o=>{d$1.error(this.name,"Spawn error:",o);}),r.on("exit",(o,n)=>{let h=Date.now()-i;this.onChildExit(r,o,n,h);}),r}catch(t){return d$1.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,i){let o=this.mp(),n=o.children.filter(h=>h!==t);if(this.patch({children:n}),o.status!=="stopping"){if(d$1.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${i}ms)`),o.isRestarting){n.length===0&&(this.patch({isRestarting:false}),this.spawnAll());return}e!==0&&e!==null&&(this.patch({status:"crashed"}),i<1500&&d$1.error(this.name,`Immediate crash (${i}ms) \u2013 likely a syntax/build error. Waiting for next file change.`),this.scheduleRestart());}}scheduleRestart(){let t=this.mp(),e=t.backoffTime,r=this.cfg.maxBackoff??B;d$1.warn(this.name,`Scheduling restart in ${e}ms (attempt #${t.restartCount+1})`);let i=setTimeout(async()=>{this.patch({restartCount:t.restartCount+1,backoffTime:Math.min(e*2,r)}),await this.spawnAll();},e);this.patch({restartTimer:i});}startProbe(){let t=this.cfg.probe,e=(t.intervalSeconds??10)*1e3,r=t.failureThreshold??3,o=setInterval(async()=>{let n=this.mp();if(n.status!=="running")return;if(await P(t)){n.probeFailures>0&&this.patch({probeFailures:0});return}let l=n.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:o});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}findProjectRoot(t){let e=c.resolve(t);for(m.existsSync(e)&&m.statSync(e).isFile()&&(e=c.dirname(e));e!==c.parse(e).root;){if(m.existsSync(c.join(e,"package.json")))return e;e=c.dirname(e);}return process.cwd()}watchFiles(){this.stopWatcher();let t=this.findProjectRoot(this.cfg.scriptPath),e=c.resolve(t,"src");d$1.info(this.name,f.gray(`Watcher active on: ${e}`)),this.watcher=I.watch(e,{ignored:[/node_modules/,/\.pid$/],persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:1500,pollInterval:500}}),this.watcher.on("all",async(r,i)=>{if(!this.isBuilding&&(r==="change"||r==="add"))if(d$1.info(this.name,f.yellow(`File ${r}: ${c.basename(i)} \u2013 restarting`)),this.cfg.reloadCommand){this.isBuilding=true,d$1.info(this.name,f.blue(`Executing: ${this.cfg.reloadCommand}`));let{exec:o}=await import('child_process');o(this.cfg.reloadCommand,{cwd:t,env:{...process.env,PATH:`${c.resolve(t,"node_modules/.bin")}${c.delimiter}${process.env.PATH}`}},(n,h,l)=>{if(this.isBuilding=false,n){d$1.error(this.name,`Build Failed:
2
+ ${l||h||n.message}`);return}d$1.success(this.name,"Build successful. Triggering restart..."),this.restart();});}else this.restart();}),this.watcher.on("error",r=>d$1.error(this.name,"Watcher error:",r)),this.watcher.on("ready",()=>d$1.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){e.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:d,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return e.get(this.name)}_patch(t){e.set(this.name,{...this.mp(),...t});}patch(t){let e$1=this.mp();t.status&&t.status!==e$1.status&&d$1.info(this.name,`[STATE] ${e$1.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),t.lastError&&d$1.error(this.name,`[REASON] ${t.lastError}`),e.set(this.name,{...e$1,...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",o=>d$1.error(this.name,"Log Collector WS Error",o.message)));let i=o=>{let n=o.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${n}`),r&&r.readyState===k.OPEN&&r.send(JSON.stringify({app:this.name,timestamp:Date.now(),log:n}));};t.stdout?.on("data",i),t.stderr?.on("data",i);}};var C=class{workers=new Map;async start(t){let e$1=this.workers.get(t.name);if(e$1){let i=e.get(t.name);if(i?.status==="stopped"||i?.status==="crashed"||i?.status==="errored"){d$1.info("ZPM",`Resuming existing worker "${t.name}"`),await e$1.start();return}d$1.warn("ZPM",`Worker "${f.cyan(t.name)}" is ${f.cyan(i?.status)} - use restart()`);return}let r=new p(t);this.workers.set(t.name,r),await r.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$1=this.require(t);e$1&&(await e$1.stop(),this.workers.delete(t),e.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{P as a,p as b,C as c};
@@ -1,3 +1,3 @@
1
- 'use strict';var chunkD4SST7VW_cjs=require('./chunk-D4SST7VW.cjs'),child_process=require('child_process'),$=require('http'),F=require('https'),x=require('net'),_=require('chokidar'),I=require('fs'),v=require('os'),l=require('path'),p=require('picocolors'),b=require('ws'),N=require('pidusage');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var $__default=/*#__PURE__*/_interopDefault($);var F__default=/*#__PURE__*/_interopDefault(F);var x__default=/*#__PURE__*/_interopDefault(x);var ___default=/*#__PURE__*/_interopDefault(_);var I__default=/*#__PURE__*/_interopDefault(I);var v__default=/*#__PURE__*/_interopDefault(v);var l__default=/*#__PURE__*/_interopDefault(l);var p__default=/*#__PURE__*/_interopDefault(p);var b__default=/*#__PURE__*/_interopDefault(b);var N__default=/*#__PURE__*/_interopDefault(N);/* ZuzJS Process Manager */
2
- function E(a,t){return new Promise(e=>{let i=(a.startsWith("https")?F__default.default:$__default.default).get(a,{timeout:t},o=>{e((o.statusCode??500)<500);});i.on("error",()=>e(false)),i.on("timeout",()=>{i.destroy(),e(false);});})}function R(a,t){let[e,r]=a.split(":"),i=Number(r);return new Promise(o=>{let n=x__default.default.createConnection({host:e,port:i},()=>{n.destroy(),o(true);});n.setTimeout(t),n.on("timeout",()=>{n.destroy(),o(false);}),n.on("error",()=>o(false));})}function A(a,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);child_process.exec(a,i=>{clearTimeout(r),e(!i);});})}async function g(a){let t=(a.timeoutSeconds??5)*1e3;switch(a.type){case "http":return E(a.target,t);case "tcp":return R(a.target,t);case "exec":return A(a.target,t);default:return false}}var P=5e3,L=16e3,d=1e3,B=5e3;async function O(a){return new Promise(t=>{x__default.default.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(a);})}async function q(a){if(await O(a))return;let t=v__default.default.platform()==="darwin"?`lsof -ti :${a} | xargs kill -9 2>/dev/null || true`:`fuser -k -9 ${a}/tcp 2>/dev/null; true`;await new Promise(e=>child_process.exec(t,()=>e())),await new Promise(e=>setTimeout(e,800));}async function k(a,t){let e=a.process?.pid??a.pid;if(e)return new Promise(r=>{let i=false,o=()=>{i||(i=true,clearTimeout(n),r());};a.once?.("exit",o),a.once?.("exit",o);try{process.kill(e,"SIGTERM");}catch{return o()}let n=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(o,100);}catch{o();}},t),h=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(h),o();}},500);})}var m=class{cfg;name;watcher=null;isBuilding=false;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"){chunkD4SST7VW_cjs.d.warn(this.name,"Already running \u2013 ignoring start()");return}this.patch({status:"starting",isRestarting:false,children:[],restartCount:0,backoffTime:d,probeFailures:0,startTime:null}),this.clearTimers(),this.stopProbe(),chunkD4SST7VW_cjs.d.info(this.name,"Initializing fresh start...");try{await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}catch(e){this.patch({status:"errored"}),chunkD4SST7VW_cjs.d.error(this.name,`Start failed: ${e.message}`);}}async stop(){let t=this.mp();if(t.status==="stopping"){chunkD4SST7VW_cjs.d.info(this.name,"Already stopping...");return}this.patch({status:"stopping",isRestarting:false}),chunkD4SST7VW_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=>k(e,this.cfg.killTimeout??P))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){chunkD4SST7VW_cjs.d.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),chunkD4SST7VW_cjs.d.success(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(chunkD4SST7VW_cjs.d.info(this.name,"Restarting..."),this.patch({isRestarting:true,status:"stopping"}),this.clearTimers(),this.stopProbe(),await Promise.all(t.children.map(e=>k(e,this.cfg.killTimeout??P))),this.patch({isRestarting:false,children:[]}));}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,i=null,o=null;if(e&&t.status==="running")try{let n=await N__default.default(e);r=n.cpu,i=n.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:i,memoryHeap:o,mode:this.cfg.mode??"fork",instances:t.children.length}}async spawnAll(){if(!I__default.default.existsSync(this.cfg.scriptPath)){chunkD4SST7VW_cjs.d.error(this.name,`Script not found: ${this.cfg.scriptPath}. Waiting for build...`),this.patch({status:"errored"});return}this.cfg.port&&await q(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??v__default.default.cpus().length:1,r=[];for(let o=0;o<e;o++){let n=this.forkChild();n&&r.push(n);}if(r.length===0){chunkD4SST7VW_cjs.d.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),chunkD4SST7VW_cjs.d.success(this.name,`Started ${r.length} instance(s) [${t}]`);let i=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:d,restartCount:0}),chunkD4SST7VW_cjs.d.success(this.name,"Process is stable."));},B);this.patch({stabilityTimer:i}),this.cfg.probe&&this.startProbe();}forkChild(){try{let t=this.cfg.scriptPath.endsWith(".js"),e=l__default.default.isAbsolute(this.cfg.scriptPath),r,i,o;t?(r=process.execPath,i=[this.cfg.scriptPath,...this.cfg.args??[]],o=l__default.default.dirname(l__default.default.resolve(this.cfg.scriptPath,".."))):(r=this.cfg.scriptPath,i=[...this.cfg.args??[]],o=e?l__default.default.dirname(this.cfg.scriptPath):process.cwd());let n=child_process.spawn(r,i,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,...this.cfg.env??{},NODE_ENV:this.cfg.devMode?"development":"production",PATH:`${l__default.default.resolve(process.cwd(),"node_modules/.bin")}${l__default.default.delimiter}${process.env.PATH}`},detached:!1,shell:!t});this.setupLogging(n);let h=Date.now();return n.on("error",c=>{chunkD4SST7VW_cjs.d.error(this.name,`Spawn error (${r}):`,c.message);}),n.on("exit",(c,S)=>{let C=Date.now()-h;this.onChildExit(n,c,S,C);}),n}catch(t){return chunkD4SST7VW_cjs.d.error(this.name,"Failed to fork child:",t.message),null}}_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:l__default.default.dirname(l__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 i=Date.now();return r.on("error",o=>{chunkD4SST7VW_cjs.d.error(this.name,"Spawn error:",o);}),r.on("exit",(o,n)=>{let h=Date.now()-i;this.onChildExit(r,o,n,h);}),r}catch(t){return chunkD4SST7VW_cjs.d.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,i){let o=this.mp(),n=o.children.filter(h=>h!==t);if(this.patch({children:n}),o.status!=="stopping"){if(chunkD4SST7VW_cjs.d.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${i}ms)`),o.isRestarting){n.length===0&&(this.patch({isRestarting:false}),this.spawnAll());return}e!==0&&e!==null&&(this.patch({status:"crashed"}),i<1500&&chunkD4SST7VW_cjs.d.error(this.name,`Immediate crash (${i}ms) \u2013 likely a syntax/build error. Waiting for next file change.`),this.scheduleRestart());}}scheduleRestart(){let t=this.mp(),e=t.backoffTime,r=this.cfg.maxBackoff??L;chunkD4SST7VW_cjs.d.warn(this.name,`Scheduling restart in ${e}ms (attempt #${t.restartCount+1})`);let i=setTimeout(async()=>{this.patch({restartCount:t.restartCount+1,backoffTime:Math.min(e*2,r)}),await this.spawnAll();},e);this.patch({restartTimer:i});}startProbe(){let t=this.cfg.probe,e=(t.intervalSeconds??10)*1e3,r=t.failureThreshold??3,o=setInterval(async()=>{let n=this.mp();if(n.status!=="running")return;if(await g(t)){n.probeFailures>0&&this.patch({probeFailures:0});return}let c=n.probeFailures+1;this.patch({probeFailures:c}),chunkD4SST7VW_cjs.d.warn(this.name,`Liveness probe failed (${c}/${r})`),c>=r&&(chunkD4SST7VW_cjs.d.error(this.name,"Liveness probe threshold exceeded \u2013 restarting."),this.patch({probeFailures:0}),await this.restart());},e);this.patch({probeTimer:o});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}watchFiles(){this.stopWatcher();let t=process.cwd(),e=l__default.default.resolve(t,"src");chunkD4SST7VW_cjs.d.info(this.name,p__default.default.gray(`Watcher active on: ${e}`)),this.watcher=___default.default.watch(e,{ignored:[/node_modules/,/\.pid$/],persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:1500,pollInterval:500}}),this.watcher.on("all",async(r,i)=>{if(!this.isBuilding&&(r==="change"||r==="add"))if(chunkD4SST7VW_cjs.d.info(this.name,p__default.default.yellow(`File ${r}: ${l__default.default.basename(i)} \u2013 restarting`)),this.cfg.reloadCommand){this.isBuilding=true,chunkD4SST7VW_cjs.d.info(this.name,p__default.default.blue(`Executing: ${this.cfg.reloadCommand}`));let{exec:o}=await import('child_process');o(this.cfg.reloadCommand,{cwd:t,env:{...process.env,PATH:`${l__default.default.resolve(t,"node_modules/.bin")}${l__default.default.delimiter}${process.env.PATH}`}},(n,h,c)=>{if(this.isBuilding=false,n){chunkD4SST7VW_cjs.d.error(this.name,`Build Failed:
3
- ${c||h||n.message}`);return}chunkD4SST7VW_cjs.d.success(this.name,"Build successful. Triggering restart..."),this.restart();});}else this.restart();}),this.watcher.on("error",r=>chunkD4SST7VW_cjs.d.error(this.name,"Watcher error:",r)),this.watcher.on("ready",()=>chunkD4SST7VW_cjs.d.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){chunkD4SST7VW_cjs.e.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:d,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return chunkD4SST7VW_cjs.e.get(this.name)}_patch(t){chunkD4SST7VW_cjs.e.set(this.name,{...this.mp(),...t});}patch(t){let e=this.mp();t.status&&t.status!==e.status&&chunkD4SST7VW_cjs.d.info(this.name,`[STATE] ${e.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),t.lastError&&chunkD4SST7VW_cjs.d.error(this.name,`[REASON] ${t.lastError}`),chunkD4SST7VW_cjs.e.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 b__default.default(e),r.on("open",()=>chunkD4SST7VW_cjs.d.debug(this.name,"Connected to log collector")),r.on("error",o=>chunkD4SST7VW_cjs.d.error(this.name,"Log Collector WS Error",o.message)));let i=o=>{let n=o.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${n}`),r&&r.readyState===b__default.default.OPEN&&r.send(JSON.stringify({app:this.name,timestamp:Date.now(),log:n}));};t.stdout?.on("data",i),t.stderr?.on("data",i);}};var y=class{workers=new Map;async start(t){let e=this.workers.get(t.name);if(e){let i=chunkD4SST7VW_cjs.e.get(t.name);if(i?.status==="stopped"||i?.status==="crashed"||i?.status==="errored"){chunkD4SST7VW_cjs.d.info("ZPM",`Resuming existing worker "${t.name}"`),await e.start();return}chunkD4SST7VW_cjs.d.warn("ZPM",`Worker "${p__default.default.cyan(t.name)}" is ${p__default.default.cyan(i?.status)} - use restart()`);return}let r=new m(t);this.workers.set(t.name,r),await r.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),chunkD4SST7VW_cjs.e.delete(t),chunkD4SST7VW_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(){chunkD4SST7VW_cjs.d.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),chunkD4SST7VW_cjs.d.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||(chunkD4SST7VW_cjs.d.error(t,"Worker Not Found"),null)}require(t){let e=this.workers.get(t);return e||(chunkD4SST7VW_cjs.d.error(t,"Worker Not Found"),null)}};exports.a=g;exports.b=m;exports.c=y;
1
+ 'use strict';var chunkD4SST7VW_cjs=require('./chunk-D4SST7VW.cjs'),child_process=require('child_process'),F=require('http'),x=require('https'),R=require('net'),M=require('chokidar'),m=require('fs'),y=require('os'),c=require('path'),f=require('picocolors'),b=require('ws'),N=require('pidusage');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var F__default=/*#__PURE__*/_interopDefault(F);var x__default=/*#__PURE__*/_interopDefault(x);var R__default=/*#__PURE__*/_interopDefault(R);var M__default=/*#__PURE__*/_interopDefault(M);var m__default=/*#__PURE__*/_interopDefault(m);var y__default=/*#__PURE__*/_interopDefault(y);var c__default=/*#__PURE__*/_interopDefault(c);var f__default=/*#__PURE__*/_interopDefault(f);var b__default=/*#__PURE__*/_interopDefault(b);var N__default=/*#__PURE__*/_interopDefault(N);/* ZuzJS Process Manager */
2
+ function E(a,t){return new Promise(e=>{let i=(a.startsWith("https")?x__default.default:F__default.default).get(a,{timeout:t},o=>{e((o.statusCode??500)<500);});i.on("error",()=>e(false)),i.on("timeout",()=>{i.destroy(),e(false);});})}function A(a,t){let[e,r]=a.split(":"),i=Number(r);return new Promise(o=>{let n=R__default.default.createConnection({host:e,port:i},()=>{n.destroy(),o(true);});n.setTimeout(t),n.on("timeout",()=>{n.destroy(),o(false);}),n.on("error",()=>o(false));})}function _(a,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);child_process.exec(a,i=>{clearTimeout(r),e(!i);});})}async function w(a){let t=(a.timeoutSeconds??5)*1e3;switch(a.type){case "http":return E(a.target,t);case "tcp":return A(a.target,t);case "exec":return _(a.target,t);default:return false}}var k=5e3,L=16e3,d=1e3,B=5e3;async function O(a){return new Promise(t=>{R__default.default.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(a);})}async function j(a){if(await O(a))return;let t=y__default.default.platform()==="darwin"?`lsof -ti :${a} | xargs kill -9 2>/dev/null || true`:`fuser -k -9 ${a}/tcp 2>/dev/null; true`;await new Promise(e=>child_process.exec(t,()=>e())),await new Promise(e=>setTimeout(e,800));}async function v(a,t){let e=a.process?.pid??a.pid;if(e)return new Promise(r=>{let i=false,o=()=>{i||(i=true,clearTimeout(n),r());};a.once?.("exit",o),a.once?.("exit",o);try{process.kill(e,"SIGTERM");}catch{return o()}let n=setTimeout(()=>{try{process.kill(e,"SIGKILL"),setTimeout(o,100);}catch{o();}},t),h=setInterval(()=>{try{process.kill(e,0);}catch{clearInterval(h),o();}},500);})}var p=class{cfg;name;watcher=null;isBuilding=false;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"){chunkD4SST7VW_cjs.d.warn(this.name,"Already running \u2013 ignoring start()");return}this.patch({status:"starting",isRestarting:false,children:[],restartCount:0,backoffTime:d,probeFailures:0,startTime:null}),this.clearTimers(),this.stopProbe(),chunkD4SST7VW_cjs.d.info(this.name,"Initializing fresh start...");try{await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}catch(e){this.patch({status:"errored"}),chunkD4SST7VW_cjs.d.error(this.name,`Start failed: ${e.message}`);}}async stop(){let t=this.mp();if(t.status==="stopping"){chunkD4SST7VW_cjs.d.info(this.name,"Already stopping...");return}this.patch({status:"stopping",isRestarting:false}),chunkD4SST7VW_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=>v(e,this.cfg.killTimeout??k))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){chunkD4SST7VW_cjs.d.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),chunkD4SST7VW_cjs.d.success(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(chunkD4SST7VW_cjs.d.info(this.name,"Restarting..."),this.patch({isRestarting:true,status:"stopping"}),this.clearTimers(),this.stopProbe(),await Promise.all(t.children.map(e=>v(e,this.cfg.killTimeout??k))),this.patch({isRestarting:false,children:[]}));}async getStats(){let t=this.mp(),e=t.children[0]?.pid??null,r=null,i=null,o=null;if(e&&t.status==="running")try{let n=await N__default.default(e);r=n.cpu,i=n.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:i,memoryHeap:o,mode:this.cfg.mode??"fork",instances:t.children.length}}async spawnAll(){if(!m__default.default.existsSync(this.cfg.scriptPath)){chunkD4SST7VW_cjs.d.error(this.name,`Script not found: ${this.cfg.scriptPath}. Waiting for build...`),this.patch({status:"errored"});return}this.cfg.port&&await j(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??y__default.default.cpus().length:1,r=[];for(let o=0;o<e;o++){let n=this.forkChild();n&&r.push(n);}if(r.length===0){chunkD4SST7VW_cjs.d.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),chunkD4SST7VW_cjs.d.success(this.name,`Started ${r.length} instance(s) [${t}]`);let i=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:d,restartCount:0}),chunkD4SST7VW_cjs.d.success(this.name,"Process is stable."));},B);this.patch({stabilityTimer:i}),this.cfg.probe&&this.startProbe();}forkChild(){try{let t=this.cfg.scriptPath.endsWith(".js"),e=c__default.default.isAbsolute(this.cfg.scriptPath),r,i,o;t?(r=process.execPath,i=[this.cfg.scriptPath,...this.cfg.args??[]],o=c__default.default.dirname(c__default.default.resolve(this.cfg.scriptPath,".."))):(r=this.cfg.scriptPath,i=[...this.cfg.args??[]],o=e?c__default.default.dirname(this.cfg.scriptPath):process.cwd());let n=child_process.spawn(r,i,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,...this.cfg.env??{},NODE_ENV:this.cfg.devMode?"development":"production",PATH:`${c__default.default.resolve(process.cwd(),"node_modules/.bin")}${c__default.default.delimiter}${process.env.PATH}`},detached:!1,shell:!t});this.setupLogging(n);let h=Date.now();return n.on("error",l=>{chunkD4SST7VW_cjs.d.error(this.name,`Spawn error (${r}):`,l.message);}),n.on("exit",(l,C)=>{let W=Date.now()-h;this.onChildExit(n,l,C,W);}),n}catch(t){return chunkD4SST7VW_cjs.d.error(this.name,"Failed to fork child:",t.message),null}}_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:c__default.default.dirname(c__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 i=Date.now();return r.on("error",o=>{chunkD4SST7VW_cjs.d.error(this.name,"Spawn error:",o);}),r.on("exit",(o,n)=>{let h=Date.now()-i;this.onChildExit(r,o,n,h);}),r}catch(t){return chunkD4SST7VW_cjs.d.error(this.name,"Failed to fork child:",t),null}}onChildExit(t,e,r,i){let o=this.mp(),n=o.children.filter(h=>h!==t);if(this.patch({children:n}),o.status!=="stopping"){if(chunkD4SST7VW_cjs.d.warn(this.name,`Process exited (code=${e}, signal=${r}, uptime=${i}ms)`),o.isRestarting){n.length===0&&(this.patch({isRestarting:false}),this.spawnAll());return}e!==0&&e!==null&&(this.patch({status:"crashed"}),i<1500&&chunkD4SST7VW_cjs.d.error(this.name,`Immediate crash (${i}ms) \u2013 likely a syntax/build error. Waiting for next file change.`),this.scheduleRestart());}}scheduleRestart(){let t=this.mp(),e=t.backoffTime,r=this.cfg.maxBackoff??L;chunkD4SST7VW_cjs.d.warn(this.name,`Scheduling restart in ${e}ms (attempt #${t.restartCount+1})`);let i=setTimeout(async()=>{this.patch({restartCount:t.restartCount+1,backoffTime:Math.min(e*2,r)}),await this.spawnAll();},e);this.patch({restartTimer:i});}startProbe(){let t=this.cfg.probe,e=(t.intervalSeconds??10)*1e3,r=t.failureThreshold??3,o=setInterval(async()=>{let n=this.mp();if(n.status!=="running")return;if(await w(t)){n.probeFailures>0&&this.patch({probeFailures:0});return}let l=n.probeFailures+1;this.patch({probeFailures:l}),chunkD4SST7VW_cjs.d.warn(this.name,`Liveness probe failed (${l}/${r})`),l>=r&&(chunkD4SST7VW_cjs.d.error(this.name,"Liveness probe threshold exceeded \u2013 restarting."),this.patch({probeFailures:0}),await this.restart());},e);this.patch({probeTimer:o});}stopProbe(){let{probeTimer:t}=this.mp();t&&(clearInterval(t),this.patch({probeTimer:null,probeFailures:0}));}findProjectRoot(t){let e=c__default.default.resolve(t);for(m__default.default.existsSync(e)&&m__default.default.statSync(e).isFile()&&(e=c__default.default.dirname(e));e!==c__default.default.parse(e).root;){if(m__default.default.existsSync(c__default.default.join(e,"package.json")))return e;e=c__default.default.dirname(e);}return process.cwd()}watchFiles(){this.stopWatcher();let t=this.findProjectRoot(this.cfg.scriptPath),e=c__default.default.resolve(t,"src");chunkD4SST7VW_cjs.d.info(this.name,f__default.default.gray(`Watcher active on: ${e}`)),this.watcher=M__default.default.watch(e,{ignored:[/node_modules/,/\.pid$/],persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:1500,pollInterval:500}}),this.watcher.on("all",async(r,i)=>{if(!this.isBuilding&&(r==="change"||r==="add"))if(chunkD4SST7VW_cjs.d.info(this.name,f__default.default.yellow(`File ${r}: ${c__default.default.basename(i)} \u2013 restarting`)),this.cfg.reloadCommand){this.isBuilding=true,chunkD4SST7VW_cjs.d.info(this.name,f__default.default.blue(`Executing: ${this.cfg.reloadCommand}`));let{exec:o}=await import('child_process');o(this.cfg.reloadCommand,{cwd:t,env:{...process.env,PATH:`${c__default.default.resolve(t,"node_modules/.bin")}${c__default.default.delimiter}${process.env.PATH}`}},(n,h,l)=>{if(this.isBuilding=false,n){chunkD4SST7VW_cjs.d.error(this.name,`Build Failed:
3
+ ${l||h||n.message}`);return}chunkD4SST7VW_cjs.d.success(this.name,"Build successful. Triggering restart..."),this.restart();});}else this.restart();}),this.watcher.on("error",r=>chunkD4SST7VW_cjs.d.error(this.name,"Watcher error:",r)),this.watcher.on("ready",()=>chunkD4SST7VW_cjs.d.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){chunkD4SST7VW_cjs.e.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:d,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return chunkD4SST7VW_cjs.e.get(this.name)}_patch(t){chunkD4SST7VW_cjs.e.set(this.name,{...this.mp(),...t});}patch(t){let e=this.mp();t.status&&t.status!==e.status&&chunkD4SST7VW_cjs.d.info(this.name,`[STATE] ${e.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),t.lastError&&chunkD4SST7VW_cjs.d.error(this.name,`[REASON] ${t.lastError}`),chunkD4SST7VW_cjs.e.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 b__default.default(e),r.on("open",()=>chunkD4SST7VW_cjs.d.debug(this.name,"Connected to log collector")),r.on("error",o=>chunkD4SST7VW_cjs.d.error(this.name,"Log Collector WS Error",o.message)));let i=o=>{let n=o.toString();this.cfg.devMode&&process.stdout.write(`[${this.name}] ${n}`),r&&r.readyState===b__default.default.OPEN&&r.send(JSON.stringify({app:this.name,timestamp:Date.now(),log:n}));};t.stdout?.on("data",i),t.stderr?.on("data",i);}};var S=class{workers=new Map;async start(t){let e=this.workers.get(t.name);if(e){let i=chunkD4SST7VW_cjs.e.get(t.name);if(i?.status==="stopped"||i?.status==="crashed"||i?.status==="errored"){chunkD4SST7VW_cjs.d.info("ZPM",`Resuming existing worker "${t.name}"`),await e.start();return}chunkD4SST7VW_cjs.d.warn("ZPM",`Worker "${f__default.default.cyan(t.name)}" is ${f__default.default.cyan(i?.status)} - use restart()`);return}let r=new p(t);this.workers.set(t.name,r),await r.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),chunkD4SST7VW_cjs.e.delete(t),chunkD4SST7VW_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(){chunkD4SST7VW_cjs.d.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),chunkD4SST7VW_cjs.d.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||(chunkD4SST7VW_cjs.d.error(t,"Worker Not Found"),null)}require(t){let e=this.workers.get(t);return e||(chunkD4SST7VW_cjs.d.error(t,"Worker Not Found"),null)}};exports.a=w;exports.b=p;exports.c=S;
package/dist/daemon.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkTUMZTKHG_cjs=require('./chunk-TUMZTKHG.cjs'),chunkD4SST7VW_cjs=require('./chunk-D4SST7VW.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(){chunkD4SST7VW_cjs.d.success("daemon",`Booting ZPM daemon (PID ${process.pid})`),d();let o=new chunkTUMZTKHG_cjs.c,s=chunkD4SST7VW_cjs.g(o);async function t(e){chunkD4SST7VW_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=>chunkD4SST7VW_cjs.d.error("daemon","Uncaught exception:",e)),process.on("unhandledRejection",e=>chunkD4SST7VW_cjs.d.error("daemon","Unhandled rejection:",e)),chunkD4SST7VW_cjs.d.success("daemon","Ready \u2013 waiting for IPC commands.");}S().catch(o=>{chunkD4SST7VW_cjs.d.error("daemon","Fatal startup error:",o),process.exit(1);});
1
+ 'use strict';var chunkKBAMWOIM_cjs=require('./chunk-KBAMWOIM.cjs'),chunkD4SST7VW_cjs=require('./chunk-D4SST7VW.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(){chunkD4SST7VW_cjs.d.success("daemon",`Booting ZPM daemon (PID ${process.pid})`),d();let o=new chunkKBAMWOIM_cjs.c,s=chunkD4SST7VW_cjs.g(o);async function t(e){chunkD4SST7VW_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=>chunkD4SST7VW_cjs.d.error("daemon","Uncaught exception:",e)),process.on("unhandledRejection",e=>chunkD4SST7VW_cjs.d.error("daemon","Unhandled rejection:",e)),chunkD4SST7VW_cjs.d.success("daemon","Ready \u2013 waiting for IPC commands.");}S().catch(o=>{chunkD4SST7VW_cjs.d.error("daemon","Fatal startup error:",o),process.exit(1);});
package/dist/daemon.js CHANGED
@@ -1 +1 @@
1
- import {c}from'./chunk-RG3OLHUW.js';import {d as d$1,g}from'./chunk-USJACDTS.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 c,s=g(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 {c}from'./chunk-BDZZ2TSJ.js';import {d as d$1,g}from'./chunk-USJACDTS.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 c,s=g(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 chunkJWYNDWX7_cjs=require('./chunk-JWYNDWX7.cjs'),chunkTUMZTKHG_cjs=require('./chunk-TUMZTKHG.cjs'),chunkD4SST7VW_cjs=require('./chunk-D4SST7VW.cjs');Object.defineProperty(exports,"ZPMClient",{enumerable:true,get:function(){return chunkJWYNDWX7_cjs.a}});Object.defineProperty(exports,"zpm",{enumerable:true,get:function(){return chunkJWYNDWX7_cjs.b}});Object.defineProperty(exports,"ProcessManager",{enumerable:true,get:function(){return chunkTUMZTKHG_cjs.c}});Object.defineProperty(exports,"Worker",{enumerable:true,get:function(){return chunkTUMZTKHG_cjs.b}});Object.defineProperty(exports,"runProbe",{enumerable:true,get:function(){return chunkTUMZTKHG_cjs.a}});Object.defineProperty(exports,"WorkerMode",{enumerable:true,get:function(){return chunkD4SST7VW_cjs.b}});Object.defineProperty(exports,"WorkerStatus",{enumerable:true,get:function(){return chunkD4SST7VW_cjs.c}});Object.defineProperty(exports,"getSocketPath",{enumerable:true,get:function(){return chunkD4SST7VW_cjs.f}});Object.defineProperty(exports,"logger",{enumerable:true,get:function(){return chunkD4SST7VW_cjs.d}});Object.defineProperty(exports,"processStore",{enumerable:true,get:function(){return chunkD4SST7VW_cjs.e}});
1
+ 'use strict';var chunkJWYNDWX7_cjs=require('./chunk-JWYNDWX7.cjs'),chunkKBAMWOIM_cjs=require('./chunk-KBAMWOIM.cjs'),chunkD4SST7VW_cjs=require('./chunk-D4SST7VW.cjs');Object.defineProperty(exports,"ZPMClient",{enumerable:true,get:function(){return chunkJWYNDWX7_cjs.a}});Object.defineProperty(exports,"zpm",{enumerable:true,get:function(){return chunkJWYNDWX7_cjs.b}});Object.defineProperty(exports,"ProcessManager",{enumerable:true,get:function(){return chunkKBAMWOIM_cjs.c}});Object.defineProperty(exports,"Worker",{enumerable:true,get:function(){return chunkKBAMWOIM_cjs.b}});Object.defineProperty(exports,"runProbe",{enumerable:true,get:function(){return chunkKBAMWOIM_cjs.a}});Object.defineProperty(exports,"WorkerMode",{enumerable:true,get:function(){return chunkD4SST7VW_cjs.b}});Object.defineProperty(exports,"WorkerStatus",{enumerable:true,get:function(){return chunkD4SST7VW_cjs.c}});Object.defineProperty(exports,"getSocketPath",{enumerable:true,get:function(){return chunkD4SST7VW_cjs.f}});Object.defineProperty(exports,"logger",{enumerable:true,get:function(){return chunkD4SST7VW_cjs.d}});Object.defineProperty(exports,"processStore",{enumerable:true,get:function(){return chunkD4SST7VW_cjs.e}});
package/dist/index.d.cts CHANGED
@@ -146,6 +146,7 @@ declare class Worker {
146
146
  private scheduleRestart;
147
147
  private startProbe;
148
148
  private stopProbe;
149
+ private findProjectRoot;
149
150
  private watchFiles;
150
151
  private stopWatcher;
151
152
  private initStore;
package/dist/index.d.ts CHANGED
@@ -146,6 +146,7 @@ declare class Worker {
146
146
  private scheduleRestart;
147
147
  private startProbe;
148
148
  private stopProbe;
149
+ private findProjectRoot;
149
150
  private watchFiles;
150
151
  private stopWatcher;
151
152
  private initStore;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export{a as ZPMClient,b as zpm}from'./chunk-C2XMYYVX.js';export{c as ProcessManager,b as Worker,a as runProbe}from'./chunk-RG3OLHUW.js';export{b as WorkerMode,c as WorkerStatus,f as getSocketPath,d as logger,e as processStore}from'./chunk-USJACDTS.js';
1
+ export{a as ZPMClient,b as zpm}from'./chunk-C2XMYYVX.js';export{c as ProcessManager,b as Worker,a as runProbe}from'./chunk-BDZZ2TSJ.js';export{b as WorkerMode,c as WorkerStatus,f as getSocketPath,d as logger,e as processStore}from'./chunk-USJACDTS.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuzjs/pm",
3
- "version": "0.0.18",
3
+ "version": "0.0.19",
4
4
  "keywords": [
5
5
  "core",
6
6
  "zuz",