var T=Object.defineProperty;var k=(o,e)=>T(o,"name",{value:e,configurable:!0});import{createRequire as F}from"node:module";import{p as c,O as A,C as H,Q as U,U as L,W as O,Y as P}from"./bin.js";import{c as D,r as z,s as C,S as G,a as $,b,d as q,p as B,i as M,e as V}from"../packem_shared/lifecycle-DvVTL8nx.js";const _=F(import.meta.url),m=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,I=k(o=>{if(typeof m<"u"&&m.versions&&m.versions.node){const[e,r]=m.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return m.getBuiltinModule(o)}return _(o)},"__cjs_getBuiltinModule"),{stat:y,open:R,watch:N}=I("node:fs/promises");var W=Object.defineProperty,g=k((o,e)=>W(o,"name",{value:e,configurable:!0}),"f");const h=g(async o=>{const e=o?.plugins;if(!e||e.length===0)return;const r=D();return await z(r,e),{callHook:g(async(d,...s)=>{try{await r.callHook(d,...s)}catch(t){const n=t instanceof Error?t.message:String(t);c.warn(`Plugin error in ${d}: ${n}`)}},"callHook")}},"loadServiceHooks"),J=g(o=>{const e=o.trim(),r=e.lastIndexOf(":");if(!(r<=0||r===e.length-1))return{project:e.slice(0,r),target:e.slice(r+1)}},"splitTargetId"),j=g(async(o,e,r)=>{const d=J(r);if(!d){c.error(`Invalid target id "${r}". Expected "<project>:<target>", e.g. "@my/api:db".`);return}const s=await A(o),{projectOptions:t,workspace:n}=H(o,e,s),i=n.projects[d.project],a=t.get(d.project)?.[d.target];if(!i||!a){c.error(`Target "${r}" not found in this workspace.`);return}const p=a.options?.service;if(!p){c.error(`Target "${r}" is not a service. Add an \`options.service\` block to make it eligible for \`vis service\`.`);return}if(!a.command){c.error(`Target "${r}" has no command — services must be runnable.`);return}const f=U(o,i.root,a.options?.runFromWorkspaceRoot===!0),v=a.options?.envFile?L(f,a.options.envFile):{};return{command:a.command,cwd:f,env:{...v,...p.env},service:p,target:a,targetId:r}},"resolveTarget"),w=g(o=>{if(!o)throw new Error("Could not determine workspace root. Run `vis service` inside a workspace.");return o},"requireWorkspace"),oe=g(async({argument:o,options:e,visConfig:r,workspaceRoot:d})=>{const s=w(d),t=o[0]?.trim();if(!t){c.error("Missing target id. Usage: vis service start <project>:<target>"),process.exitCode=1;return}const n=await j(s,r,t);if(!n){process.exitCode=1;return}try{const{entry:i}=await C({command:n.command,config:n.service,cwd:n.cwd,env:n.env,id:t,readinessTimeoutMs:e.timeout,skipReadiness:e.readiness===!1,workspaceRoot:s});await(await h(r))?.callHook("service:start",i),c.success(`Started ${t} (pid ${String(i.pid)})`),c.info(`  log: ${i.logFile}`)}catch(i){const a=i instanceof Error?i.message:String(i);i instanceof G?c.error(`Readiness probe failed for ${t}: ${a}`):c.error(`Failed to start ${t}: ${a}`),process.exitCode=1}},"serviceStartExecute"),S=g(async({graceMs:o,hookSink:e,id:r,workspaceRoot:d})=>{const s=await $(d,r),{stopped:t}=await b({graceMs:o,id:r,workspaceRoot:d});return t?(s&&await e?.callHook("service:stop",s),c.success(`Stopped ${r}`),!0):(c.info(`No running service registered for ${r}`),!1)},"stopOne"),se=g(async({argument:o,options:e,visConfig:r,workspaceRoot:d})=>{const s=w(d),{graceMs:t}=e,n=o[0]?.trim(),i=await h(r);if(e.all===!0){if(n){c.error("Cannot combine --all with a target id. Use one or the other."),process.exitCode=1;return}const a=await q(s);if(a.length===0){c.info("No running services registered for this workspace.");return}for(const p of a)await S({graceMs:t,hookSink:i,id:p.id,workspaceRoot:s});return}if(!n){c.error("Missing target id. Usage: vis service stop <project>:<target> | --all"),process.exitCode=1;return}await S({graceMs:t,hookSink:i,id:n,workspaceRoot:s})||(process.exitCode=1)},"serviceStopExecute"),Q=g(o=>{const e=o.config.readiness?.tcp.port??o.config.port;return e===void 0?"—":String(e)},"formatPort"),E=new Set(["json","table"]),ie=g(async({logger:o,options:e,workspaceRoot:r})=>{const d=w(r),s=e.format??"table";if(!E.has(s)){c.error(`Invalid --format "${s}". Expected one of: ${[...E].sort().join(", ")}.`),process.exitCode=1;return}const{surviving:t}=await B(d);if(s==="json"){const l=Date.now();process.stdout.write(`${JSON.stringify(t.map(u=>{const x=Date.parse(u.startedAt);return{ageMs:Number.isFinite(x)?l-x:null,alive:M(u.pid),command:u.command,cwd:u.cwd,env:u.env,id:u.id,logFile:u.logFile,pid:u.pid,port:u.config.readiness?.tcp.port??u.config.port??null,startedAt:u.startedAt,visVersion:u.visVersion}}),void 0,2)}
`);return}if(t.length===0){c.info("No running services registered for this workspace.");return}const n=Date.now(),i=t.map(l=>{const u=Date.parse(l.startedAt);return{age:Number.isFinite(u)?O(u,n):"?",id:l.id,log:l.logFile,pid:String(l.pid),port:Q(l)}}),a=Math.max(2,...i.map(l=>l.id.length)),p=Math.max(3,...i.map(l=>l.pid.length)),f=Math.max(4,...i.map(l=>l.port.length)),v=Math.max(3,...i.map(l=>l.age.length));o.info(`  ${"id".padEnd(a)}  ${"pid".padEnd(p)}  ${"port".padEnd(f)}  ${"age".padEnd(v)}  log`),o.info(`  ${"-".repeat(a)}  ${"-".repeat(p)}  ${"-".repeat(f)}  ${"-".repeat(v)}  ---`);for(const l of i)o.info(`  ${l.id.padEnd(a)}  ${l.pid.padEnd(p)}  ${l.port.padEnd(f)}  ${l.age.padEnd(v)}  ${l.log}`)},"serviceListExecute"),ae=g(async({argument:o,options:e,workspaceRoot:r})=>{const d=w(r),s=o[0]?.trim();if(!s){c.error("Missing target id. Usage: vis service status <project>:<target>"),process.exitCode=1;return}const t=await $(d,s);if(!t){c.error(`No service registered for ${s}.`),process.exitCode=1;return}if(!M(t.pid)){c.error(`Service ${s} is not running (pid ${String(t.pid)} is dead). Run \`vis service start ${s}\` to recover.`),process.exitCode=1;return}try{await V(t.config,{timeoutMs:e.timeout}),c.success(`${s} healthy (pid ${String(t.pid)})`)}catch(n){const i=n instanceof Error?n.message:String(n);c.error(`${s} probe failed: ${i}`),process.exitCode=1}},"serviceStatusExecute"),ne=g(async({argument:o,options:e,visConfig:r,workspaceRoot:d})=>{const s=w(d),t=o[0]?.trim();if(!t){c.error("Missing target id. Usage: vis service restart <project>:<target>"),process.exitCode=1;return}const n=await h(r),i=await $(s,t);(await b({graceMs:e.graceMs,id:t,workspaceRoot:s})).stopped&&i&&await n?.callHook("service:stop",i);const a=await j(s,r,t);if(!a){process.exitCode=1;return}try{const{entry:p}=await C({command:a.command,config:a.service,cwd:a.cwd,env:a.env,id:t,readinessTimeoutMs:e.timeout,skipReadiness:e.readiness===!1,workspaceRoot:s});await n?.callHook("service:start",p),c.success(`Restarted ${t} (pid ${String(p.pid)})`)}catch(p){const f=p instanceof Error?p.message:String(p);c.error(`Failed to restart ${t}: ${f}`),process.exitCode=1}},"serviceRestartExecute"),Y=200,K=1024*1024,X=g(async o=>{let e=0;try{e=(await y(o)).size}catch{e=0}const r=new AbortController;let d=!1;const s=g(()=>{d=!0,r.abort()},"onSigint"),t=g(()=>{r.abort()},"onSigterm");process.on("SIGINT",s),process.on("SIGTERM",t);let n=!1;const i=g(async()=>{if(!n){n=!0;try{const a=await y(o).catch(()=>{});if(!a||(a.size<e&&(e=0),a.size===e))return;const p=a.size-e,f=Math.min(p,K),v=await R(o,"r");try{const l=Buffer.alloc(f);await v.read(l,0,f,e),process.stdout.write(l),e+=f}finally{await v.close().catch(()=>{})}}finally{n=!1}}},"tickOnce");try{const a=(async()=>{try{const p=N(o,{signal:r.signal});for(;!(await p.next()).done;)await i()}catch{}})();for(;!r.signal.aborted;)await i(),await new Promise(p=>{const f=setTimeout(p,Y);r.signal.addEventListener("abort",()=>{clearTimeout(f),p()},{once:!0})});await a.catch(()=>{}),await i().catch(()=>{})}finally{process.off("SIGINT",s),process.off("SIGTERM",t)}d&&(process.exitCode=130)},"tailLog"),ce=g(async({argument:o,options:e,workspaceRoot:r})=>{const d=w(r),s=o[0]?.trim();if(!s){c.error("Missing target id. Usage: vis service logs <project>:<target>"),process.exitCode=1;return}const t=await $(d,s);if(!t){c.error(`No service registered for ${s}.`),process.exitCode=1;return}if(!await P(t.logFile)){c.warn(`Log file is missing for ${s}: ${t.logFile}`),process.exitCode=1;return}if(e.follow===!0){await X(t.logFile);return}const n=await R(t.logFile,"r");try{const i=n.createReadStream();await new Promise((a,p)=>{i.on("end",a),i.on("error",p),i.pipe(process.stdout,{end:!1})})}finally{await n.close().catch(()=>{})}},"serviceLogsExecute");export{ie as serviceListExecute,ce as serviceLogsExecute,ne as serviceRestartExecute,oe as serviceStartExecute,ae as serviceStatusExecute,se as serviceStopExecute};
