@zuzjs/pm 0.0.14 → 0.0.16

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 chunkX4TWGCVL_cjs=require('./chunk-X4TWGCVL.cjs'),child_process=require('child_process'),C=require('http'),$=require('https'),F=require('net'),_=require('chokidar'),M=require('fs'),k=require('os'),l=require('path'),w=require('ws'),N=require('pidusage'),v=require('picocolors');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var C__default=/*#__PURE__*/_interopDefault(C);var $__default=/*#__PURE__*/_interopDefault($);var F__default=/*#__PURE__*/_interopDefault(F);var ___default=/*#__PURE__*/_interopDefault(_);var M__default=/*#__PURE__*/_interopDefault(M);var k__default=/*#__PURE__*/_interopDefault(k);var l__default=/*#__PURE__*/_interopDefault(l);var w__default=/*#__PURE__*/_interopDefault(w);var N__default=/*#__PURE__*/_interopDefault(N);var v__default=/*#__PURE__*/_interopDefault(v);/* ZuzJS Process Manager */
2
+ function x(a,t){return new Promise(e=>{let i=(a.startsWith("https")?$__default.default:C__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 E(a,t){let[e,r]=a.split(":"),i=Number(r);return new Promise(o=>{let n=F__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 R(a,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);child_process.exec(a,i=>{clearTimeout(r),e(!i);});})}async function d(a){let t=(a.timeoutSeconds??5)*1e3;switch(a.type){case "http":return x(a.target,t);case "tcp":return E(a.target,t);case "exec":return R(a.target,t);default:return false}}var P=5e3,D=16e3,p=1e3,L=5e3;async function O(a){return new Promise(t=>{F__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=k__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 b(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;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"){chunkX4TWGCVL_cjs.d.warn(this.name,"Already running \u2013 ignoring start()");return}this.patch({status:"starting",isRestarting:false,children:[],restartCount:0,backoffTime:p,probeFailures:0,startTime:null}),this.clearTimers(),this.stopProbe(),chunkX4TWGCVL_cjs.d.info(this.name,"Initializing fresh start...");try{await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}catch(e){this.patch({status:"errored"}),chunkX4TWGCVL_cjs.d.error(this.name,`Start failed: ${e.message}`);}}async stop(){let t=this.mp();if(t.status==="stopping"){chunkX4TWGCVL_cjs.d.info(this.name,"Already stopping...");return}this.patch({status:"stopping",isRestarting:false}),chunkX4TWGCVL_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=>b(e,this.cfg.killTimeout??P))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){chunkX4TWGCVL_cjs.d.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),chunkX4TWGCVL_cjs.d.success(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(chunkX4TWGCVL_cjs.d.info(this.name,"Restarting..."),this.patch({isRestarting:true,status:"stopping"}),this.clearTimers(),this.stopProbe(),await Promise.all(t.children.map(e=>b(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(!M__default.default.existsSync(this.cfg.scriptPath)){chunkX4TWGCVL_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??k__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){chunkX4TWGCVL_cjs.d.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),chunkX4TWGCVL_cjs.d.success(this.name,`Started ${r.length} instance(s) [${t}]`);let i=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:p,restartCount:0}),chunkX4TWGCVL_cjs.d.success(this.name,"Process is stable."));},L);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=>{chunkX4TWGCVL_cjs.d.error(this.name,`Spawn error (${r}):`,c.message);}),n.on("exit",(c,y)=>{let S=Date.now()-h;this.onChildExit(n,c,y,S);}),n}catch(t){return chunkX4TWGCVL_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=>{chunkX4TWGCVL_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 chunkX4TWGCVL_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(chunkX4TWGCVL_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&&chunkX4TWGCVL_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??D;chunkX4TWGCVL_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 d(t)){n.probeFailures>0&&this.patch({probeFailures:0});return}let c=n.probeFailures+1;this.patch({probeFailures:c}),chunkX4TWGCVL_cjs.d.warn(this.name,`Liveness probe failed (${c}/${r})`),c>=r&&(chunkX4TWGCVL_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=l__default.default.dirname(this.cfg.scriptPath);this.watcher=___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")&&(chunkX4TWGCVL_cjs.d.info(this.name,`File ${e}: ${l__default.default.basename(r)} \u2013 restarting`),this.restart());}),this.watcher.on("error",e=>chunkX4TWGCVL_cjs.d.error(this.name,"Watcher error:",e)),this.watcher.on("ready",()=>chunkX4TWGCVL_cjs.d.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){chunkX4TWGCVL_cjs.e.set(this.name,{config:this.cfg,children:[],status:"stopped",startTime:null,restartCount:0,backoffTime:p,restartTimer:null,stabilityTimer:null,probeTimer:null,probeFailures:0,isRestarting:false});}mp(){return chunkX4TWGCVL_cjs.e.get(this.name)}_patch(t){chunkX4TWGCVL_cjs.e.set(this.name,{...this.mp(),...t});}patch(t){let e=this.mp();t.status&&t.status!==e.status&&chunkX4TWGCVL_cjs.d.info(this.name,`[STATE] ${e.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),t.lastError&&chunkX4TWGCVL_cjs.d.error(this.name,`[REASON] ${t.lastError}`),chunkX4TWGCVL_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 w__default.default(e),r.on("open",()=>chunkX4TWGCVL_cjs.d.debug(this.name,"Connected to log collector")),r.on("error",o=>chunkX4TWGCVL_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===w__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 T=class{workers=new Map;async start(t){let e=this.workers.get(t.name);if(e){let i=chunkX4TWGCVL_cjs.e.get(t.name);if(i?.status==="stopped"||i?.status==="crashed"||i?.status==="errored"){chunkX4TWGCVL_cjs.d.info("ZPM",`Resuming existing worker "${t.name}"`),await e.start();return}chunkX4TWGCVL_cjs.d.warn("ZPM",`Worker "${v__default.default.cyan(t.name)}" is ${v__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),chunkX4TWGCVL_cjs.e.delete(t),chunkX4TWGCVL_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(){chunkX4TWGCVL_cjs.d.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),chunkX4TWGCVL_cjs.d.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||(chunkX4TWGCVL_cjs.d.error(t,"Worker Not Found"),null)}require(t){let e=this.workers.get(t);return e||(chunkX4TWGCVL_cjs.d.error(t,"Worker Not Found"),null)}};exports.a=d;exports.b=m;exports.c=T;
@@ -0,0 +1 @@
1
+ import {d,e}from'./chunk-USJACDTS.js';import {spawn,exec}from'child_process';import $ from'http';import F from'https';import x from'net';import A from'chokidar';import I from'fs';import v from'os';import l from'path';import P from'ws';import D from'pidusage';import T from'picocolors';function E(a,t){return new Promise(e=>{let i=(a.startsWith("https")?F:$).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.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 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.target,t);default:return false}}var b=5e3,L=16e3,p=1e3,O=5e3;async function q(a){return new Promise(t=>{x.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(a);})}async function B(a){if(await q(a))return;let t=v.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 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;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.warn(this.name,"Already running \u2013 ignoring start()");return}this.patch({status:"starting",isRestarting:false,children:[],restartCount:0,backoffTime:p,probeFailures:0,startTime:null}),this.clearTimers(),this.stopProbe(),d.info(this.name,"Initializing fresh start...");try{await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}catch(e){this.patch({status:"errored"}),d.error(this.name,`Start failed: ${e.message}`);}}async stop(){let t=this.mp();if(t.status==="stopping"){d.info(this.name,"Already stopping...");return}this.patch({status:"stopping",isRestarting:false}),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??b))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){d.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),d.success(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(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??b))),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 D(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.existsSync(this.cfg.scriptPath)){d.error(this.name,`Script not found: ${this.cfg.scriptPath}. Waiting for build...`),this.patch({status:"errored"});return}this.cfg.port&&await B(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??v.cpus().length:1,r=[];for(let o=0;o<e;o++){let n=this.forkChild();n&&r.push(n);}if(r.length===0){d.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),d.success(this.name,`Started ${r.length} instance(s) [${t}]`);let i=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:p,restartCount:0}),d.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.error(this.name,`Spawn error (${r}):`,c.message);}),n.on("exit",(c,S)=>{let W=Date.now()-h;this.onChildExit(n,c,S,W);}),n}catch(t){return 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=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.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.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.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.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;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}),d.warn(this.name,`Liveness probe failed (${c}/${r})`),c>=r&&(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=l.dirname(this.cfg.scriptPath);this.watcher=A.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.info(this.name,`File ${e}: ${l.basename(r)} \u2013 restarting`),this.restart());}),this.watcher.on("error",e=>d.error(this.name,"Watcher error:",e)),this.watcher.on("ready",()=>d.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:p,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.info(this.name,`[STATE] ${e$1.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),t.lastError&&d.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.debug(this.name,"Connected to log collector")),r.on("error",o=>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===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 y=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.info("ZPM",`Resuming existing worker "${t.name}"`),await e$1.start();return}d.warn("ZPM",`Worker "${T.cyan(t.name)}" is ${T.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.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.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),d.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||(d.error(t,"Worker Not Found"),null)}require(t){let e=this.workers.get(t);return e||(d.error(t,"Worker Not Found"),null)}};export{g as a,m as b,y as c};
package/dist/daemon.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkKXRLI3RB_cjs=require('./chunk-KXRLI3RB.cjs'),chunkX4TWGCVL_cjs=require('./chunk-X4TWGCVL.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(){chunkX4TWGCVL_cjs.d.success("daemon",`Booting ZPM daemon (PID ${process.pid})`),d();let o=new chunkKXRLI3RB_cjs.c,s=chunkX4TWGCVL_cjs.g(o);async function t(e){chunkX4TWGCVL_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=>chunkX4TWGCVL_cjs.d.error("daemon","Uncaught exception:",e)),process.on("unhandledRejection",e=>chunkX4TWGCVL_cjs.d.error("daemon","Unhandled rejection:",e)),chunkX4TWGCVL_cjs.d.success("daemon","Ready \u2013 waiting for IPC commands.");}S().catch(o=>{chunkX4TWGCVL_cjs.d.error("daemon","Fatal startup error:",o),process.exit(1);});
1
+ 'use strict';var chunkR3GSFE3M_cjs=require('./chunk-R3GSFE3M.cjs'),chunkX4TWGCVL_cjs=require('./chunk-X4TWGCVL.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(){chunkX4TWGCVL_cjs.d.success("daemon",`Booting ZPM daemon (PID ${process.pid})`),d();let o=new chunkR3GSFE3M_cjs.c,s=chunkX4TWGCVL_cjs.g(o);async function t(e){chunkX4TWGCVL_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=>chunkX4TWGCVL_cjs.d.error("daemon","Uncaught exception:",e)),process.on("unhandledRejection",e=>chunkX4TWGCVL_cjs.d.error("daemon","Unhandled rejection:",e)),chunkX4TWGCVL_cjs.d.success("daemon","Ready \u2013 waiting for IPC commands.");}S().catch(o=>{chunkX4TWGCVL_cjs.d.error("daemon","Fatal startup error:",o),process.exit(1);});
package/dist/daemon.js CHANGED
@@ -1 +1 @@
1
- import {c}from'./chunk-XWDXM76F.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-WXDVA6OC.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 chunkFXHHFO4C_cjs=require('./chunk-FXHHFO4C.cjs'),chunkKXRLI3RB_cjs=require('./chunk-KXRLI3RB.cjs'),chunkX4TWGCVL_cjs=require('./chunk-X4TWGCVL.cjs');Object.defineProperty(exports,"ZPMClient",{enumerable:true,get:function(){return chunkFXHHFO4C_cjs.a}});Object.defineProperty(exports,"zpm",{enumerable:true,get:function(){return chunkFXHHFO4C_cjs.b}});Object.defineProperty(exports,"ProcessManager",{enumerable:true,get:function(){return chunkKXRLI3RB_cjs.c}});Object.defineProperty(exports,"Worker",{enumerable:true,get:function(){return chunkKXRLI3RB_cjs.b}});Object.defineProperty(exports,"runProbe",{enumerable:true,get:function(){return chunkKXRLI3RB_cjs.a}});Object.defineProperty(exports,"WorkerMode",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.b}});Object.defineProperty(exports,"WorkerStatus",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.c}});Object.defineProperty(exports,"getSocketPath",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.f}});Object.defineProperty(exports,"logger",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.d}});Object.defineProperty(exports,"processStore",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.e}});
1
+ 'use strict';var chunkFXHHFO4C_cjs=require('./chunk-FXHHFO4C.cjs'),chunkR3GSFE3M_cjs=require('./chunk-R3GSFE3M.cjs'),chunkX4TWGCVL_cjs=require('./chunk-X4TWGCVL.cjs');Object.defineProperty(exports,"ZPMClient",{enumerable:true,get:function(){return chunkFXHHFO4C_cjs.a}});Object.defineProperty(exports,"zpm",{enumerable:true,get:function(){return chunkFXHHFO4C_cjs.b}});Object.defineProperty(exports,"ProcessManager",{enumerable:true,get:function(){return chunkR3GSFE3M_cjs.c}});Object.defineProperty(exports,"Worker",{enumerable:true,get:function(){return chunkR3GSFE3M_cjs.b}});Object.defineProperty(exports,"runProbe",{enumerable:true,get:function(){return chunkR3GSFE3M_cjs.a}});Object.defineProperty(exports,"WorkerMode",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.b}});Object.defineProperty(exports,"WorkerStatus",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.c}});Object.defineProperty(exports,"getSocketPath",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.f}});Object.defineProperty(exports,"logger",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.d}});Object.defineProperty(exports,"processStore",{enumerable:true,get:function(){return chunkX4TWGCVL_cjs.e}});
package/dist/index.d.cts CHANGED
@@ -132,12 +132,11 @@ declare class Worker {
132
132
  constructor(config: WorkerConfig);
133
133
  start(): Promise<void>;
134
134
  stop(): Promise<void>;
135
- _stop(): Promise<void>;
136
135
  restart(): Promise<void>;
137
- _restart(): Promise<void>;
138
136
  getStats(): Promise<WorkerStats>;
139
137
  private spawnAll;
140
138
  private forkChild;
139
+ private _forkChild;
141
140
  private onChildExit;
142
141
  private scheduleRestart;
143
142
  private startProbe;
package/dist/index.d.ts CHANGED
@@ -132,12 +132,11 @@ declare class Worker {
132
132
  constructor(config: WorkerConfig);
133
133
  start(): Promise<void>;
134
134
  stop(): Promise<void>;
135
- _stop(): Promise<void>;
136
135
  restart(): Promise<void>;
137
- _restart(): Promise<void>;
138
136
  getStats(): Promise<WorkerStats>;
139
137
  private spawnAll;
140
138
  private forkChild;
139
+ private _forkChild;
141
140
  private onChildExit;
142
141
  private scheduleRestart;
143
142
  private startProbe;
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-XWDXM76F.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-WXDVA6OC.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.14",
3
+ "version": "0.0.16",
4
4
  "keywords": [
5
5
  "core",
6
6
  "zuz",
@@ -1,2 +0,0 @@
1
- 'use strict';var chunkX4TWGCVL_cjs=require('./chunk-X4TWGCVL.cjs'),child_process=require('child_process'),v=require('http'),y=require('https'),S=require('net'),F=require('chokidar'),I=require('fs'),k=require('os'),u=require('path'),b=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 S__default=/*#__PURE__*/_interopDefault(S);var F__default=/*#__PURE__*/_interopDefault(F);var I__default=/*#__PURE__*/_interopDefault(I);var k__default=/*#__PURE__*/_interopDefault(k);var u__default=/*#__PURE__*/_interopDefault(u);var b__default=/*#__PURE__*/_interopDefault(b);var E__default=/*#__PURE__*/_interopDefault(E);/* ZuzJS Process Manager */
2
- function W(n,t){return new Promise(e=>{let o=(n.startsWith("https")?y__default.default:v__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 C(n,t){let[e,r]=n.split(":"),o=Number(r);return new Promise(i=>{let a=S__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 $(n,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);child_process.exec(n,o=>{clearTimeout(r),e(!o);});})}async function w(n){let t=(n.timeoutSeconds??5)*1e3;switch(n.type){case "http":return W(n.target,t);case "tcp":return C(n.target,t);case "exec":return $(n.target,t);default:return false}}var m=5e3,M=16e3,d=1e3,A=5e3;async function L(n){return new Promise(t=>{S__default.default.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(n);})}async function N(n){if(await L(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"){chunkX4TWGCVL_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(),chunkX4TWGCVL_cjs.d.info(this.name,"Initializing fresh start...");try{await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}catch(e){this.patch({status:"errored"}),chunkX4TWGCVL_cjs.d.error(this.name,`Start failed: ${e.message}`);}}async stop(){let t=this.mp();if(t.status==="stopping"){chunkX4TWGCVL_cjs.d.info(this.name,"Already stopping...");return}this.patch({status:"stopping",isRestarting:false}),chunkX4TWGCVL_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??m))),new Promise((e,r)=>setTimeout(()=>r(new Error("Termination timeout")),1e4))]);}catch(e){chunkX4TWGCVL_cjs.d.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),chunkX4TWGCVL_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??m);this.stopWatcher(),this.patch({children:[],status:"stopped",startTime:null}),chunkX4TWGCVL_cjs.d.info(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(chunkX4TWGCVL_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??m))),this.patch({isRestarting:false,children:[]}));}async _restart(){chunkX4TWGCVL_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??m);}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(!I__default.default.existsSync(this.cfg.scriptPath)){chunkX4TWGCVL_cjs.d.error(this.name,`Script not found: ${this.cfg.scriptPath}. Waiting for build...`),this.patch({status:"errored"});return}this.cfg.port&&await N(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){chunkX4TWGCVL_cjs.d.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),chunkX4TWGCVL_cjs.d.success(this.name,`Started ${r.length} instance(s) [${t}]`);let o=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:d,restartCount:0}),chunkX4TWGCVL_cjs.d.success(this.name,"Process is stable."));},A);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:u__default.default.dirname(u__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=>{chunkX4TWGCVL_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 chunkX4TWGCVL_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(chunkX4TWGCVL_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}e!==0&&e!==null&&(this.patch({status:"crashed"}),o<1500&&chunkX4TWGCVL_cjs.d.error(this.name,`Immediate crash (${o}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??M;chunkX4TWGCVL_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 w(t)){a.probeFailures>0&&this.patch({probeFailures:0});return}let h=a.probeFailures+1;this.patch({probeFailures:h}),chunkX4TWGCVL_cjs.d.warn(this.name,`Liveness probe failed (${h}/${r})`),h>=r&&(chunkX4TWGCVL_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=u__default.default.dirname(this.cfg.scriptPath);this.watcher=F__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")&&(chunkX4TWGCVL_cjs.d.info(this.name,`File ${e}: ${u__default.default.basename(r)} \u2013 restarting`),this.restart());}),this.watcher.on("error",e=>chunkX4TWGCVL_cjs.d.error(this.name,"Watcher error:",e)),this.watcher.on("ready",()=>chunkX4TWGCVL_cjs.d.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){chunkX4TWGCVL_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 chunkX4TWGCVL_cjs.e.get(this.name)}_patch(t){chunkX4TWGCVL_cjs.e.set(this.name,{...this.mp(),...t});}patch(t){let e=this.mp();t.status&&t.status!==e.status&&chunkX4TWGCVL_cjs.d.info(this.name,`[STATE] ${e.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),t.lastError&&chunkX4TWGCVL_cjs.d.error(this.name,`[REASON] ${t.lastError}`),chunkX4TWGCVL_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",()=>chunkX4TWGCVL_cjs.d.debug(this.name,"Connected to log collector")),r.on("error",i=>chunkX4TWGCVL_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===b__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 P=class{workers=new Map;async start(t){if(this.workers.has(t.name)){chunkX4TWGCVL_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),chunkX4TWGCVL_cjs.e.delete(t),chunkX4TWGCVL_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(){chunkX4TWGCVL_cjs.d.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),chunkX4TWGCVL_cjs.d.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||(chunkX4TWGCVL_cjs.d.error(t,"Worker Not Found"),null)}require(t){let e=this.workers.get(t);return e||(chunkX4TWGCVL_cjs.d.error(t,"Worker Not Found"),null)}};exports.a=w;exports.b=f;exports.c=P;
@@ -1 +0,0 @@
1
- import {d as d$1,e}from'./chunk-USJACDTS.js';import {spawn,exec}from'child_process';import y from'http';import S from'https';import W from'net';import R from'chokidar';import _ from'fs';import P from'os';import u from'path';import k from'ws';import M from'pidusage';function C(n,t){return new Promise(e=>{let o=(n.startsWith("https")?S:y).get(n,{timeout:t},i=>{e((i.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(i=>{let a=W.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 F(n,t){return new Promise(e=>{let r=setTimeout(()=>e(false),t);exec(n,o=>{clearTimeout(r),e(!o);});})}async function b(n){let t=(n.timeoutSeconds??5)*1e3;switch(n.type){case "http":return C(n.target,t);case "tcp":return $(n.target,t);case "exec":return F(n.target,t);default:return false}}var m=5e3,A=16e3,d=1e3,L=5e3;async function N(n){return new Promise(t=>{W.createServer().once("error",()=>t(false)).once("listening",function(){this.close(()=>t(true));}).listen(n);})}async function D(n){if(await N(n))return;let t=P.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: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=>p(e,this.cfg.killTimeout??m))),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??m);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??m))),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??m);}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 M(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(!_.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 D(this.cfg.port);let t=this.cfg.mode??"fork",e=t==="cluster"?this.cfg.instances??P.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:d,restartCount:0}),d$1.success(this.name,"Process is stable."));},L);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:u.dirname(u.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}e!==0&&e!==null&&(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.`),this.scheduleRestart());}}scheduleRestart(){let t=this.mp(),e=t.backoffTime,r=this.cfg.maxBackoff??A;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 b(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=u.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}: ${u.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(){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",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 T=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$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{b as a,f as b,T as c};