@zuzjs/pm 0.0.19 → 0.0.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-AZIXEAKE.js +2 -0
- package/dist/chunk-CLGIBT3W.cjs +4 -0
- package/dist/chunk-FXEDN7ZZ.js +6 -0
- package/dist/chunk-IYTWXZHG.js +3 -0
- package/dist/{chunk-D4SST7VW.cjs → chunk-WPWZGJN5.cjs} +6 -6
- package/dist/chunk-YGHAA45S.cjs +3 -0
- package/dist/cli.cjs +8 -8
- package/dist/cli.js +7 -7
- package/dist/daemon.cjs +2 -2
- package/dist/daemon.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +15 -1
- package/dist/index.d.ts +15 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-BDZZ2TSJ.js +0 -2
- package/dist/chunk-C2XMYYVX.js +0 -3
- package/dist/chunk-JWYNDWX7.cjs +0 -4
- package/dist/chunk-KBAMWOIM.cjs +0 -3
- package/dist/chunk-USJACDTS.js +0 -6
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {d as d$1,e}from'./chunk-FXEDN7ZZ.js';import {spawn,exec}from'child_process';import x from'http';import R from'https';import E from'net';import I from'chokidar';import p 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 m=class{cfg;name;watcher=null;isBuilding=false;constructor(t){this.cfg={mode:"fork",instances:1,...t},this.name=t.name,this.initStore();}getConfig(){return this.cfg}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(!p.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(p.existsSync(e)&&p.statSync(e).isFile()&&(e=c.dirname(e));e!==c.parse(e).root;){if(p.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 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)}async addWorker(t,e){let r=new m(t);this.workers.set(t.name,r),e&&await r.start();}require(t){let e=this.workers.get(t);return e||(d$1.error(t,"Worker Not Found"),null)}};export{P as a,m as b,C as c};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';var chunkWPWZGJN5_cjs=require('./chunk-WPWZGJN5.cjs'),child_process=require('child_process'),p=require('fs'),h=require('net'),w=require('os'),P=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var p__default=/*#__PURE__*/_interopDefault(p);var h__default=/*#__PURE__*/_interopDefault(h);var w__default=/*#__PURE__*/_interopDefault(w);var P__default=/*#__PURE__*/_interopDefault(P);/* ZuzJS Process Manager */
|
|
2
|
+
function s(d,e="zuz-pm"){return new Promise((r,t)=>{let n=h__default.default.createConnection(chunkWPWZGJN5_cjs.f(e)),o="";n.on("connect",()=>{n.write(JSON.stringify(d)+`
|
|
3
|
+
`);}),n.on("data",i=>{o+=i.toString();let m=o.split(`
|
|
4
|
+
`);o=m.pop()??"";for(let g of m)if(g.trim())try{let a=JSON.parse(g);n.destroy(),a.ok?r(a.data):t(new Error(a.error));}catch(a){n.destroy(),t(a);}}),n.on("error",i=>t(i)),n.setTimeout(1e4,()=>{n.destroy(),t(new Error("IPC timeout"));});})}var u=class{daemonScript;namespace;constructor(e){this.namespace=e?.namespace??"zuz-pm",this.daemonScript=e?.daemonScript??P__default.default.join(__dirname,"daemon.js");}async isDaemonRunning(){try{return chunkWPWZGJN5_cjs.d.info("[ZPM]","Daemon is Running :?"),await s({cmd:"ping"},this.namespace),!0}catch{return chunkWPWZGJN5_cjs.d.info("[ZPM]","Daemon is not running."),false}}async ensureDaemon(){if(await this.isDaemonRunning())return;chunkWPWZGJN5_cjs.d.info("Starting ZPM daemon...");let r=process.env.NODE_ENV!=="production";child_process.spawn(process.execPath,[this.daemonScript],{detached:true,stdio:r?"inherit":"ignore"}).unref(),await this.waitForDaemon(8e3);}async killDaemon(){let e=P__default.default.join(w__default.default.tmpdir(),"zuz-pm.pid");if(!p__default.default.existsSync(e))throw new Error("Daemon PID file not found \u2013 is the daemon running?");let r=Number(p__default.default.readFileSync(e,"utf8").trim());try{process.kill(r,"SIGTERM"),console.log(`[ZPM] Sent SIGTERM to daemon (PID ${r})`);}catch(t){throw new Error(`Failed to kill daemon: ${t.message}`)}finally{p__default.default.unlinkSync(e);}}async getStore(){let e=await s({cmd:"get-store"},this.namespace);return e.ok==true?e.data:null}async getProcessByName(e){let r=await s({cmd:"get-store"},this.namespace);return (r.ok==true?r.data:[]).find(n=>n.name==e)}async start(e){return s({cmd:"start",name:e.name,config:e},this.namespace)}async stop(e){return s({cmd:"stop",name:e},this.namespace)}async restart(e){return s({cmd:"restart",name:e},this.namespace)}async delete(e){return s({cmd:"delete",name:e},this.namespace)}async replaceWorker(e,r,t){let n=await this.getWorkerByName(e);if(n)return await this.stop(e),await this.delete(e),await s({cmd:"add-worker",config:{...n.getConfig(),name:r},autoStart:t})}async getWorkerByName(e){return await s({cmd:"find-worker",name:e},this.namespace)}async stats(e){return s({cmd:"stats",name:e},this.namespace)}async list(){return s({cmd:"list"},this.namespace)}waitForDaemon(e){let r=Date.now(),t=200;return new Promise((n,o)=>{let i=()=>{this.isDaemonRunning().then(m=>{if(m)return n();if(Date.now()-r>e)return o(new Error("Daemon did not start in time"));setTimeout(i,t);});};setTimeout(i,t);})}},W=new u;exports.a=u;exports.b=W;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import C from'path';import {fileURLToPath}from'url';import y from'os';import g from'picocolors';import c from'winston';import D from'events';import w from'fs';import W from'net';var I=()=>fileURLToPath(import.meta.url),N=()=>C.dirname(I()),u=N();var R=(s=>(s.Fork="fork",s.Cluster="cluster",s))(R||{}),L=(n=>(n.Stopped="stopped",n.Starting="starting",n.Running="running",n.Stopping="stopping",n.Crashed="crashed",n.Errored="errored",n))(L||{});var F=C.join(y.homedir(),".zpm","logs"),J=c.format.combine(c.format.timestamp({format:"YYYY/MM/DD HH:mm:ss"}),c.format.splat(),c.format.printf(({timestamp:e,level:r,message:s,tag:t})=>{let o=g.gray(`[${e}]`),m=g.bold(`[ZPM/${(t||"SYS").toUpperCase()}]`);return `${o} [${r=="info"?g.cyan(r):r=="warn"?g.yellow(r):r=="error"?g.red(r):r=="success"?g.green(r):r=="debug"?g.gray(r):"debug"}] ${m} \u2192 ${s}`})),l=c.createLogger({levels:{error:0,warn:1,info:2,success:2,debug:3},transports:[new c.transports.Console({level:"debug",format:J}),new c.transports.File({filename:C.join(F,"daemon.log"),format:c.format.combine(c.format.timestamp(),c.format.json())})]}),p={info:(e,...r)=>l.info(r.join(" "),{tag:e}),warn:(e,...r)=>l.warn(r.join(" "),{tag:e}),error:(e,...r)=>l.error(r.join(" "),{tag:e}),debug:(e,...r)=>l.debug(r.join(" "),{tag:e}),success:(e,...r)=>l.log("success",r.join(" "),{tag:e})};var k=class extends D{map=new Map;set(r,s){this.map.set(r,s),this.emit("change",r,s);}get(r){return this.map.get(r)}has(r){return this.map.has(r)}delete(r){this.map.delete(r),this.emit("delete",r);}all(){return new Map(this.map)}onchange(r){return this.on("change",r)}offchange(r){return this.off("change",r)}},P=new k;function O(e="zuz-pm"){return y.platform()==="win32"?C.join("\\\\.\\pipe",e):C.join(y.tmpdir(),`${e}.sock`)}function ar(e){let r=O();w.existsSync(r)&&w.unlinkSync(r);let s=W.createServer(t=>{let o="";t.on("data",m=>{o+=m.toString();let n=o.split(`
|
|
2
|
+
`);o=n.pop()??"";for(let d of n)d.trim()&&E(e,t,d);}),t.on("error",m=>{p.error("IPC","Socket error:",m.message);});});return s.listen(r,()=>{if(y.platform()!=="win32")try{w.chmodSync(r,"777");}catch(t){console.error("Failed to set socket permissions:",t);}p.success("IPC",`Listening on ${r}`);}),s.on("error",t=>{p.error("IPC","Server error:",t);}),s}async function E(e,r,s){let t;try{t=JSON.parse(s);}catch{S(r,{ok:false,error:"Invalid JSON"});return}try{let o=null;switch(t.cmd){case "ping":o="pong";break;case "start":await e.start(t.config),o=`Started "${t.name}"`;break;case "stop":await e.stop(t.name),o=`Stopped "${t.name}"`;break;case "restart":await e.restart(t.name),o=`Restarted "${t.name}"`;break;case "delete":await e.delete(t.name),o=`Deleted "${t.name}"`;break;case "stats":o=await e.getStats(t.name);break;case "list":o=e.list();break;case "add-worker":await e.addWorker(t.config,t.autoStart),o=`Added "${t.config.name}"`;break;case "find-worker":o=e.getWorker(t.name);break;case "get-store":{o=Array.from(P.all()).map(([i,a])=>({name:i,status:a.status,childrenCount:a.children.length,restartCount:a.restartCount,backoffTime:a.backoffTime,isRestarting:a.isRestarting,probeFailures:a.probeFailures}));break}case "logs":let m=t.name,n=[];if(m){let i=e.getWorker(m);if(!i){r.write(JSON.stringify({ok:!1,error:`Worker "${m}" not found`})+`
|
|
3
|
+
`);return}n.push(i);}else {let i=e.list();for(let a of i){let f=e.getWorker(a);f&&n.push(f);}}if(n.length===0){r.write(JSON.stringify({ok:!1,error:"No active workers to stream logs from"})+`
|
|
4
|
+
`);return}let d=[];for(let i of n){let a=i.mp();for(let f of a.children){let b=x=>{let $=m?"":`[${i.name}] `;r.write(JSON.stringify({ok:!0,data:`${$}${x.toString()}`})+`
|
|
5
|
+
`);};f.stdout?.on("data",b),f.stderr?.on("data",b),d.push({child:f,onData:b});}}r.on("close",()=>{for(let{child:i,onData:a}of d)i.stdout?.off("data",a),i.stderr?.off("data",a);});break;default:p.error("ZPM",`Unknown command: ${t.cmd}`);}S(r,{ok:!0,data:o});}catch(o){S(r,{ok:false,error:String(o.message??o)});}}function S(e,r){e.writable&&e.write(JSON.stringify(r)+`
|
|
6
|
+
`);}export{u as a,R as b,L as c,p as d,P as e,O as f,ar as g};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a,d,f as f$1}from'./chunk-FXEDN7ZZ.js';import {spawn}from'child_process';import p from'fs';import w from'net';import y from'os';import f from'path';function s(d,e="zuz-pm"){return new Promise((r,t)=>{let n=w.createConnection(f$1(e)),i="";n.on("connect",()=>{n.write(JSON.stringify(d)+`
|
|
2
|
+
`);}),n.on("data",o=>{i+=o.toString();let m=i.split(`
|
|
3
|
+
`);i=m.pop()??"";for(let g of m)if(g.trim())try{let a=JSON.parse(g);n.destroy(),a.ok?r(a.data):t(new Error(a.error));}catch(a){n.destroy(),t(a);}}),n.on("error",o=>t(o)),n.setTimeout(1e4,()=>{n.destroy(),t(new Error("IPC timeout"));});})}var u=class{daemonScript;namespace;constructor(e){this.namespace=e?.namespace??"zuz-pm",this.daemonScript=e?.daemonScript??f.join(a,"daemon.js");}async isDaemonRunning(){try{return d.info("[ZPM]","Daemon is Running :?"),await s({cmd:"ping"},this.namespace),!0}catch{return d.info("[ZPM]","Daemon is not running."),false}}async ensureDaemon(){if(await this.isDaemonRunning())return;d.info("Starting ZPM daemon...");let r=process.env.NODE_ENV!=="production";spawn(process.execPath,[this.daemonScript],{detached:true,stdio:r?"inherit":"ignore"}).unref(),await this.waitForDaemon(8e3);}async killDaemon(){let e=f.join(y.tmpdir(),"zuz-pm.pid");if(!p.existsSync(e))throw new Error("Daemon PID file not found \u2013 is the daemon running?");let r=Number(p.readFileSync(e,"utf8").trim());try{process.kill(r,"SIGTERM"),console.log(`[ZPM] Sent SIGTERM to daemon (PID ${r})`);}catch(t){throw new Error(`Failed to kill daemon: ${t.message}`)}finally{p.unlinkSync(e);}}async getStore(){let e=await s({cmd:"get-store"},this.namespace);return e.ok==true?e.data:null}async getProcessByName(e){let r=await s({cmd:"get-store"},this.namespace);return (r.ok==true?r.data:[]).find(n=>n.name==e)}async start(e){return s({cmd:"start",name:e.name,config:e},this.namespace)}async stop(e){return s({cmd:"stop",name:e},this.namespace)}async restart(e){return s({cmd:"restart",name:e},this.namespace)}async delete(e){return s({cmd:"delete",name:e},this.namespace)}async replaceWorker(e,r,t){let n=await this.getWorkerByName(e);if(n)return await this.stop(e),await this.delete(e),await s({cmd:"add-worker",config:{...n.getConfig(),name:r},autoStart:t})}async getWorkerByName(e){return await s({cmd:"find-worker",name:e},this.namespace)}async stats(e){return s({cmd:"stats",name:e},this.namespace)}async list(){return s({cmd:"list"},this.namespace)}waitForDaemon(e){let r=Date.now(),t=200;return new Promise((n,i)=>{let o=()=>{this.isDaemonRunning().then(m=>{if(m)return n();if(Date.now()-r>e)return i(new Error("Daemon did not start in time"));setTimeout(o,t);});};setTimeout(o,t);})}},E=new u;export{u as a,E as b};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
var $=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,l=$();var I=(s=>(s.Fork="fork",s.Cluster="cluster",s))(I||{}),M=(o=>(o.Stopped="stopped",o.Starting="starting",o.Running="running",o.Stopping="stopping",o.Crashed="crashed",o.Errored="errored",o))(M||{});var R=
|
|
3
|
-
`);n=o.pop()??"";for(let
|
|
4
|
-
`);return}o.push(i);}else {let i=e.list();for(let a of i){let
|
|
5
|
-
`);return}let
|
|
6
|
-
`);};
|
|
1
|
+
'use strict';var S=require('os'),C=require('path'),g=require('picocolors'),c=require('winston'),L=require('events'),k=require('fs'),j=require('net');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var S__default=/*#__PURE__*/_interopDefault(S);var C__default=/*#__PURE__*/_interopDefault(C);var g__default=/*#__PURE__*/_interopDefault(g);var c__default=/*#__PURE__*/_interopDefault(c);var L__default=/*#__PURE__*/_interopDefault(L);var k__default=/*#__PURE__*/_interopDefault(k);var j__default=/*#__PURE__*/_interopDefault(j);/* ZuzJS Process Manager */
|
|
2
|
+
var $=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,l=$();var I=(s=>(s.Fork="fork",s.Cluster="cluster",s))(I||{}),M=(o=>(o.Stopped="stopped",o.Starting="starting",o.Running="running",o.Stopping="stopping",o.Crashed="crashed",o.Errored="errored",o))(M||{});var R=C__default.default.join(S__default.default.homedir(),".zpm","logs"),N=c__default.default.format.combine(c__default.default.format.timestamp({format:"YYYY/MM/DD HH:mm:ss"}),c__default.default.format.splat(),c__default.default.format.printf(({timestamp:e,level:r,message:s,tag:t})=>{let n=g__default.default.gray(`[${e}]`),m=g__default.default.bold(`[ZPM/${(t||"SYS").toUpperCase()}]`);return `${n} [${r=="info"?g__default.default.cyan(r):r=="warn"?g__default.default.yellow(r):r=="error"?g__default.default.red(r):r=="success"?g__default.default.green(r):r=="debug"?g__default.default.gray(r):"debug"}] ${m} \u2192 ${s}`})),u=c__default.default.createLogger({levels:{error:0,warn:1,info:2,success:2,debug:3},transports:[new c__default.default.transports.Console({level:"debug",format:N}),new c__default.default.transports.File({filename:C__default.default.join(R,"daemon.log"),format:c__default.default.format.combine(c__default.default.format.timestamp(),c__default.default.format.json())})]}),p={info:(e,...r)=>u.info(r.join(" "),{tag:e}),warn:(e,...r)=>u.warn(r.join(" "),{tag:e}),error:(e,...r)=>u.error(r.join(" "),{tag:e}),debug:(e,...r)=>u.debug(r.join(" "),{tag:e}),success:(e,...r)=>u.log("success",r.join(" "),{tag:e})};var h=class extends L__default.default{map=new Map;set(r,s){this.map.set(r,s),this.emit("change",r,s);}get(r){return this.map.get(r)}has(r){return this.map.has(r)}delete(r){this.map.delete(r),this.emit("delete",r);}all(){return new Map(this.map)}onchange(r){return this.on("change",r)}offchange(r){return this.off("change",r)}},y=new h;function J(e="zuz-pm"){return S__default.default.platform()==="win32"?C__default.default.join("\\\\.\\pipe",e):C__default.default.join(S__default.default.tmpdir(),`${e}.sock`)}function rr(e){let r=J();k__default.default.existsSync(r)&&k__default.default.unlinkSync(r);let s=j__default.default.createServer(t=>{let n="";t.on("data",m=>{n+=m.toString();let o=n.split(`
|
|
3
|
+
`);n=o.pop()??"";for(let f of o)f.trim()&&U(e,t,f);}),t.on("error",m=>{p.error("IPC","Socket error:",m.message);});});return s.listen(r,()=>{if(S__default.default.platform()!=="win32")try{k__default.default.chmodSync(r,"777");}catch(t){console.error("Failed to set socket permissions:",t);}p.success("IPC",`Listening on ${r}`);}),s.on("error",t=>{p.error("IPC","Server error:",t);}),s}async function U(e,r,s){let t;try{t=JSON.parse(s);}catch{w(r,{ok:false,error:"Invalid JSON"});return}try{let n=null;switch(t.cmd){case "ping":n="pong";break;case "start":await e.start(t.config),n=`Started "${t.name}"`;break;case "stop":await e.stop(t.name),n=`Stopped "${t.name}"`;break;case "restart":await e.restart(t.name),n=`Restarted "${t.name}"`;break;case "delete":await e.delete(t.name),n=`Deleted "${t.name}"`;break;case "stats":n=await e.getStats(t.name);break;case "list":n=e.list();break;case "add-worker":await e.addWorker(t.config,t.autoStart),n=`Added "${t.config.name}"`;break;case "find-worker":n=e.getWorker(t.name);break;case "get-store":{n=Array.from(y.all()).map(([i,a])=>({name:i,status:a.status,childrenCount:a.children.length,restartCount:a.restartCount,backoffTime:a.backoffTime,isRestarting:a.isRestarting,probeFailures:a.probeFailures}));break}case "logs":let m=t.name,o=[];if(m){let i=e.getWorker(m);if(!i){r.write(JSON.stringify({ok:!1,error:`Worker "${m}" not found`})+`
|
|
4
|
+
`);return}o.push(i);}else {let i=e.list();for(let a of i){let d=e.getWorker(a);d&&o.push(d);}}if(o.length===0){r.write(JSON.stringify({ok:!1,error:"No active workers to stream logs from"})+`
|
|
5
|
+
`);return}let f=[];for(let i of o){let a=i.mp();for(let d of a.children){let b=T=>{let x=m?"":`[${i.name}] `;r.write(JSON.stringify({ok:!0,data:`${x}${T.toString()}`})+`
|
|
6
|
+
`);};d.stdout?.on("data",b),d.stderr?.on("data",b),f.push({child:d,onData:b});}}r.on("close",()=>{for(let{child:i,onData:a}of f)i.stdout?.off("data",a),i.stderr?.off("data",a);});break;default:p.error("ZPM",`Unknown command: ${t.cmd}`);}w(r,{ok:!0,data:n});}catch(n){w(r,{ok:false,error:String(n.message??n)});}}function w(e,r){e.writable&&e.write(JSON.stringify(r)+`
|
|
7
7
|
`);}exports.a=l;exports.b=I;exports.c=M;exports.d=p;exports.e=y;exports.f=J;exports.g=rr;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var chunkWPWZGJN5_cjs=require('./chunk-WPWZGJN5.cjs'),child_process=require('child_process'),F=require('http'),x=require('https'),R=require('net'),M=require('chokidar'),p=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 p__default=/*#__PURE__*/_interopDefault(p);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 m=class{cfg;name;watcher=null;isBuilding=false;constructor(t){this.cfg={mode:"fork",instances:1,...t},this.name=t.name,this.initStore();}getConfig(){return this.cfg}async start(){let t=this.mp();if(t.status==="running"||t.status==="starting"){chunkWPWZGJN5_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(),chunkWPWZGJN5_cjs.d.info(this.name,"Initializing fresh start...");try{await this.spawnAll(),this.cfg.devMode&&this.watchFiles();}catch(e){this.patch({status:"errored"}),chunkWPWZGJN5_cjs.d.error(this.name,`Start failed: ${e.message}`);}}async stop(){let t=this.mp();if(t.status==="stopping"){chunkWPWZGJN5_cjs.d.info(this.name,"Already stopping...");return}this.patch({status:"stopping",isRestarting:false}),chunkWPWZGJN5_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){chunkWPWZGJN5_cjs.d.error(this.name,`Stop timed out, forcing state reset: ${e.message||"UNKNOWN"}`);}this.patch({children:[],status:"stopped",startTime:null}),this.stopWatcher(),chunkWPWZGJN5_cjs.d.success(this.name,"Stopped.");}async restart(){let t=this.mp();t.isRestarting||(chunkWPWZGJN5_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(!p__default.default.existsSync(this.cfg.scriptPath)){chunkWPWZGJN5_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){chunkWPWZGJN5_cjs.d.error(this.name,"Failed to spawn any instances."),this.patch({status:"stopped"});return}this.patch({children:r,startTime:Date.now(),status:"running"}),chunkWPWZGJN5_cjs.d.success(this.name,`Started ${r.length} instance(s) [${t}]`);let i=setTimeout(()=>{this.mp().status==="running"&&(this.patch({backoffTime:d,restartCount:0}),chunkWPWZGJN5_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=>{chunkWPWZGJN5_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 chunkWPWZGJN5_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=>{chunkWPWZGJN5_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 chunkWPWZGJN5_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(chunkWPWZGJN5_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&&chunkWPWZGJN5_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;chunkWPWZGJN5_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}),chunkWPWZGJN5_cjs.d.warn(this.name,`Liveness probe failed (${l}/${r})`),l>=r&&(chunkWPWZGJN5_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(p__default.default.existsSync(e)&&p__default.default.statSync(e).isFile()&&(e=c__default.default.dirname(e));e!==c__default.default.parse(e).root;){if(p__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");chunkWPWZGJN5_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(chunkWPWZGJN5_cjs.d.info(this.name,f__default.default.yellow(`File ${r}: ${c__default.default.basename(i)} \u2013 restarting`)),this.cfg.reloadCommand){this.isBuilding=true,chunkWPWZGJN5_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){chunkWPWZGJN5_cjs.d.error(this.name,`Build Failed:
|
|
3
|
+
${l||h||n.message}`);return}chunkWPWZGJN5_cjs.d.success(this.name,"Build successful. Triggering restart..."),this.restart();});}else this.restart();}),this.watcher.on("error",r=>chunkWPWZGJN5_cjs.d.error(this.name,"Watcher error:",r)),this.watcher.on("ready",()=>chunkWPWZGJN5_cjs.d.info(this.name,`Watching ${t}`));}stopWatcher(){this.watcher&&(this.watcher.close(),this.watcher=null);}initStore(){chunkWPWZGJN5_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 chunkWPWZGJN5_cjs.e.get(this.name)}_patch(t){chunkWPWZGJN5_cjs.e.set(this.name,{...this.mp(),...t});}patch(t){let e=this.mp();t.status&&t.status!==e.status&&chunkWPWZGJN5_cjs.d.info(this.name,`[STATE] ${e.status} \u2794 ${t.status}${t.isRestarting?" (Restarting)":""}`),t.lastError&&chunkWPWZGJN5_cjs.d.error(this.name,`[REASON] ${t.lastError}`),chunkWPWZGJN5_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",()=>chunkWPWZGJN5_cjs.d.debug(this.name,"Connected to log collector")),r.on("error",o=>chunkWPWZGJN5_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=chunkWPWZGJN5_cjs.e.get(t.name);if(i?.status==="stopped"||i?.status==="crashed"||i?.status==="errored"){chunkWPWZGJN5_cjs.d.info("ZPM",`Resuming existing worker "${t.name}"`),await e.start();return}chunkWPWZGJN5_cjs.d.warn("ZPM",`Worker "${f__default.default.cyan(t.name)}" is ${f__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),chunkWPWZGJN5_cjs.e.delete(t),chunkWPWZGJN5_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(){chunkWPWZGJN5_cjs.d.info("PM","Stopping all workers..."),await Promise.all([...this.workers.values()].map(t=>t.stop())),chunkWPWZGJN5_cjs.d.info("PM","All workers stopped.");}getWorker(t){let e=this.workers.get(t);return e||(chunkWPWZGJN5_cjs.d.error(t,"Worker Not Found"),null)}async addWorker(t,e){let r=new m(t);this.workers.set(t.name,r),e&&await r.start();}require(t){let e=this.workers.get(t);return e||(chunkWPWZGJN5_cjs.d.error(t,"Worker Not Found"),null)}};exports.a=w;exports.b=m;exports.c=S;
|
package/dist/cli.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var
|
|
3
|
-
var n=new commander.Command;n.option("-s, --namespace <name>","Internal daemon namespace","zuz-pm");n.parseOptions(process.argv);var x=n.opts(),f=x.namespace,c=new
|
|
4
|
-
`),
|
|
5
|
-
`);for(let i of p)if(i.trim())try{let g=JSON.parse(i);g.ok&&process.stdout.write(g.data);}catch{}}),
|
|
6
|
-
Disconnected from logs.`)),process.exit();});}n.name("zpm").description("Production grade process manager for the @zuzjs ecosystem").version(P.version,"-v, --version","output the current version");n.command("start <script>").description("Start a new process").option("-n, --name <name>","Unique name for the process").option("-p, --port <port>","Port the app listens on",parseInt).option("-i, --instances <number>","Number of instances (cluster mode)",parseInt,1).option("-d, --dev","Enable development mode (auto-restart)",false).option("--reload-cmd <command>","Command to run before restarting in dev mode").option("-c, --cluster","Use cluster mode instead of fork",false).option("--ws <url>","WebSocket URL to stream logs (e.g. for ZPanel)","http://127.0.0.1:2082/_/wss/zpm").option("--save-logs","Save logs to a local file",false).option("--args <string>",'Arguments to pass to the script (e.g. "dev -p 3000")').option("--probe-type <type>","Type of probe: http, tcp, or exec").option("--probe-target <target>","URL, host:port, or command").option("--probe-interval <sec>","Seconds between probes",parseInt,30).option("--probe-threshold <count>","Failures before restart",parseInt,3).action(async(o,e)=>{try{await c.ensureDaemon();let
|
|
7
|
-
`),a.on("data",
|
|
8
|
-
`);for(let p of l)if(p.trim())try{let i=JSON.parse(p);i.ok?process.stdout.write(i.data):(console.error(`\x1B[31m${i.error}\x1B[0m`),process.exit(1));}catch{}}),a.on("error",
|
|
9
|
-
\x1B[90mDisconnected from logs.\x1B[0m`),process.exit();});}catch(e){console.error(`\x1B[31m[Error]\x1B[0m ${e.message}`);}});n.command("list").description("List all managed processes").action(async()=>{let o=await c.list();if(o.length===0){console.log("No workers registered.");return}console.log("\x1B[1mManaged Processes:\x1B[0m"),o.forEach(e=>console.log(` \u2022 ${e}`));});n.command("stats [name]").description("Show telemetry for processes").action(async o=>{let e=await c.stats(o);if(e.length===0){console.log("No stats available.");return}e.forEach(
|
|
2
|
+
'use strict';var chunkCLGIBT3W_cjs=require('./chunk-CLGIBT3W.cjs'),chunkWPWZGJN5_cjs=require('./chunk-WPWZGJN5.cjs'),commander=require('commander'),w=require('fs'),h=require('net'),m=require('path'),url=require('url'),s=require('picocolors');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var w__default=/*#__PURE__*/_interopDefault(w);var h__default=/*#__PURE__*/_interopDefault(h);var m__default=/*#__PURE__*/_interopDefault(m);var s__default=/*#__PURE__*/_interopDefault(s);/* ZuzJS Process Manager */
|
|
3
|
+
var n=new commander.Command;n.option("-s, --namespace <name>","Internal daemon namespace","zuz-pm");n.parseOptions(process.argv);var x=n.opts(),f=x.namespace,c=new chunkCLGIBT3W_cjs.a(f),v=m__default.default.dirname(url.fileURLToPath(chunkWPWZGJN5_cjs.a)),$=m__default.default.resolve(v,"../package.json"),P=JSON.parse(w__default.default.readFileSync($,"utf8"));async function k(o,e){if(!await c.isDaemonRunning())return;let a=e?`"${e}"`:"all workers";console.log(s__default.default.cyan("[ZPM]"),s__default.default.gray(`Attaching stream for ${a}...`));let t=h__default.default.createConnection(chunkWPWZGJN5_cjs.f(o));t.write(JSON.stringify({cmd:"logs",name:e})+`
|
|
4
|
+
`),t.on("data",l=>{let p=l.toString().split(`
|
|
5
|
+
`);for(let i of p)if(i.trim())try{let g=JSON.parse(i);g.ok&&process.stdout.write(g.data);}catch{}}),t.on("error",l=>{console.error(s__default.default.red(`[IPC Error] ${l.message}`));}),process.on("SIGINT",()=>{t.destroy(),console.log(s__default.default.gray(`
|
|
6
|
+
Disconnected from logs.`)),process.exit();});}n.name("zpm").description("Production grade process manager for the @zuzjs ecosystem").version(P.version,"-v, --version","output the current version");n.command("start <script>").description("Start a new process").option("-n, --name <name>","Unique name for the process").option("-p, --port <port>","Port the app listens on",parseInt).option("-i, --instances <number>","Number of instances (cluster mode)",parseInt,1).option("-d, --dev","Enable development mode (auto-restart)",false).option("--reload-cmd <command>","Command to run before restarting in dev mode").option("-c, --cluster","Use cluster mode instead of fork",false).option("--ws <url>","WebSocket URL to stream logs (e.g. for ZPanel)","http://127.0.0.1:2082/_/wss/zpm").option("--save-logs","Save logs to a local file",false).option("--args <string>",'Arguments to pass to the script (e.g. "dev -p 3000")').option("--probe-type <type>","Type of probe: http, tcp, or exec").option("--probe-target <target>","URL, host:port, or command").option("--probe-interval <sec>","Seconds between probes",parseInt,30).option("--probe-threshold <count>","Failures before restart",parseInt,3).action(async(o,e)=>{try{await c.ensureDaemon();let r=m__default.default.resolve(process.cwd(),o),a=e.name??m__default.default.basename(o),t=await c.start({name:e.name??m__default.default.basename(o),scriptPath:r,port:e.port,instances:e.instances,devMode:e.dev,mode:e.cluster?"cluster":"fork",args:e.args?e.args.split(" "):[],reloadCommand:e.reloadCmd,probe:e.probeTarget?{type:e.probeType,target:e.probeTarget||(e.probeType==="http"?"http://localhost:3000":"localhost:3000"),intervalSeconds:e.probeInterval,failureThreshold:e.probeThreshold,timeoutSeconds:5}:void 0,logs:{wsUrl:e.ws,saveToFile:e.saveLogs}});console.log(s__default.default.cyan("[ZPM]"),t),e.dev?await k(f,a):process.exit(0);}catch(r){console.log(s__default.default.cyan("[ZPM]"),s__default.default.red("[ERROR]"),r.message);}});n.command("logs [name]").description("Stream real-time logs (omit name for all logs)").action(async o=>{try{if(!await c.isDaemonRunning())throw new Error("Daemon is not running.");let r=o?`"${o}"`:"all workers";console.log(s__default.default.cyan("[ZPM]"),`Streaming logs for "${s__default.default.green(r)}" (Ctrl+C to stop)`);let a=h__default.default.createConnection(chunkWPWZGJN5_cjs.f(f));a.write(JSON.stringify({cmd:"logs",name:o})+`
|
|
7
|
+
`),a.on("data",t=>{let l=t.toString().split(`
|
|
8
|
+
`);for(let p of l)if(p.trim())try{let i=JSON.parse(p);i.ok?process.stdout.write(i.data):(console.error(`\x1B[31m${i.error}\x1B[0m`),process.exit(1));}catch{}}),a.on("error",t=>{console.error(`\x1B[31m[IPC Error]\x1B[0m ${t.message}`),process.exit(1);}),process.on("SIGINT",()=>{a.destroy(),console.log(`
|
|
9
|
+
\x1B[90mDisconnected from logs.\x1B[0m`),process.exit();});}catch(e){console.error(`\x1B[31m[Error]\x1B[0m ${e.message}`);}});n.command("list").description("List all managed processes").action(async()=>{let o=await c.list();if(o.length===0){console.log("No workers registered.");return}console.log("\x1B[1mManaged Processes:\x1B[0m"),o.forEach(e=>console.log(` \u2022 ${e}`));});n.command("stats [name]").description("Show telemetry for processes").action(async o=>{let e=await c.stats(o);if(e.length===0){console.log("No stats available.");return}e.forEach(r=>{let a=r.uptime?`${Math.round(r.uptime/1e3)}s`:"0s",t=r.status==="running"?"\x1B[32m":"\x1B[31m";console.log(`${t}[${r.status.toUpperCase()}]\x1B[0m \x1B[1m${r.name.padEnd(15)}\x1B[0m PID: ${String(r.pid??"N/A").padEnd(6)} CPU: ${String(r.cpu??0).padStart(3)}% MEM: ${Math.round((r.memoryRss??0)/1024/1024)}MB Uptime: ${a}`);});});["stop","restart","delete"].forEach(o=>{n.command(`${o} <name>`).description(`${o.charAt(0).toUpperCase()+o.slice(1)} a process`).action(async e=>{try{let r=await c[o](e);console.log(`\x1B[32m[ZPM]\x1B[0m ${r}`);}catch(r){console.error(`\x1B[31m[Error]\x1B[0m ${r.message}`);}});});n.command("kill-daemon").description("Stop the background ZPM daemon").action(async()=>{await c.killDaemon(),console.log("\x1B[33mDaemon killed.\x1B[0m");});n.command("store").description("Show raw internal store state for debugging").action(async()=>{let o=await c.getStore();if(o){let e=o;if(e.length===0){console.log(s__default.default.yellow("Store is empty."));return}console.log(s__default.default.magenta(`
|
|
10
10
|
--- Internal Process Store ---`)),console.table(e),console.log(s__default.default.gray(`Total Managed Processes: ${e.length}
|
|
11
11
|
`));}else console.log("StoreError",o);});n.parse(process.argv);
|
package/dist/cli.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a}from'./chunk-
|
|
3
|
-
`),
|
|
4
|
-
`);for(let i of p)if(i.trim())try{let g=JSON.parse(i);g.ok&&process.stdout.write(g.data);}catch{}}),
|
|
5
|
-
Disconnected from logs.`)),process.exit();});}n.name("zpm").description("Production grade process manager for the @zuzjs ecosystem").version($.version,"-v, --version","output the current version");n.command("start <script>").description("Start a new process").option("-n, --name <name>","Unique name for the process").option("-p, --port <port>","Port the app listens on",parseInt).option("-i, --instances <number>","Number of instances (cluster mode)",parseInt,1).option("-d, --dev","Enable development mode (auto-restart)",false).option("--reload-cmd <command>","Command to run before restarting in dev mode").option("-c, --cluster","Use cluster mode instead of fork",false).option("--ws <url>","WebSocket URL to stream logs (e.g. for ZPanel)","http://127.0.0.1:2082/_/wss/zpm").option("--save-logs","Save logs to a local file",false).option("--args <string>",'Arguments to pass to the script (e.g. "dev -p 3000")').option("--probe-type <type>","Type of probe: http, tcp, or exec").option("--probe-target <target>","URL, host:port, or command").option("--probe-interval <sec>","Seconds between probes",parseInt,30).option("--probe-threshold <count>","Failures before restart",parseInt,3).action(async(o,e)=>{try{await c.ensureDaemon();let
|
|
6
|
-
`),a.on("data",
|
|
7
|
-
`);for(let p of l)if(p.trim())try{let i=JSON.parse(p);i.ok?process.stdout.write(i.data):(console.error(`\x1B[31m${i.error}\x1B[0m`),process.exit(1));}catch{}}),a.on("error",
|
|
8
|
-
\x1B[90mDisconnected from logs.\x1B[0m`),process.exit();});}catch(e){console.error(`\x1B[31m[Error]\x1B[0m ${e.message}`);}});n.command("list").description("List all managed processes").action(async()=>{let o=await c.list();if(o.length===0){console.log("No workers registered.");return}console.log("\x1B[1mManaged Processes:\x1B[0m"),o.forEach(e=>console.log(` \u2022 ${e}`));});n.command("stats [name]").description("Show telemetry for processes").action(async o=>{let e=await c.stats(o);if(e.length===0){console.log("No stats available.");return}e.forEach(
|
|
2
|
+
import {a}from'./chunk-IYTWXZHG.js';import {f as f$1}from'./chunk-FXEDN7ZZ.js';import {Command}from'commander';import y from'fs';import b from'net';import m from'path';import {fileURLToPath}from'url';import s from'picocolors';var n=new Command;n.option("-s, --namespace <name>","Internal daemon namespace","zuz-pm");n.parseOptions(process.argv);var S=n.opts(),f=S.namespace,c=new a(f),x=m.dirname(fileURLToPath(import.meta.url)),v=m.resolve(x,"../package.json"),$=JSON.parse(y.readFileSync(v,"utf8"));async function P(o,e){if(!await c.isDaemonRunning())return;let a=e?`"${e}"`:"all workers";console.log(s.cyan("[ZPM]"),s.gray(`Attaching stream for ${a}...`));let t=b.createConnection(f$1(o));t.write(JSON.stringify({cmd:"logs",name:e})+`
|
|
3
|
+
`),t.on("data",l=>{let p=l.toString().split(`
|
|
4
|
+
`);for(let i of p)if(i.trim())try{let g=JSON.parse(i);g.ok&&process.stdout.write(g.data);}catch{}}),t.on("error",l=>{console.error(s.red(`[IPC Error] ${l.message}`));}),process.on("SIGINT",()=>{t.destroy(),console.log(s.gray(`
|
|
5
|
+
Disconnected from logs.`)),process.exit();});}n.name("zpm").description("Production grade process manager for the @zuzjs ecosystem").version($.version,"-v, --version","output the current version");n.command("start <script>").description("Start a new process").option("-n, --name <name>","Unique name for the process").option("-p, --port <port>","Port the app listens on",parseInt).option("-i, --instances <number>","Number of instances (cluster mode)",parseInt,1).option("-d, --dev","Enable development mode (auto-restart)",false).option("--reload-cmd <command>","Command to run before restarting in dev mode").option("-c, --cluster","Use cluster mode instead of fork",false).option("--ws <url>","WebSocket URL to stream logs (e.g. for ZPanel)","http://127.0.0.1:2082/_/wss/zpm").option("--save-logs","Save logs to a local file",false).option("--args <string>",'Arguments to pass to the script (e.g. "dev -p 3000")').option("--probe-type <type>","Type of probe: http, tcp, or exec").option("--probe-target <target>","URL, host:port, or command").option("--probe-interval <sec>","Seconds between probes",parseInt,30).option("--probe-threshold <count>","Failures before restart",parseInt,3).action(async(o,e)=>{try{await c.ensureDaemon();let r=m.resolve(process.cwd(),o),a=e.name??m.basename(o),t=await c.start({name:e.name??m.basename(o),scriptPath:r,port:e.port,instances:e.instances,devMode:e.dev,mode:e.cluster?"cluster":"fork",args:e.args?e.args.split(" "):[],reloadCommand:e.reloadCmd,probe:e.probeTarget?{type:e.probeType,target:e.probeTarget||(e.probeType==="http"?"http://localhost:3000":"localhost:3000"),intervalSeconds:e.probeInterval,failureThreshold:e.probeThreshold,timeoutSeconds:5}:void 0,logs:{wsUrl:e.ws,saveToFile:e.saveLogs}});console.log(s.cyan("[ZPM]"),t),e.dev?await P(f,a):process.exit(0);}catch(r){console.log(s.cyan("[ZPM]"),s.red("[ERROR]"),r.message);}});n.command("logs [name]").description("Stream real-time logs (omit name for all logs)").action(async o=>{try{if(!await c.isDaemonRunning())throw new Error("Daemon is not running.");let r=o?`"${o}"`:"all workers";console.log(s.cyan("[ZPM]"),`Streaming logs for "${s.green(r)}" (Ctrl+C to stop)`);let a=b.createConnection(f$1(f));a.write(JSON.stringify({cmd:"logs",name:o})+`
|
|
6
|
+
`),a.on("data",t=>{let l=t.toString().split(`
|
|
7
|
+
`);for(let p of l)if(p.trim())try{let i=JSON.parse(p);i.ok?process.stdout.write(i.data):(console.error(`\x1B[31m${i.error}\x1B[0m`),process.exit(1));}catch{}}),a.on("error",t=>{console.error(`\x1B[31m[IPC Error]\x1B[0m ${t.message}`),process.exit(1);}),process.on("SIGINT",()=>{a.destroy(),console.log(`
|
|
8
|
+
\x1B[90mDisconnected from logs.\x1B[0m`),process.exit();});}catch(e){console.error(`\x1B[31m[Error]\x1B[0m ${e.message}`);}});n.command("list").description("List all managed processes").action(async()=>{let o=await c.list();if(o.length===0){console.log("No workers registered.");return}console.log("\x1B[1mManaged Processes:\x1B[0m"),o.forEach(e=>console.log(` \u2022 ${e}`));});n.command("stats [name]").description("Show telemetry for processes").action(async o=>{let e=await c.stats(o);if(e.length===0){console.log("No stats available.");return}e.forEach(r=>{let a=r.uptime?`${Math.round(r.uptime/1e3)}s`:"0s",t=r.status==="running"?"\x1B[32m":"\x1B[31m";console.log(`${t}[${r.status.toUpperCase()}]\x1B[0m \x1B[1m${r.name.padEnd(15)}\x1B[0m PID: ${String(r.pid??"N/A").padEnd(6)} CPU: ${String(r.cpu??0).padStart(3)}% MEM: ${Math.round((r.memoryRss??0)/1024/1024)}MB Uptime: ${a}`);});});["stop","restart","delete"].forEach(o=>{n.command(`${o} <name>`).description(`${o.charAt(0).toUpperCase()+o.slice(1)} a process`).action(async e=>{try{let r=await c[o](e);console.log(`\x1B[32m[ZPM]\x1B[0m ${r}`);}catch(r){console.error(`\x1B[31m[Error]\x1B[0m ${r.message}`);}});});n.command("kill-daemon").description("Stop the background ZPM daemon").action(async()=>{await c.killDaemon(),console.log("\x1B[33mDaemon killed.\x1B[0m");});n.command("store").description("Show raw internal store state for debugging").action(async()=>{let o=await c.getStore();if(o){let e=o;if(e.length===0){console.log(s.yellow("Store is empty."));return}console.log(s.magenta(`
|
|
9
9
|
--- Internal Process Store ---`)),console.table(e),console.log(s.gray(`Total Managed Processes: ${e.length}
|
|
10
10
|
`));}else console.log("StoreError",o);});n.parse(process.argv);
|
package/dist/daemon.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var
|
|
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(){
|
|
1
|
+
'use strict';var chunkYGHAA45S_cjs=require('./chunk-YGHAA45S.cjs'),chunkWPWZGJN5_cjs=require('./chunk-WPWZGJN5.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(){chunkWPWZGJN5_cjs.d.success("daemon",`Booting ZPM daemon (PID ${process.pid})`),d();let o=new chunkYGHAA45S_cjs.c,s=chunkWPWZGJN5_cjs.g(o);async function t(e){chunkWPWZGJN5_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=>chunkWPWZGJN5_cjs.d.error("daemon","Uncaught exception:",e)),process.on("unhandledRejection",e=>chunkWPWZGJN5_cjs.d.error("daemon","Unhandled rejection:",e)),chunkWPWZGJN5_cjs.d.success("daemon","Ready \u2013 waiting for IPC commands.");}S().catch(o=>{chunkWPWZGJN5_cjs.d.error("daemon","Fatal startup error:",o),process.exit(1);});
|
package/dist/daemon.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {c}from'./chunk-
|
|
1
|
+
import {c}from'./chunk-AZIXEAKE.js';import {d as d$1,g}from'./chunk-FXEDN7ZZ.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
|
|
1
|
+
'use strict';var chunkCLGIBT3W_cjs=require('./chunk-CLGIBT3W.cjs'),chunkYGHAA45S_cjs=require('./chunk-YGHAA45S.cjs'),chunkWPWZGJN5_cjs=require('./chunk-WPWZGJN5.cjs');Object.defineProperty(exports,"ZPMClient",{enumerable:true,get:function(){return chunkCLGIBT3W_cjs.a}});Object.defineProperty(exports,"zpm",{enumerable:true,get:function(){return chunkCLGIBT3W_cjs.b}});Object.defineProperty(exports,"ProcessManager",{enumerable:true,get:function(){return chunkYGHAA45S_cjs.c}});Object.defineProperty(exports,"Worker",{enumerable:true,get:function(){return chunkYGHAA45S_cjs.b}});Object.defineProperty(exports,"runProbe",{enumerable:true,get:function(){return chunkYGHAA45S_cjs.a}});Object.defineProperty(exports,"WorkerMode",{enumerable:true,get:function(){return chunkWPWZGJN5_cjs.b}});Object.defineProperty(exports,"WorkerStatus",{enumerable:true,get:function(){return chunkWPWZGJN5_cjs.c}});Object.defineProperty(exports,"getSocketPath",{enumerable:true,get:function(){return chunkWPWZGJN5_cjs.f}});Object.defineProperty(exports,"logger",{enumerable:true,get:function(){return chunkWPWZGJN5_cjs.d}});Object.defineProperty(exports,"processStore",{enumerable:true,get:function(){return chunkWPWZGJN5_cjs.e}});
|
package/dist/index.d.cts
CHANGED
|
@@ -94,6 +94,13 @@ type IPCCommand = {
|
|
|
94
94
|
cmd: "list";
|
|
95
95
|
} | {
|
|
96
96
|
cmd: "ping";
|
|
97
|
+
} | {
|
|
98
|
+
cmd: "find-worker";
|
|
99
|
+
name: string;
|
|
100
|
+
} | {
|
|
101
|
+
cmd: "add-worker";
|
|
102
|
+
autoStart: boolean;
|
|
103
|
+
config: WorkerConfig;
|
|
97
104
|
} | {
|
|
98
105
|
cmd: "logs";
|
|
99
106
|
name?: string;
|
|
@@ -107,6 +114,7 @@ type IPCResponse = {
|
|
|
107
114
|
ok: false;
|
|
108
115
|
error: string;
|
|
109
116
|
};
|
|
117
|
+
type StoreInfo = ManagedProcess[] | null;
|
|
110
118
|
interface ManagedProcess {
|
|
111
119
|
config: WorkerConfig;
|
|
112
120
|
children: ChildProcess[];
|
|
@@ -135,6 +143,7 @@ declare class Worker {
|
|
|
135
143
|
private watcher;
|
|
136
144
|
private isBuilding;
|
|
137
145
|
constructor(config: WorkerConfig);
|
|
146
|
+
getConfig(): WorkerConfig;
|
|
138
147
|
start(): Promise<void>;
|
|
139
148
|
stop(): Promise<void>;
|
|
140
149
|
restart(): Promise<void>;
|
|
@@ -173,6 +182,7 @@ declare class ProcessManager {
|
|
|
173
182
|
list(): string[];
|
|
174
183
|
stopAll(): Promise<void>;
|
|
175
184
|
getWorker(name: string): Worker | null;
|
|
185
|
+
addWorker(config: WorkerConfig, autoStart: boolean): Promise<void>;
|
|
176
186
|
private require;
|
|
177
187
|
}
|
|
178
188
|
|
|
@@ -202,11 +212,15 @@ declare class ZPMClient {
|
|
|
202
212
|
ensureDaemon(): Promise<void>;
|
|
203
213
|
/** Kill the daemon by PID */
|
|
204
214
|
killDaemon(): Promise<void>;
|
|
205
|
-
getStore(): Promise<
|
|
215
|
+
getStore(): Promise<StoreInfo>;
|
|
216
|
+
getProcessByName(processName: string): Promise<ManagedProcess | undefined>;
|
|
206
217
|
start(config: WorkerConfig): Promise<string>;
|
|
207
218
|
stop(name: string): Promise<string>;
|
|
208
219
|
restart(name: string): Promise<string>;
|
|
209
220
|
delete(name: string): Promise<string>;
|
|
221
|
+
/** Replace worker with new name */
|
|
222
|
+
replaceWorker(oldName: string, newName: string, autoStart: boolean): Promise<unknown>;
|
|
223
|
+
getWorkerByName(workerName: string): Promise<Worker | null>;
|
|
210
224
|
stats(name?: string): Promise<WorkerStats[]>;
|
|
211
225
|
list(): Promise<string[]>;
|
|
212
226
|
private waitForDaemon;
|
package/dist/index.d.ts
CHANGED
|
@@ -94,6 +94,13 @@ type IPCCommand = {
|
|
|
94
94
|
cmd: "list";
|
|
95
95
|
} | {
|
|
96
96
|
cmd: "ping";
|
|
97
|
+
} | {
|
|
98
|
+
cmd: "find-worker";
|
|
99
|
+
name: string;
|
|
100
|
+
} | {
|
|
101
|
+
cmd: "add-worker";
|
|
102
|
+
autoStart: boolean;
|
|
103
|
+
config: WorkerConfig;
|
|
97
104
|
} | {
|
|
98
105
|
cmd: "logs";
|
|
99
106
|
name?: string;
|
|
@@ -107,6 +114,7 @@ type IPCResponse = {
|
|
|
107
114
|
ok: false;
|
|
108
115
|
error: string;
|
|
109
116
|
};
|
|
117
|
+
type StoreInfo = ManagedProcess[] | null;
|
|
110
118
|
interface ManagedProcess {
|
|
111
119
|
config: WorkerConfig;
|
|
112
120
|
children: ChildProcess[];
|
|
@@ -135,6 +143,7 @@ declare class Worker {
|
|
|
135
143
|
private watcher;
|
|
136
144
|
private isBuilding;
|
|
137
145
|
constructor(config: WorkerConfig);
|
|
146
|
+
getConfig(): WorkerConfig;
|
|
138
147
|
start(): Promise<void>;
|
|
139
148
|
stop(): Promise<void>;
|
|
140
149
|
restart(): Promise<void>;
|
|
@@ -173,6 +182,7 @@ declare class ProcessManager {
|
|
|
173
182
|
list(): string[];
|
|
174
183
|
stopAll(): Promise<void>;
|
|
175
184
|
getWorker(name: string): Worker | null;
|
|
185
|
+
addWorker(config: WorkerConfig, autoStart: boolean): Promise<void>;
|
|
176
186
|
private require;
|
|
177
187
|
}
|
|
178
188
|
|
|
@@ -202,11 +212,15 @@ declare class ZPMClient {
|
|
|
202
212
|
ensureDaemon(): Promise<void>;
|
|
203
213
|
/** Kill the daemon by PID */
|
|
204
214
|
killDaemon(): Promise<void>;
|
|
205
|
-
getStore(): Promise<
|
|
215
|
+
getStore(): Promise<StoreInfo>;
|
|
216
|
+
getProcessByName(processName: string): Promise<ManagedProcess | undefined>;
|
|
206
217
|
start(config: WorkerConfig): Promise<string>;
|
|
207
218
|
stop(name: string): Promise<string>;
|
|
208
219
|
restart(name: string): Promise<string>;
|
|
209
220
|
delete(name: string): Promise<string>;
|
|
221
|
+
/** Replace worker with new name */
|
|
222
|
+
replaceWorker(oldName: string, newName: string, autoStart: boolean): Promise<unknown>;
|
|
223
|
+
getWorkerByName(workerName: string): Promise<Worker | null>;
|
|
210
224
|
stats(name?: string): Promise<WorkerStats[]>;
|
|
211
225
|
list(): Promise<string[]>;
|
|
212
226
|
private waitForDaemon;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as ZPMClient,b as zpm}from'./chunk-
|
|
1
|
+
export{a as ZPMClient,b as zpm}from'./chunk-IYTWXZHG.js';export{c as ProcessManager,b as Worker,a as runProbe}from'./chunk-AZIXEAKE.js';export{b as WorkerMode,c as WorkerStatus,f as getSocketPath,d as logger,e as processStore}from'./chunk-FXEDN7ZZ.js';
|
package/package.json
CHANGED
package/dist/chunk-BDZZ2TSJ.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
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};
|
package/dist/chunk-C2XMYYVX.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import {a,d,f as f$1}from'./chunk-USJACDTS.js';import {spawn}from'child_process';import p from'fs';import y from'net';import w from'os';import f from'path';function s(d,n="zuz-pm"){return new Promise((t,e)=>{let r=y.createConnection(f$1(n)),o="";r.on("connect",()=>{r.write(JSON.stringify(d)+`
|
|
2
|
-
`);}),r.on("data",i=>{o+=i.toString();let m=o.split(`
|
|
3
|
-
`);o=m.pop()??"";for(let l of m)if(l.trim())try{let a=JSON.parse(l);r.destroy(),a.ok?t(a.data):e(new Error(a.error));}catch(a){r.destroy(),e(a);}}),r.on("error",i=>e(i)),r.setTimeout(1e4,()=>{r.destroy(),e(new Error("IPC timeout"));});})}var u=class{daemonScript;namespace;constructor(n){this.namespace=n?.namespace??"zuz-pm",this.daemonScript=n?.daemonScript??f.join(a,"daemon.js");}async isDaemonRunning(){try{return d.info("[ZPM]","Daemon is Running :?"),await s({cmd:"ping"},this.namespace),!0}catch{return d.info("[ZPM]","Daemon is not running."),false}}async ensureDaemon(){if(await this.isDaemonRunning())return;d.info("Starting ZPM daemon...");let t=process.env.NODE_ENV!=="production";spawn(process.execPath,[this.daemonScript],{detached:true,stdio:t?"inherit":"ignore"}).unref(),await this.waitForDaemon(8e3);}async killDaemon(){let n=f.join(w.tmpdir(),"zuz-pm.pid");if(!p.existsSync(n))throw new Error("Daemon PID file not found \u2013 is the daemon running?");let t=Number(p.readFileSync(n,"utf8").trim());try{process.kill(t,"SIGTERM"),console.log(`[ZPM] Sent SIGTERM to daemon (PID ${t})`);}catch(e){throw new Error(`Failed to kill daemon: ${e.message}`)}finally{p.unlinkSync(n);}}async getStore(){return s({cmd:"get-store"},this.namespace)}async start(n){return s({cmd:"start",name:n.name,config:n},this.namespace)}async stop(n){return s({cmd:"stop",name:n},this.namespace)}async restart(n){return s({cmd:"restart",name:n},this.namespace)}async delete(n){return s({cmd:"delete",name:n},this.namespace)}async stats(n){return s({cmd:"stats",name:n},this.namespace)}async list(){return s({cmd:"list"},this.namespace)}waitForDaemon(n){let t=Date.now(),e=200;return new Promise((r,o)=>{let i=()=>{this.isDaemonRunning().then(m=>{if(m)return r();if(Date.now()-t>n)return o(new Error("Daemon did not start in time"));setTimeout(i,e);});};setTimeout(i,e);})}},v=new u;export{u as a,v as b};
|
package/dist/chunk-JWYNDWX7.cjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkD4SST7VW_cjs=require('./chunk-D4SST7VW.cjs'),child_process=require('child_process'),p=require('fs'),h=require('net'),y=require('os'),P=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var p__default=/*#__PURE__*/_interopDefault(p);var h__default=/*#__PURE__*/_interopDefault(h);var y__default=/*#__PURE__*/_interopDefault(y);var P__default=/*#__PURE__*/_interopDefault(P);/* ZuzJS Process Manager */
|
|
2
|
-
function s(d,n="zuz-pm"){return new Promise((t,e)=>{let r=h__default.default.createConnection(chunkD4SST7VW_cjs.f(n)),o="";r.on("connect",()=>{r.write(JSON.stringify(d)+`
|
|
3
|
-
`);}),r.on("data",i=>{o+=i.toString();let m=o.split(`
|
|
4
|
-
`);o=m.pop()??"";for(let l of m)if(l.trim())try{let a=JSON.parse(l);r.destroy(),a.ok?t(a.data):e(new Error(a.error));}catch(a){r.destroy(),e(a);}}),r.on("error",i=>e(i)),r.setTimeout(1e4,()=>{r.destroy(),e(new Error("IPC timeout"));});})}var u=class{daemonScript;namespace;constructor(n){this.namespace=n?.namespace??"zuz-pm",this.daemonScript=n?.daemonScript??P__default.default.join(__dirname,"daemon.js");}async isDaemonRunning(){try{return chunkD4SST7VW_cjs.d.info("[ZPM]","Daemon is Running :?"),await s({cmd:"ping"},this.namespace),!0}catch{return chunkD4SST7VW_cjs.d.info("[ZPM]","Daemon is not running."),false}}async ensureDaemon(){if(await this.isDaemonRunning())return;chunkD4SST7VW_cjs.d.info("Starting ZPM daemon...");let t=process.env.NODE_ENV!=="production";child_process.spawn(process.execPath,[this.daemonScript],{detached:true,stdio:t?"inherit":"ignore"}).unref(),await this.waitForDaemon(8e3);}async killDaemon(){let n=P__default.default.join(y__default.default.tmpdir(),"zuz-pm.pid");if(!p__default.default.existsSync(n))throw new Error("Daemon PID file not found \u2013 is the daemon running?");let t=Number(p__default.default.readFileSync(n,"utf8").trim());try{process.kill(t,"SIGTERM"),console.log(`[ZPM] Sent SIGTERM to daemon (PID ${t})`);}catch(e){throw new Error(`Failed to kill daemon: ${e.message}`)}finally{p__default.default.unlinkSync(n);}}async getStore(){return s({cmd:"get-store"},this.namespace)}async start(n){return s({cmd:"start",name:n.name,config:n},this.namespace)}async stop(n){return s({cmd:"stop",name:n},this.namespace)}async restart(n){return s({cmd:"restart",name:n},this.namespace)}async delete(n){return s({cmd:"delete",name:n},this.namespace)}async stats(n){return s({cmd:"stats",name:n},this.namespace)}async list(){return s({cmd:"list"},this.namespace)}waitForDaemon(n){let t=Date.now(),e=200;return new Promise((r,o)=>{let i=()=>{this.isDaemonRunning().then(m=>{if(m)return r();if(Date.now()-t>n)return o(new Error("Daemon did not start in time"));setTimeout(i,e);});};setTimeout(i,e);})}},E=new u;exports.a=u;exports.b=E;
|
package/dist/chunk-KBAMWOIM.cjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
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/chunk-USJACDTS.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import C from'path';import {fileURLToPath}from'url';import y from'os';import g from'picocolors';import c from'winston';import D from'events';import w from'fs';import O from'net';var I=()=>fileURLToPath(import.meta.url),N=()=>C.dirname(I()),u=N();var R=(s=>(s.Fork="fork",s.Cluster="cluster",s))(R||{}),L=(o=>(o.Stopped="stopped",o.Starting="starting",o.Running="running",o.Stopping="stopping",o.Crashed="crashed",o.Errored="errored",o))(L||{});var F=C.join(y.homedir(),".zpm","logs"),J=c.format.combine(c.format.timestamp({format:"YYYY/MM/DD HH:mm:ss"}),c.format.splat(),c.format.printf(({timestamp:e,level:r,message:s,tag:t})=>{let n=g.gray(`[${e}]`),m=g.bold(`[ZPM/${(t||"SYS").toUpperCase()}]`);return `${n} [${r=="info"?g.cyan(r):r=="warn"?g.yellow(r):r=="error"?g.red(r):r=="success"?g.green(r):r=="debug"?g.gray(r):"debug"}] ${m} \u2192 ${s}`})),d=c.createLogger({levels:{error:0,warn:1,info:2,success:2,debug:3},transports:[new c.transports.Console({level:"debug",format:J}),new c.transports.File({filename:C.join(F,"daemon.log"),format:c.format.combine(c.format.timestamp(),c.format.json())})]}),l={info:(e,...r)=>d.info(r.join(" "),{tag:e}),warn:(e,...r)=>d.warn(r.join(" "),{tag:e}),error:(e,...r)=>d.error(r.join(" "),{tag:e}),debug:(e,...r)=>d.debug(r.join(" "),{tag:e}),success:(e,...r)=>d.log("success",r.join(" "),{tag:e})};var k=class extends D{map=new Map;set(r,s){this.map.set(r,s),this.emit("change",r,s);}get(r){return this.map.get(r)}has(r){return this.map.has(r)}delete(r){this.map.delete(r),this.emit("delete",r);}all(){return new Map(this.map)}onchange(r){return this.on("change",r)}offchange(r){return this.off("change",r)}},P=new k;function E(e="zuz-pm"){return y.platform()==="win32"?C.join("\\\\.\\pipe",e):C.join(y.tmpdir(),`${e}.sock`)}function ar(e){let r=E();w.existsSync(r)&&w.unlinkSync(r);let s=O.createServer(t=>{let n="";t.on("data",m=>{n+=m.toString();let o=n.split(`
|
|
2
|
-
`);n=o.pop()??"";for(let p of o)p.trim()&&W(e,t,p);}),t.on("error",m=>{l.error("IPC","Socket error:",m.message);});});return s.listen(r,()=>{if(y.platform()!=="win32")try{w.chmodSync(r,"777");}catch(t){console.error("Failed to set socket permissions:",t);}l.success("IPC",`Listening on ${r}`);}),s.on("error",t=>{l.error("IPC","Server error:",t);}),s}async function W(e,r,s){let t;try{t=JSON.parse(s);}catch{S(r,{ok:false,error:"Invalid JSON"});return}try{let n=null;switch(t.cmd){case "ping":n="pong";break;case "start":await e.start(t.config),n=`Started "${t.name}"`;break;case "stop":await e.stop(t.name),n=`Stopped "${t.name}"`;break;case "restart":await e.restart(t.name),n=`Restarted "${t.name}"`;break;case "delete":await e.delete(t.name),n=`Deleted "${t.name}"`;break;case "stats":n=await e.getStats(t.name);break;case "list":n=e.list();break;case "get-store":{n=Array.from(P.all()).map(([i,a])=>({name:i,status:a.status,childrenCount:a.children.length,restartCount:a.restartCount,backoffTime:a.backoffTime,isRestarting:a.isRestarting,probeFailures:a.probeFailures}));break}case "logs":let m=t.name,o=[];if(m){let i=e.getWorker(m);if(!i){r.write(JSON.stringify({ok:!1,error:`Worker "${m}" not found`})+`
|
|
3
|
-
`);return}o.push(i);}else {let i=e.list();for(let a of i){let f=e.getWorker(a);f&&o.push(f);}}if(o.length===0){r.write(JSON.stringify({ok:!1,error:"No active workers to stream logs from"})+`
|
|
4
|
-
`);return}let p=[];for(let i of o){let a=i.mp();for(let f of a.children){let b=x=>{let $=m?"":`[${i.name}] `;r.write(JSON.stringify({ok:!0,data:`${$}${x.toString()}`})+`
|
|
5
|
-
`);};f.stdout?.on("data",b),f.stderr?.on("data",b),p.push({child:f,onData:b});}}r.on("close",()=>{for(let{child:i,onData:a}of p)i.stdout?.off("data",a),i.stderr?.off("data",a);});break;default:l.error("ZPM",`Unknown command: ${t.cmd}`);}S(r,{ok:!0,data:n});}catch(n){S(r,{ok:false,error:String(n.message??n)});}}function S(e,r){e.writable&&e.write(JSON.stringify(r)+`
|
|
6
|
-
`);}export{u as a,R as b,L as c,l as d,P as e,E as f,ar as g};
|