nuwax-file-server 1.3.7 → 1.3.9
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/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.3.7",d=new ee,w={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"};function j(e){console.error(`${w.red}ERROR: ${e}${w.reset}`)}function b(e){console.log(`${w.green}${e}${w.reset}`)}function oe(e){console.log(`${w.blue}${e}${w.reset}`)}function y(e){return async(...t)=>{try{let o=await e(...t);o&&o.success===!1?(j(o.message||"Command failed"),process.exitCode=1):process.exitCode=0}catch(o){j(o?.message||"Command failed with unexpected error"),process.exitCode=1}}}async function se(e){let t=await N({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(`Service started (PID: ${t.pid})`),t}async function re(e){let t=await T({force:e.force,timeout:Number(e.timeout)});return t.success&&b(t.message||"Service stopped"),t}async function ne(e){let t=await O({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(t.message||"Service restarted"),t}function ie(){let e=_();return oe(`${n.name} service status:`),console.log(""),console.log(` Service name: ${n.name}`),console.log(` Running status: ${e.running?"Running":"Stopped"}`),console.log(` Message: ${e.message}`),console.log(` PID file: ${$()}`),e.pidInfo&&(console.log(` Process ID: ${e.pidInfo.pid}`),console.log(` Environment: ${e.pidInfo.env||"Unknown"}`),console.log(` Port: ${e.pidInfo.port||"Unknown"}`),console.log(` Version: ${e.pidInfo.version||A}`),console.log(` Platform: ${e.pidInfo.platform||process.platform}`),console.log(` Started at: ${e.pidInfo.startedAt||"Unknown"}`),console.log(` Uptime: ${L(e.pidInfo.startedAt)}`)),console.log(""),{success:e.running,message:e.message}}function ce(){d.name("nuwax-file-server").description("Cross-platform file service deployment tool, supporting start/stop/restart/status").version(A,"-v, --version","Display version number").helpOption("-h, --help","Display help information"),d.command("start").allowUnknownOption().description("Start service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(se)),d.command("stop").description("Stop service").option("--force","Force stop").option("--timeout <ms>","\u505C\u6B62\u670D\u52A1\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).action(y(re)),d.command("restart").allowUnknownOption().description("Restart service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(ne)),d.command("status").description("View service status").action(y(ie)),d.command("help").description("Display help information").action(()=>{d.outputHelp()}),d.parse(process.argv),process.argv.slice(2).length||(d.outputHelp(),process.exitCode=0)}ce();
|
|
2
|
+
import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.3.9",d=new ee,w={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"};function j(e){console.error(`${w.red}ERROR: ${e}${w.reset}`)}function b(e){console.log(`${w.green}${e}${w.reset}`)}function oe(e){console.log(`${w.blue}${e}${w.reset}`)}function y(e){return async(...t)=>{try{let o=await e(...t);o&&o.success===!1?(j(o.message||"Command failed"),process.exitCode=1):process.exitCode=0}catch(o){j(o?.message||"Command failed with unexpected error"),process.exitCode=1}}}async function se(e){let t=await N({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(`Service started (PID: ${t.pid})`),t}async function re(e){let t=await T({force:e.force,timeout:Number(e.timeout)});return t.success&&b(t.message||"Service stopped"),t}async function ne(e){let t=await O({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(t.message||"Service restarted"),t}function ie(){let e=_();return oe(`${n.name} service status:`),console.log(""),console.log(` Service name: ${n.name}`),console.log(` Running status: ${e.running?"Running":"Stopped"}`),console.log(` Message: ${e.message}`),console.log(` PID file: ${$()}`),e.pidInfo&&(console.log(` Process ID: ${e.pidInfo.pid}`),console.log(` Environment: ${e.pidInfo.env||"Unknown"}`),console.log(` Port: ${e.pidInfo.port||"Unknown"}`),console.log(` Version: ${e.pidInfo.version||A}`),console.log(` Platform: ${e.pidInfo.platform||process.platform}`),console.log(` Started at: ${e.pidInfo.startedAt||"Unknown"}`),console.log(` Uptime: ${L(e.pidInfo.startedAt)}`)),console.log(""),{success:e.running,message:e.message}}function ce(){d.name("nuwax-file-server").description("Cross-platform file service deployment tool, supporting start/stop/restart/status").version(A,"-v, --version","Display version number").helpOption("-h, --help","Display help information"),d.command("start").allowUnknownOption().description("Start service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(se)),d.command("stop").description("Stop service").option("--force","Force stop").option("--timeout <ms>","\u505C\u6B62\u670D\u52A1\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).action(y(re)),d.command("restart").allowUnknownOption().description("Restart service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(ne)),d.command("status").description("View service status").action(y(ie)),d.command("help").description("Display help information").action(()=>{d.outputHelp()}),d.parse(process.argv),process.argv.slice(2).length||(d.outputHelp(),process.exitCode=0)}ce();
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import
|
|
1
|
+
import v from"path";import i from"fs";import dt from"crypto";import l from"isomorphic-git";import{createPatch as ut}from"diff";import C from"../appConfig/index.js";import{log as g}from"../utils/log/logUtils.js";import{ValidationError as P,BusinessError as H,SystemError as A,ResourceError as W}from"../utils/error/errorHandler.js";import{resolveProjectPath as ht}from"../utils/common/projectPathUtils.js";import{isGitRepo as mt,ensureGitRepo as N,ensureGitignore as _,addAll as gt,commitAllChanges as wt,stageFiles as L,getDefaultAuthor as yt,hasGitHead as M}from"../utils/git/gitUtils.js";function k(o){const{workspaceType:t,projectId:s,isolationContext:e,userId:r,cId:a}=o||{};if(!t||!["pageApp","taskAgent"].includes(t))throw new P("workspaceType is required and must be pageApp or taskAgent",{field:"workspaceType"});if(t==="taskAgent"){if(!r||!a)throw new P("taskAgent mode requires userId and cId",{field:"userId/cId"});const c=v.join(C.COMPUTER_WORKSPACE_DIR,String(r),String(a));if(!i.existsSync(c))throw new W("Computer workspace does not exist",{userId:r,cId:a});return{targetPath:c,logId:`computer:${r}:${a}`}}if(!s)throw new P("pageApp mode requires projectId",{field:"projectId"});const n=ht(s,e||{});if(!i.existsSync(n))throw new W("Project does not exist",{projectId:s});return{targetPath:n,logId:s}}function q(o){for(let t=0;t<Math.min(o.length,8e3);t++)if(o[t]===0)return!0;return!1}function D(o){const t=Buffer.from(`blob ${o.length}\0`);return dt.createHash("sha1").update(Buffer.concat([t,o])).digest("hex")}function pt(o,t,s,e,r,a,n){const u=ut(o,e?t:"",r?s:"",e?`a/${o}`:"/dev/null",r?`b/${o}`:"/dev/null").split(`
|
|
2
2
|
`).slice(4);u.length>0&&u[u.length-1]===""&&u.pop();const d=[];let h=0,m=0;for(const y of u){if(y.startsWith("@@")){const p=y.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(p){const S=p[1],F=p[2]!==void 0?parseInt(p[2],10):1,T=p[3],b=p[4]!==void 0?parseInt(p[4],10):1,$=F===1?S:`${S},${F}`,G=b===1?T:`${T},${b}`;d.push(`@@ -${$} +${G} @@`);continue}}y.startsWith("+")&&!y.startsWith("+++")?h++:y.startsWith("-")&&!y.startsWith("---")&&m++,d.push(y)}const f=e&&t!==""&&!t.endsWith(`
|
|
3
3
|
`),I=r&&s!==""&&!s.endsWith(`
|
|
4
|
-
`);if((f||I)&&d.length>0){let y=0;for(let b=0;b<d.length;b++)d[b].startsWith("@@")&&(y=b);let p=-1,S=-1,F=-1;for(let b=d.length-1;b>y;b--){const $=d[b];$.startsWith("-")&&!$.startsWith("---")&&p<0?p=b:$.startsWith("+")&&!$.startsWith("++")&&S<0?S=b:$.startsWith(" ")&&F<0&&(F=b)}const T=Math.max(p,S,F);if(T>=0){const b=d[T];if(b.startsWith(" "))(f||I)&&d.splice(T+1,0,"\");else if(b.startsWith("+")){let $=-1;for(let G=T-1;G>y;G--)if(d[G].startsWith("-")&&!d[G].startsWith("---")){$=G;break}$>=0&&f?(d.splice($+1,0,"\"),I&&d.splice(T+2,0,"\")):I&&d.splice(T+1,0,"\")}else b.startsWith("-")&&f&&d.splice(T+1,0,"\")}}const O=e&&a?
|
|
4
|
+
`);if((f||I)&&d.length>0){let y=0;for(let b=0;b<d.length;b++)d[b].startsWith("@@")&&(y=b);let p=-1,S=-1,F=-1;for(let b=d.length-1;b>y;b--){const $=d[b];$.startsWith("-")&&!$.startsWith("---")&&p<0?p=b:$.startsWith("+")&&!$.startsWith("++")&&S<0?S=b:$.startsWith(" ")&&F<0&&(F=b)}const T=Math.max(p,S,F);if(T>=0){const b=d[T];if(b.startsWith(" "))(f||I)&&d.splice(T+1,0,"\");else if(b.startsWith("+")){let $=-1;for(let G=T-1;G>y;G--)if(d[G].startsWith("-")&&!d[G].startsWith("---")){$=G;break}$>=0&&f?(d.splice($+1,0,"\"),I&&d.splice(T+2,0,"\")):I&&d.splice(T+1,0,"\")}else b.startsWith("-")&&f&&d.splice(T+1,0,"\")}}const O=e&&a?D(a).substring(0,7):"0000000",x=r&&n?D(n).substring(0,7):"0000000",R=[];return R.push(`diff --git a/${o} b/${o}`),e?r?R.push(`index ${O}..${x} 100644`):(R.push("deleted file mode 100644"),R.push(`index ${O}..0000000`)):(R.push("new file mode 100644"),R.push(`index 0000000..${x}`)),R.push(`--- ${e?`a/${o}`:"/dev/null"}`),R.push(`+++ ${r?`b/${o}`:"/dev/null"}`),{diff:[...R,...d].join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`,insertions:h,deletions:m}}async function j(o){return l.resolveRef({fs:i,dir:o,ref:"HEAD"})}async function B(o,t,s){try{const{blob:e}=await l.readBlob({fs:i,dir:o,oid:t,filepath:s}),r=Buffer.from(e);return{content:r.toString("utf8"),buf:r}}catch{return null}}async function z(o={}){const{targetPath:t,logId:s}=k(o);if(mt(t))return{success:!0,message:"Git repository already initialized",logId:s,alreadyExists:!0};try{return await l.init({fs:i,dir:t,defaultBranch:"main"}),_(t),await l.setConfig({fs:i,dir:t,path:"user.name",value:C.GIT_DEFAULT_AUTHOR_NAME}),await l.setConfig({fs:i,dir:t,path:"user.email",value:C.GIT_DEFAULT_AUTHOR_EMAIL}),g(s,"INFO","Git repository initialized",{logId:s,targetPath:t}),{success:!0,message:"Git repository initialized successfully",logId:s,alreadyExists:!1}}catch(e){throw g(s,"ERROR","Failed to initialize Git repository",{logId:s,error:e.message}),new A("Failed to initialize Git repository",{originalError:e.message})}}async function K(o={}){const{targetPath:t,logId:s}=k(o);await N(t);try{const e=await l.currentBranch({fs:i,dir:t,fullname:!1}),r=await l.statusMatrix({fs:i,dir:t}),a=[],n=[],c=[],w=[],u=[];for(const[d,h,m,f]of r)h!==f&&a.push(d),h===0&&f!==0&&c.push(d),(h===1&&f===0||m===0&&f!==0)&&w.push(d),f!==0&&m!==0&&m!==f&&n.push(d),h===0&&f===0&&m!==0&&u.push(d);return{success:!0,logId:s,current:e,staged:[...new Set(a)],modified:[...new Set(n)],created:[...new Set(c)],deleted:[...new Set(w)],untracked:[...new Set(u)],conflicted:[],ahead:0,behind:0,tracking:null}}catch(e){throw g(s,"ERROR","Failed to get Git status",{logId:s,error:e.message}),new A("Failed to get Git status",{originalError:e.message})}}async function V(o={}){const{message:t,files:s,authorName:e,authorEmail:r}=o;if(!t||typeof t!="string")throw new
|
|
6
|
+
`,insertions:h,deletions:m}}async function j(o){return l.resolveRef({fs:i,dir:o,ref:"HEAD"})}async function B(o,t,s){try{const{blob:e}=await l.readBlob({fs:i,dir:o,oid:t,filepath:s}),r=Buffer.from(e);return{content:r.toString("utf8"),buf:r}}catch{return null}}async function z(o={}){const{targetPath:t,logId:s}=k(o);if(mt(t))return{success:!0,message:"Git repository already initialized",logId:s,alreadyExists:!0};try{return await l.init({fs:i,dir:t,defaultBranch:"main"}),_(t),await l.setConfig({fs:i,dir:t,path:"user.name",value:C.GIT_DEFAULT_AUTHOR_NAME}),await l.setConfig({fs:i,dir:t,path:"user.email",value:C.GIT_DEFAULT_AUTHOR_EMAIL}),g(s,"INFO","Git repository initialized",{logId:s,targetPath:t}),{success:!0,message:"Git repository initialized successfully",logId:s,alreadyExists:!1}}catch(e){throw g(s,"ERROR","Failed to initialize Git repository",{logId:s,error:e.message}),new A("Failed to initialize Git repository",{originalError:e.message})}}async function K(o={}){const{targetPath:t,logId:s}=k(o);await N(t);try{const e=await l.currentBranch({fs:i,dir:t,fullname:!1}),r=await l.statusMatrix({fs:i,dir:t}),a=[],n=[],c=[],w=[],u=[];for(const[d,h,m,f]of r)h!==f&&a.push(d),h===0&&f!==0&&c.push(d),(h===1&&f===0||m===0&&f!==0)&&w.push(d),f!==0&&m!==0&&m!==f&&n.push(d),h===0&&f===0&&m!==0&&u.push(d);return{success:!0,logId:s,current:e,staged:[...new Set(a)],modified:[...new Set(n)],created:[...new Set(c)],deleted:[...new Set(w)],untracked:[...new Set(u)],conflicted:[],ahead:0,behind:0,tracking:null}}catch(e){throw g(s,"ERROR","Failed to get Git status",{logId:s,error:e.message}),new A("Failed to get Git status",{originalError:e.message})}}async function V(o={}){const{message:t,files:s,authorName:e,authorEmail:r}=o;if(!t||typeof t!="string")throw new P("Commit message cannot be empty",{field:"message"});const{targetPath:a,logId:n}=k(o);await N(a);try{const c={name:e||C.GIT_DEFAULT_AUTHOR_NAME,email:r||C.GIT_DEFAULT_AUTHOR_EMAIL};if(Array.isArray(s)&&s.length>0){const u={};if(await L(a,s,{cache:u,force:!0}),!(await l.statusMatrix({fs:i,dir:a,cache:u,filepaths:s})).some(([,,,f])=>f!==1))return{success:!0,message:"Nothing to commit",logId:n,nothingToCommit:!0};const m=await l.commit({fs:i,dir:a,message:t,author:c,cache:u});return g(n,"INFO","Git commit successful",{logId:n,commitHash:m,message:t}),{success:!0,message:"Commit successful",logId:n,commit:m,summary:{changes:1}}}const w=await wt(a,{message:t,authorName:c.name,authorEmail:c.email,cache:{}});return w.nothingToCommit?{success:!0,message:"Nothing to commit",logId:n,nothingToCommit:!0}:(g(n,"INFO","Git commit successful",{logId:n,commitHash:w.commitHash,message:t,viaNative:w.viaNative===!0}),{success:!0,message:"Commit successful",logId:n,commit:w.commitHash,summary:{changes:1}})}catch(c){throw g(n,"ERROR","Failed to commit",{logId:n,error:c.message}),new A("Failed to commit",{originalError:c.message})}}async function J(o={}){const{files:t}=o,{targetPath:s,logId:e}=k(o);await N(s);try{const r={};return Array.isArray(t)&&t.length>0?await L(s,t,{cache:r,force:!0}):await gt(s,{cache:r}),g(e,"INFO","Git add successful",{logId:e,filesCount:t?t.length:"all"}),{success:!0,message:"Files staged successfully",logId:e}}catch(r){throw g(e,"ERROR","Failed to add files",{logId:e,error:r.message}),new A("Failed to add files",{originalError:r.message})}}async function Q(o={}){const{files:t}=o,{targetPath:s,logId:e}=k(o);await N(s);try{if(Array.isArray(t)&&t.length>0){for(const n of t)await l.resetIndex({fs:i,dir:s,filepath:n});return g(e,"INFO","Git unstage specified files",{logId:e,files:t}),{success:!0,message:"Specified files unstaged successfully",logId:e,files:t}}const a=(await l.statusMatrix({fs:i,dir:s})).filter(([,,,n])=>n!==1).map(([n])=>n);for(const n of a)await l.resetIndex({fs:i,dir:s,filepath:n});return g(e,"INFO","Git unstage all files",{logId:e}),{success:!0,message:"All files unstaged successfully",logId:e,files:"all"}}catch(r){throw g(e,"ERROR","Failed to unstage",{logId:e,error:r.message}),new A("Failed to unstage files",{originalError:r.message})}}async function U(o,t){const s=new Set;for(const r of t){let a=v.dirname(r);for(;a&&a!==".";)s.add(a),a=v.dirname(a)}const e=[...s].sort((r,a)=>{const n=r.split(/[/\\]/).length;return a.split(/[/\\]/).length-n});for(const r of e){const a=v.join(o,r);try{(await i.promises.readdir(a)).length===0&&await i.promises.rmdir(a)}catch{}}}async function X(o={}){const{files:t}=o,{targetPath:s,logId:e}=k(o);await N(s);try{const r=await l.statusMatrix({fs:i,dir:s}),a=Array.isArray(t)&&t.length>0?new Set(t):null,n=[],c=[],w=[];for(const[d,h,m,f]of r)a&&!a.has(d)||(h!==0?(f!==1||m!==1)&&n.push(d):h===0&&f!==0?c.push(d):h===0&&f===0&&m!==0&&w.push(d));if(n.length>0){const d=await j(s);for(const h of n){const m=await B(s,d,h);if(!m)continue;const f=v.join(s,h);i.mkdirSync(v.dirname(f),{recursive:!0}),i.writeFileSync(f,m.buf),await l.add({fs:i,dir:s,filepath:h})}}for(const d of c){try{await l.remove({fs:i,dir:s,filepath:d})}catch{}const h=v.join(s,d);i.existsSync(h)&&await i.promises.unlink(h)}c.length>0&&await U(s,c);for(const d of w){const h=v.join(s,d);i.existsSync(h)&&await i.promises.unlink(h)}w.length>0&&await U(s,w);const u=n.length+c.length+w.length;return g(e,"INFO","Git discard",{logId:e,trackedFiles:n.length,newFiles:c.length,untrackedFiles:w.length}),{success:!0,message:"Files discarded successfully",logId:e,discardedCount:u,trackedFiles:n,newFiles:c,untrackedFiles:w}}catch(r){throw g(e,"ERROR","Failed to discard",{logId:e,error:r.message}),new A("Failed to discard files",{originalError:r.message})}}async function Y(o={}){const{maxCount:t=50,branch:s,skip:e=0,filePath:r}=o,{targetPath:a,logId:n}=k(o);await N(a);try{if(!await M(a))return{success:!0,logId:n,commits:[],total:0};const c=Math.min(Math.max(1,t),500),w=Math.max(0,e),u={fs:i,dir:a,depth:c+w};s&&(u.ref=s),r&&(u.filepath=r);const m=(await l.log(u)).slice(w,w+c).map(f=>({hash:f.oid,date:new Date(f.commit.author.timestamp*1e3).toISOString(),message:f.commit.message,author_name:f.commit.author.name,author_email:f.commit.author.email}));return{success:!0,logId:n,commits:m,total:m.length}}catch(c){if(c?.code==="NotFoundError"||/NotFoundError|Could not find|unable to resolve|does not have any commits/i.test(String(c?.message||"")))return{success:!0,logId:n,commits:[],total:0};throw g(n,"ERROR","Failed to get Git log",{logId:n,error:c.message}),new A("Failed to get Git log",{originalError:c.message})}}async function Z(o={}){const{source:t="worktree",from:s,to:e,paths:r}=o,{targetPath:a,logId:n}=k(o);await N(a);try{const c=Array.isArray(r)&&r.length>0?new Set(r):null;let w="";const u=[];let d=0,h=0;async function m(f,I,O){const x=!!I,R=!!O;if(x&&R&&I.content===O.content)return;let E=!1;if(x&&q(I.buf)&&(E=!0),R&&!E&&q(O.buf)&&(E=!0),E){const F=x?D(I.buf).substring(0,7):"0000000",T=R?D(O.buf).substring(0,7):"0000000",b=[`diff --git a/${f} b/${f}`];x?R?b.push(`index ${F}..${T} 100644`):(b.push("deleted file mode 100644"),b.push(`index ${F}..0000000`)):(b.push("new file mode 100644"),b.push(`index 0000000..${T}`)),b.push(`Binary files ${x?`a/${f}`:"/dev/null"} and ${R?`b/${f}`:"/dev/null"} differ`),w+=b.join(`
|
|
7
7
|
`)+`
|
|
8
|
-
`,u.push({file:f,changes:0,insertions:0,deletions:0,binary:!0});return}const{diff:y,insertions:p,deletions:S}=pt(f,x?I.content:"",R?O.content:"",x,R,x?I.buf:null,R?O.buf:null);w+=y,u.push({file:f,changes:p+S,insertions:p,deletions:S,binary:!1}),d+=p,h+=S}if(t==="commit"){let f,I;if(s&&e)f=s,I=e;else if(s){const E=await l.readCommit({fs:i,dir:a,oid:s});E.commit.parent&&E.commit.parent.length>0?(f=E.commit.parent[0],I=s):(f=null,I=s)}else throw new v("source=commit requires at least 'from'",{field:"from"});const O=f?new Set(await l.listFiles({fs:i,dir:a,ref:f})):new Set,x=new Set(await l.listFiles({fs:i,dir:a,ref:I})),R=new Set([...O,...x]);for(const E of R){if(c&&!c.has(E))continue;const y=O.has(E)?await B(a,f,E):null,p=x.has(E)?await B(a,I,E):null;await m(E,y,p)}}else{if(!await W(a))return{success:!0,logId:n,source:t,diff:"",summary:{files:[],insertions:0,deletions:0}};const f=await j(a),I=await l.statusMatrix({fs:i,dir:a});for(const[O,x,R,E]of I){if(c&&!c.has(O))continue;if(t==="staged"){if(E===1||x===0&&E===0)continue}else if(x===0&&E===0||x===1&&R===1&&E===1)continue;const y=x!==0?await B(a,f,O):null;let p=null;if(R!==0){const S=P.join(a,O);if(i.existsSync(S))try{const F=i.readFileSync(S);p={content:F.toString("utf8"),buf:F}}catch{}}await m(O,y,p)}}return{success:!0,logId:n,source:t,diff:w,summary:{files:u,insertions:d,deletions:h}}}catch(c){throw c instanceof v?c:(g(n,"ERROR","Failed to get Git diff",{logId:n,error:c.message}),new A("Failed to get Git diff",{originalError:c.message}))}}async function tt(o={}){const{ref:t="HEAD",filePath:s}=o;if(!s)throw new v("filePath is required",{field:"filePath"});const{targetPath:e,logId:r}=k(o);await N(e);try{let a;if(t==="worktree"||t==="staged"||t===""){const n=P.join(e,s);a=i.existsSync(n)?i.readFileSync(n,"utf8"):""}else try{const n=await l.resolveRef({fs:i,dir:e,ref:t}),{blob:c}=await l.readBlob({fs:i,dir:e,oid:n,filepath:s});a=Buffer.from(c).toString("utf8")}catch{a=""}return{success:!0,logId:r,filePath:s,ref:t,content:a}}catch(a){throw a instanceof D?a:(g(r,"ERROR","Failed to get file content",{logId:r,ref:t,filePath:s,error:a.message}),new A("Failed to get file content",{originalError:a.message}))}}async function et(o={}){const{target:t,mode:s="mixed"}=o;if(!t)throw new v("Reset target cannot be empty",{field:"target"});if(!["soft","mixed","hard"].includes(s))throw new v("Mode must be soft, mixed or hard",{field:"mode"});const{targetPath:e,logId:r}=k(o);await N(e);try{if(!await W(e))throw new H("Cannot reset: repository has no commits yet");const a=await l.log({fs:i,dir:e,depth:1}),n=a.length>0?a[0].oid:null,c=await l.currentBranch({fs:i,dir:e,fullname:!1});if(!c)throw new H("Cannot reset: detached HEAD");const w=s==="hard"?new Set(await l.listFiles({fs:i,dir:e,ref:"HEAD"})):null;if(await l.writeRef({fs:i,dir:e,ref:`refs/heads/${c}`,value:t,force:!0}),s==="mixed"||s==="hard"){const u=await l.listFiles({fs:i,dir:e,ref:t}),d=new Set(u);for(const m of u)await l.resetIndex({fs:i,dir:e,filepath:m,ref:t});const h=await l.statusMatrix({fs:i,dir:e});for(const[m,,,f]of h)if(!d.has(m)&&f!==0)try{await l.remove({fs:i,dir:e,filepath:m})}catch{}}if(s==="hard"){const u=await l.listFiles({fs:i,dir:e,ref:t}),d=new Set(u);for(const h of u){const m=await B(e,t,h);if(!m)continue;const f=P.join(e,h);i.mkdirSync(P.dirname(f),{recursive:!0}),i.writeFileSync(f,m.buf)}if(w){for(const h of w)if(!d.has(h)){const m=P.join(e,h);i.existsSync(m)&&i.unlinkSync(m)}}_(e),await l.add({fs:i,dir:e,filepath:".gitignore"})}return g(r,"INFO","Git reset successful",{logId:r,target:t,mode:s,previousHead:n}),{success:!0,message:`Reset (${s}) to ${t} successful`,logId:r,target:t,mode:s,previousHead:n}}catch(a){throw a instanceof H?a:(g(r,"ERROR","Failed to reset",{logId:r,target:t,mode:s,error:a.message}),new A("Failed to reset",{originalError:a.message}))}}async function st(o={}){const{target:t,message:s,authorName:e,authorEmail:r}=o;if(!t)throw new v("Revert target cannot be empty",{field:"target"});const{targetPath:a,logId:n}=k(o);await N(a);try{if(!await W(a))throw new H("Cannot revert: repository has no commits yet");let c;try{c=(await l.readCommit({fs:i,dir:a,oid:t})).oid}catch{throw new v("Revert target commit does not exist",{field:"target",target:t})}const w=await l.statusMatrix({fs:i,dir:a});if(w.some(([y,p,S,F])=>p===0&&F===0?!1:S!==1||F!==1)){const y=w.filter(([,F])=>F!==0),p=y.filter(([,,F])=>F!==1).map(([F])=>F),S=y.filter(([,,,F])=>F!==1).map(([F])=>F);throw new H("Working directory is not clean, please commit or stash your changes before reverting",{staged:S,modified:p})}const d=new Set(await l.listFiles({fs:i,dir:a,ref:c})),h=await j(a),m=new Set(await l.listFiles({fs:i,dir:a,ref:h})),f=[];for(const y of d){const p=await B(a,c,y);if(!p)continue;const S=P.join(a,y);i.mkdirSync(P.dirname(S),{recursive:!0}),i.writeFileSync(S,p.buf),await l.add({fs:i,dir:a,filepath:y})}for(const y of m)if(!d.has(y)){f.push(y);try{await l.remove({fs:i,dir:a,filepath:y})}catch{}const p=P.join(a,y);i.existsSync(p)&&await i.promises.unlink(p)}if(f.length>0&&await U(a,f),_(a),await l.add({fs:i,dir:a,filepath:".gitignore"}),!(await l.statusMatrix({fs:i,dir:a})).some(([,,,y])=>y!==1))return g(n,"INFO","Nothing to revert, current HEAD already matches target",{logId:n,target:c}),{success:!0,message:"Nothing to revert, already at target state",logId:n,nothingToCommit:!0,target:c};const x={name:e||C.GIT_DEFAULT_AUTHOR_NAME,email:r||C.GIT_DEFAULT_AUTHOR_EMAIL},R=s||`Revert to ${c.substring(0,7)}`,E=await l.commit({fs:i,dir:a,message:R,author:x});return g(n,"INFO","Git revert successful",{logId:n,target:c,commitHash:E,previousHead:h,removedFilesCount:f.length}),{success:!0,message:"Revert successful",logId:n,commit:E,target:c,previousHead:h}}catch(c){throw c instanceof v||c instanceof H?c:(g(n,"ERROR","Failed to revert",{logId:n,target:t,error:c.message}),new A("Failed to revert",{originalError:c.message}))}}async function at(o={}){const{target:t}=o;if(!t)throw new v("Checkout target cannot be empty",{field:"target"});const{targetPath:s,logId:e}=k(o);await N(s);try{const r=await l.listFiles({fs:i,dir:s,ref:t});for(const a of r){const n=await B(s,t,a);if(!n)continue;const c=P.join(s,a);i.mkdirSync(P.dirname(c),{recursive:!0}),i.writeFileSync(c,n.buf),await l.add({fs:i,dir:s,filepath:a})}return _(s),await l.add({fs:i,dir:s,filepath:".gitignore"}),g(e,"INFO","Git checkout files successful",{logId:e,target:t}),{success:!0,message:`Checkout files from ${t} successful`,logId:e,target:t}}catch(r){throw g(e,"ERROR","Failed to checkout files",{logId:e,target:t,error:r.message}),new A("Failed to checkout files",{originalError:r.message})}}async function rt(o={}){const{targetPath:t,logId:s}=k(o);await N(t);try{const e=await l.listTags({fs:i,dir:t});return{success:!0,logId:s,tags:e,latest:e.length>0?e[e.length-1]:null}}catch(e){throw g(s,"ERROR","Failed to list tags",{logId:s,error:e.message}),new A("Failed to list tags",{originalError:e.message})}}async function it(o={}){const{tagName:t,message:s}=o;if(!t)throw new v("Tag name cannot be empty",{field:"tagName"});const{targetPath:e,logId:r}=k(o);await N(e);try{return s?await l.annotatedTag({fs:i,dir:e,ref:t,message:s,tagger:yt()}):await l.tag({fs:i,dir:e,ref:t}),g(r,"INFO","Git tag created",{logId:r,tagName:t,annotated:!!s}),{success:!0,message:"Tag created successfully",logId:r,tagName:t}}catch(a){throw g(r,"ERROR","Failed to create tag",{logId:r,tagName:t,error:a.message}),new A("Failed to create tag",{originalError:a.message})}}async function nt(o={}){const{tagName:t}=o;if(!t)throw new v("Tag name cannot be empty",{field:"tagName"});const{targetPath:s,logId:e}=k(o);await N(s);try{return await l.deleteRef({fs:i,dir:s,ref:`refs/tags/${t}`}),g(e,"INFO","Git tag deleted",{logId:e,tagName:t}),{success:!0,message:"Tag deleted successfully",logId:e,tagName:t}}catch(r){throw g(e,"ERROR","Failed to delete tag",{logId:e,tagName:t,error:r.message}),new A("Failed to delete tag",{originalError:r.message})}}async function ot(o={}){const{targetPath:t,logId:s}=k(o);await N(t);try{const e=await l.listBranches({fs:i,dir:t}),r=await l.currentBranch({fs:i,dir:t,fullname:!1}),a={};for(const n of e)a[n]={name:n,current:n===r};return{success:!0,logId:s,branches:a,current:r}}catch(e){throw g(s,"ERROR","Failed to list branches",{logId:s,error:e.message}),new A("Failed to list branches",{originalError:e.message})}}async function ct(o={}){const{branchName:t,startPoint:s}=o;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:e,logId:r}=k(o);await N(e);try{const a=s||"HEAD";return await l.branch({fs:i,dir:e,ref:t,object:a,checkout:!0}),g(r,"INFO","Git branch created",{logId:r,branchName:t,startPoint:s}),{success:!0,message:"Branch created and switched to",logId:r,branchName:t}}catch(a){throw g(r,"ERROR","Failed to create branch",{logId:r,branchName:t,error:a.message}),new A("Failed to create branch",{originalError:a.message})}}async function lt(o={}){const{branchName:t}=o;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:s,logId:e}=k(o);await N(s);try{const r=await l.statusMatrix({fs:i,dir:s});if(r.some(([n,c,w,u])=>c===0&&u===0?!1:w!==1||u!==1)){const n=r.filter(([,u])=>u!==0),c=n.filter(([,,u])=>u!==1).map(([u])=>u),w=n.filter(([,,,u])=>u!==1).map(([u])=>u);throw new H("Working directory is not clean, please commit or stash your changes before switching branches",{staged:w,modified:c})}return await l.checkout({fs:i,dir:s,ref:t}),g(e,"INFO","Git branch switched",{logId:e,branchName:t}),{success:!0,message:"Branch switched successfully",logId:e,branchName:t}}catch(r){throw r instanceof H?r:(g(e,"ERROR","Failed to switch branch",{logId:e,branchName:t,error:r.message}),new A("Failed to switch branch",{originalError:r.message}))}}async function ft(o={}){const{branchName:t,force:s=!1}=o;if(!t)throw new v("Branch name cannot be empty",{field:"branchName"});const{targetPath:e,logId:r}=k(o);await N(e);try{if(await l.currentBranch({fs:i,dir:e,fullname:!1})===t)throw new H("Cannot delete the current branch, please switch to another branch first");return await l.deleteBranch({fs:i,dir:e,ref:t,force:s}),g(r,"INFO","Git branch deleted",{logId:r,branchName:t,force:s}),{success:!0,message:"Branch deleted successfully",logId:r,branchName:t}}catch(a){throw a instanceof H?a:(g(r,"ERROR","Failed to delete branch",{logId:r,branchName:t,error:a.message}),new A("Failed to delete branch",{originalError:a.message}))}}export{z as init,K as status,V as commit,J as add,Q as unstage,X as discard,Y as logHistory,Z as diff,tt as fileContent,et as reset,st as revert,at as checkout,rt as listTags,it as createTag,nt as deleteTag,ot as listBranches,ct as createBranch,lt as switchBranch,ft as deleteBranch};export default{init:z,status:K,commit:V,add:J,unstage:Q,discard:X,logHistory:Y,diff:Z,fileContent:tt,reset:et,revert:st,checkout:at,listTags:rt,createTag:it,deleteTag:nt,listBranches:ot,createBranch:ct,switchBranch:lt,deleteBranch:ft};
|
|
8
|
+
`,u.push({file:f,changes:0,insertions:0,deletions:0,binary:!0});return}const{diff:y,insertions:p,deletions:S}=pt(f,x?I.content:"",R?O.content:"",x,R,x?I.buf:null,R?O.buf:null);w+=y,u.push({file:f,changes:p+S,insertions:p,deletions:S,binary:!1}),d+=p,h+=S}if(t==="commit"){let f,I;if(s&&e)f=s,I=e;else if(s){const E=await l.readCommit({fs:i,dir:a,oid:s});E.commit.parent&&E.commit.parent.length>0?(f=E.commit.parent[0],I=s):(f=null,I=s)}else throw new P("source=commit requires at least 'from'",{field:"from"});const O=f?new Set(await l.listFiles({fs:i,dir:a,ref:f})):new Set,x=new Set(await l.listFiles({fs:i,dir:a,ref:I})),R=new Set([...O,...x]);for(const E of R){if(c&&!c.has(E))continue;const y=O.has(E)?await B(a,f,E):null,p=x.has(E)?await B(a,I,E):null;await m(E,y,p)}}else{if(!await M(a))return{success:!0,logId:n,source:t,diff:"",summary:{files:[],insertions:0,deletions:0}};const f=await j(a),I=await l.statusMatrix({fs:i,dir:a});for(const[O,x,R,E]of I){if(c&&!c.has(O))continue;if(t==="staged"){if(E===1||x===0&&E===0)continue}else if(x===0&&E===0||x===1&&R===1&&E===1)continue;const y=x!==0?await B(a,f,O):null;let p=null;if(R!==0){const S=v.join(a,O);if(i.existsSync(S))try{const F=i.readFileSync(S);p={content:F.toString("utf8"),buf:F}}catch{}}await m(O,y,p)}}return{success:!0,logId:n,source:t,diff:w,summary:{files:u,insertions:d,deletions:h}}}catch(c){throw c instanceof P?c:(g(n,"ERROR","Failed to get Git diff",{logId:n,error:c.message}),new A("Failed to get Git diff",{originalError:c.message}))}}async function tt(o={}){const{ref:t="HEAD",filePath:s}=o;if(!s)throw new P("filePath is required",{field:"filePath"});const{targetPath:e,logId:r}=k(o);await N(e);try{let a;if(t==="worktree"||t==="staged"||t===""){const n=v.join(e,s);a=i.existsSync(n)?i.readFileSync(n,"utf8"):""}else try{const n=await l.resolveRef({fs:i,dir:e,ref:t}),{blob:c}=await l.readBlob({fs:i,dir:e,oid:n,filepath:s});a=Buffer.from(c).toString("utf8")}catch{a=""}return{success:!0,logId:r,filePath:s,ref:t,content:a}}catch(a){throw a instanceof W?a:(g(r,"ERROR","Failed to get file content",{logId:r,ref:t,filePath:s,error:a.message}),new A("Failed to get file content",{originalError:a.message}))}}async function et(o={}){const{target:t,mode:s="mixed"}=o;if(!t)throw new P("Reset target cannot be empty",{field:"target"});if(!["soft","mixed","hard"].includes(s))throw new P("Mode must be soft, mixed or hard",{field:"mode"});const{targetPath:e,logId:r}=k(o);await N(e);try{if(!await M(e))throw new H("Cannot reset: repository has no commits yet");const a=await l.log({fs:i,dir:e,depth:1}),n=a.length>0?a[0].oid:null,c=await l.currentBranch({fs:i,dir:e,fullname:!1});if(!c)throw new H("Cannot reset: detached HEAD");const w=s==="hard"?new Set(await l.listFiles({fs:i,dir:e,ref:"HEAD"})):null;if(await l.writeRef({fs:i,dir:e,ref:`refs/heads/${c}`,value:t,force:!0}),s==="mixed"||s==="hard"){const u=await l.listFiles({fs:i,dir:e,ref:t}),d=new Set(u);for(const m of u)await l.resetIndex({fs:i,dir:e,filepath:m,ref:t});const h=await l.statusMatrix({fs:i,dir:e});for(const[m,,,f]of h)if(!d.has(m)&&f!==0)try{await l.remove({fs:i,dir:e,filepath:m})}catch{}}if(s==="hard"){const u=await l.listFiles({fs:i,dir:e,ref:t}),d=new Set(u);for(const h of u){const m=await B(e,t,h);if(!m)continue;const f=v.join(e,h);i.mkdirSync(v.dirname(f),{recursive:!0}),i.writeFileSync(f,m.buf)}if(w){for(const h of w)if(!d.has(h)){const m=v.join(e,h);i.existsSync(m)&&i.unlinkSync(m)}}_(e),await l.add({fs:i,dir:e,filepath:".gitignore"})}return g(r,"INFO","Git reset successful",{logId:r,target:t,mode:s,previousHead:n}),{success:!0,message:`Reset (${s}) to ${t} successful`,logId:r,target:t,mode:s,previousHead:n}}catch(a){throw a instanceof H?a:(g(r,"ERROR","Failed to reset",{logId:r,target:t,mode:s,error:a.message}),new A("Failed to reset",{originalError:a.message}))}}async function st(o={}){const{target:t,message:s,authorName:e,authorEmail:r}=o;if(!t)throw new P("Revert target cannot be empty",{field:"target"});const{targetPath:a,logId:n}=k(o);await N(a);try{if(!await M(a))throw new H("Cannot revert: repository has no commits yet");let c;try{c=(await l.readCommit({fs:i,dir:a,oid:t})).oid}catch{throw new P("Revert target commit does not exist",{field:"target",target:t})}const w=await l.statusMatrix({fs:i,dir:a});if(w.some(([y,p,S,F])=>p===0&&F===0?!1:S!==1||F!==1)){const y=w.filter(([,F])=>F!==0),p=y.filter(([,,F])=>F!==1).map(([F])=>F),S=y.filter(([,,,F])=>F!==1).map(([F])=>F);throw new H("Working directory is not clean, please commit or stash your changes before reverting",{staged:S,modified:p})}const d=new Set(await l.listFiles({fs:i,dir:a,ref:c})),h=await j(a),m=new Set(await l.listFiles({fs:i,dir:a,ref:h})),f=[];for(const y of d){const p=await B(a,c,y);if(!p)continue;const S=v.join(a,y);i.mkdirSync(v.dirname(S),{recursive:!0}),i.writeFileSync(S,p.buf),await l.add({fs:i,dir:a,filepath:y})}for(const y of m)if(!d.has(y)){f.push(y);try{await l.remove({fs:i,dir:a,filepath:y})}catch{}const p=v.join(a,y);i.existsSync(p)&&await i.promises.unlink(p)}if(f.length>0&&await U(a,f),_(a),await l.add({fs:i,dir:a,filepath:".gitignore"}),!(await l.statusMatrix({fs:i,dir:a})).some(([,,,y])=>y!==1))return g(n,"INFO","Nothing to revert, current HEAD already matches target",{logId:n,target:c}),{success:!0,message:"Nothing to revert, already at target state",logId:n,nothingToCommit:!0,target:c};const x={name:e||C.GIT_DEFAULT_AUTHOR_NAME,email:r||C.GIT_DEFAULT_AUTHOR_EMAIL},R=s||`Revert to ${c.substring(0,7)}`,E=await l.commit({fs:i,dir:a,message:R,author:x});return g(n,"INFO","Git revert successful",{logId:n,target:c,commitHash:E,previousHead:h,removedFilesCount:f.length}),{success:!0,message:"Revert successful",logId:n,commit:E,target:c,previousHead:h}}catch(c){throw c instanceof P||c instanceof H?c:(g(n,"ERROR","Failed to revert",{logId:n,target:t,error:c.message}),new A("Failed to revert",{originalError:c.message}))}}async function at(o={}){const{target:t}=o;if(!t)throw new P("Checkout target cannot be empty",{field:"target"});const{targetPath:s,logId:e}=k(o);await N(s);try{const r=await l.listFiles({fs:i,dir:s,ref:t});for(const a of r){const n=await B(s,t,a);if(!n)continue;const c=v.join(s,a);i.mkdirSync(v.dirname(c),{recursive:!0}),i.writeFileSync(c,n.buf),await l.add({fs:i,dir:s,filepath:a})}return _(s),await l.add({fs:i,dir:s,filepath:".gitignore"}),g(e,"INFO","Git checkout files successful",{logId:e,target:t}),{success:!0,message:`Checkout files from ${t} successful`,logId:e,target:t}}catch(r){throw g(e,"ERROR","Failed to checkout files",{logId:e,target:t,error:r.message}),new A("Failed to checkout files",{originalError:r.message})}}async function rt(o={}){const{targetPath:t,logId:s}=k(o);await N(t);try{const e=await l.listTags({fs:i,dir:t});return{success:!0,logId:s,tags:e,latest:e.length>0?e[e.length-1]:null}}catch(e){throw g(s,"ERROR","Failed to list tags",{logId:s,error:e.message}),new A("Failed to list tags",{originalError:e.message})}}async function it(o={}){const{tagName:t,message:s}=o;if(!t)throw new P("Tag name cannot be empty",{field:"tagName"});const{targetPath:e,logId:r}=k(o);await N(e);try{return s?await l.annotatedTag({fs:i,dir:e,ref:t,message:s,tagger:yt()}):await l.tag({fs:i,dir:e,ref:t}),g(r,"INFO","Git tag created",{logId:r,tagName:t,annotated:!!s}),{success:!0,message:"Tag created successfully",logId:r,tagName:t}}catch(a){throw g(r,"ERROR","Failed to create tag",{logId:r,tagName:t,error:a.message}),new A("Failed to create tag",{originalError:a.message})}}async function nt(o={}){const{tagName:t}=o;if(!t)throw new P("Tag name cannot be empty",{field:"tagName"});const{targetPath:s,logId:e}=k(o);await N(s);try{return await l.deleteRef({fs:i,dir:s,ref:`refs/tags/${t}`}),g(e,"INFO","Git tag deleted",{logId:e,tagName:t}),{success:!0,message:"Tag deleted successfully",logId:e,tagName:t}}catch(r){throw g(e,"ERROR","Failed to delete tag",{logId:e,tagName:t,error:r.message}),new A("Failed to delete tag",{originalError:r.message})}}async function ot(o={}){const{targetPath:t,logId:s}=k(o);await N(t);try{const e=await l.listBranches({fs:i,dir:t}),r=await l.currentBranch({fs:i,dir:t,fullname:!1}),a={};for(const n of e)a[n]={name:n,current:n===r};return{success:!0,logId:s,branches:a,current:r}}catch(e){throw g(s,"ERROR","Failed to list branches",{logId:s,error:e.message}),new A("Failed to list branches",{originalError:e.message})}}async function ct(o={}){const{branchName:t,startPoint:s}=o;if(!t)throw new P("Branch name cannot be empty",{field:"branchName"});const{targetPath:e,logId:r}=k(o);await N(e);try{const a=s||"HEAD";return await l.branch({fs:i,dir:e,ref:t,object:a,checkout:!0}),g(r,"INFO","Git branch created",{logId:r,branchName:t,startPoint:s}),{success:!0,message:"Branch created and switched to",logId:r,branchName:t}}catch(a){throw g(r,"ERROR","Failed to create branch",{logId:r,branchName:t,error:a.message}),new A("Failed to create branch",{originalError:a.message})}}async function lt(o={}){const{branchName:t}=o;if(!t)throw new P("Branch name cannot be empty",{field:"branchName"});const{targetPath:s,logId:e}=k(o);await N(s);try{const r=await l.statusMatrix({fs:i,dir:s});if(r.some(([n,c,w,u])=>c===0&&u===0?!1:w!==1||u!==1)){const n=r.filter(([,u])=>u!==0),c=n.filter(([,,u])=>u!==1).map(([u])=>u),w=n.filter(([,,,u])=>u!==1).map(([u])=>u);throw new H("Working directory is not clean, please commit or stash your changes before switching branches",{staged:w,modified:c})}return await l.checkout({fs:i,dir:s,ref:t}),g(e,"INFO","Git branch switched",{logId:e,branchName:t}),{success:!0,message:"Branch switched successfully",logId:e,branchName:t}}catch(r){throw r instanceof H?r:(g(e,"ERROR","Failed to switch branch",{logId:e,branchName:t,error:r.message}),new A("Failed to switch branch",{originalError:r.message}))}}async function ft(o={}){const{branchName:t,force:s=!1}=o;if(!t)throw new P("Branch name cannot be empty",{field:"branchName"});const{targetPath:e,logId:r}=k(o);await N(e);try{if(await l.currentBranch({fs:i,dir:e,fullname:!1})===t)throw new H("Cannot delete the current branch, please switch to another branch first");return await l.deleteBranch({fs:i,dir:e,ref:t,force:s}),g(r,"INFO","Git branch deleted",{logId:r,branchName:t,force:s}),{success:!0,message:"Branch deleted successfully",logId:r,branchName:t}}catch(a){throw a instanceof H?a:(g(r,"ERROR","Failed to delete branch",{logId:r,branchName:t,error:a.message}),new A("Failed to delete branch",{originalError:a.message}))}}export{z as init,K as status,V as commit,J as add,Q as unstage,X as discard,Y as logHistory,Z as diff,tt as fileContent,et as reset,st as revert,at as checkout,rt as listTags,it as createTag,nt as deleteTag,ot as listBranches,ct as createBranch,lt as switchBranch,ft as deleteBranch};export default{init:z,status:K,commit:V,add:J,unstage:Q,discard:X,logHistory:Y,diff:Z,fileContent:tt,reset:et,revert:st,checkout:at,listTags:rt,createTag:it,deleteTag:nt,listBranches:ot,createBranch:ct,switchBranch:lt,deleteBranch:ft};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{log as i}from"../utils/log/logUtils.js";import E from"../appConfig/index.js";import p from"path";import t from"fs";import{extractZip as _}from"../utils/common/zipUtils.js";import"../utils/build/startDevUtils.js";import"../utils/build/restartDevUtils.js";import{stopDevServer as B}from"../utils/build/stopDevUtils.js";import{ValidationError as y,BusinessError as W,SystemError as P,FileError as b,ResourceError as A}from"../utils/error/errorHandler.js";import{sanitizeSensitivePaths as G}from"../utils/common/sensitiveUtils.js";import{removeNodeModules as j}from"../utils/buildDependency/dependencyManager.js";import{backupProjectToZip as I,copyDirectoryFiltered as ee}from"../utils/project/backupUtils.js";import{createPnpmNpmrc as L}from"../utils/common/npmrcUtils.js";import{copyNodeModulesFromCache as C}from"../utils/common/templateCacheUtils.js";import{resolveProjectPath as F}from"../utils/common/projectPathUtils.js";import{ensurePrimaryAgentDirs as te,syncAgents as ie}from"../utils/common/AgentWorkspaceUtils.js";async function J(e,r="react",c={}){const o=Date.now();if(!e)throw new y("Project ID cannot be empty",{field:"projectId"});const s=["react","vue3"];if(!s.includes(r))throw new y("Template type is invalid, only supports react or vue3",{field:"templateType",templateType:r,allowedValues:s});const m={react:E.INIT_PROJECT_NAME_REACT||"react-vite-template",vue3:E.INIT_PROJECT_NAME_VUE3||"vue3-vite-template"}[r],u=F(e,c);if(t.existsSync(u))throw new W(`Project directory ${e} already exists`,{projectId:e,projectPath:u});try{t.mkdirSync(u,{recursive:!0}),i(e,"INFO",`Project directory created successfully: ${u}`,{projectId:e});const f=E.INIT_PROJECT_DIR,w=p.join(f,`${m}.zip`),l=p.join(f,m);if(i(e,"DEBUG","Start checking template directory",{templateDir:l,templateZipPath:w}),!t.existsSync(l)){if(!t.existsSync(w))throw i(e,"ERROR",`Initialization template does not exist: ${w}`,{projectId:e,templateZipPath:w}),new A("Initialization template does not exist",{});if(i(e,"INFO",`Template directory does not exist, starting to unzip template: ${w}`,{projectId:e,templateZipPath:w}),await _(w,l),i(e,"INFO","Template unzip completed",{projectId:e}),!t.existsSync(l))throw new P("Template unzip directory still does not exist",{})}i(e,"DEBUG","Start copying template content to project directory",{templateDir:l,projectPath:u});const d=await t.promises.readdir(l,{withFileTypes:!0});for(const a of d){const h=p.join(l,a.name),N=p.join(u,a.name);a.isDirectory()?(await t.promises.mkdir(N,{recursive:!0}),await ee(h,N)):a.isFile()&&(await t.promises.mkdir(p.dirname(N),{recursive:!0}),await t.promises.copyFile(h,N))}i(e,"DEBUG","Try copying node_modules from template cache",{projectPath:u});const D=await C(u,e);if(D.cached&&i(e,"INFO",`node_modules copied from cache: ${D.templateType}`,{elapsed:D.elapsed}),i(e,"DEBUG","Start creating .npmrc configuration file",{projectPath:u}),await L(u,e),i(e,"INFO",`Project ${e} initialized successfully`,{projectId:e,elapsedMs:Date.now()-o}),E.GIT_ENABLED)try{const a=await import("./gitService.js");await a.init({workspaceType:"pageApp",projectId:e,isolationContext:c}),await a.commit({workspaceType:"pageApp",projectId:e,isolationContext:c,message:`init project: ${e}`})}catch(a){i(e,"WARN","Git init/commit failed, skipping",{error:a.message})}return{success:!0,message:`Project ${e} created successfully`,projectPath:u}}catch(f){throw i(e,"ERROR",`Project ${e} initialization failed: ${f.message}`,{projectId:e,elapsedMs:Date.now()-o}),new P(`Project ${e} initialization failed: ${f.message}`,{projectId:e,projectPath:u,originalError:f.message})}}async function re(e){const r=await t.promises.readdir(e,{withFileTypes:!0}),c=E.TOP_LEVEL_NOISE_PATTERNS,o=r.filter(s=>{const n=s.name;return n.startsWith(".")?!1:!c.some(m=>m.endsWith("*")?n.startsWith(m.slice(0,-1)):n===m)});if(o.length===1&&o[0].isDirectory()){const s=p.join(e,o[0].name),n=p.join(e,`temp_${Date.now()}`);try{await t.promises.rename(s,n)}catch(u){if(u.code==="EXDEV")await t.promises.cp(s,n,{recursive:!0}),await t.promises.rm(s,{recursive:!0,force:!0});else throw u}const m=await t.promises.readdir(n);for(const u of m){const f=p.join(n,u),w=p.join(e,u);try{await t.promises.rename(f,w)}catch(l){if(l.code==="EXDEV")await t.promises.cp(f,w,{recursive:!0}),await t.promises.rm(f,{recursive:!0,force:!0});else throw l}}await t.promises.rm(n,{recursive:!0,force:!0})}}async function U(e,r={}){if(!e)throw new y("Project ID cannot be empty",{field:"projectId"});const c=F(e,r);if(t.existsSync(c))try{i(e,"INFO",`Start cleaning project directory: ${c}`,{projectId:e}),await t.promises.rm(c,{recursive:!0,force:!0}),i(e,"INFO",`Project directory cleaned up: ${c}`,{projectId:e})}catch(o){throw i(e,"ERROR",`Failed to clean project directory: ${o.message}`,{projectId:e,projectPath:c,originalError:o.message}),new P(`Failed to clean project directory: ${o.message}`,{projectId:e,projectPath:c,originalError:o.message})}else i(e,"INFO",`Project directory does not exist, no need to clean: ${c}`,{projectId:e})}function se(e){if(!t.existsSync(e))return!0;try{return t.readdirSync(e).filter(o=>!o.startsWith(".")&&o!=="node_modules").length===0}catch(r){const c=p.basename(e);return i(c,"ERROR",`Failed to check if directory is empty: ${r.message}`,{dirPath:e}),!0}}async function Z(e,r,c,o,s,n,m={}){const u=Date.now(),f=F(e,m);try{if(se(f))i(e,"INFO","Project directory is empty, directly deploying new project",{projectId:e});else{i(e,"INFO","Project directory is not empty, starting to backup current version",{projectId:e});const l=parseInt(o)-1,d=p.join(E.UPLOAD_PROJECT_DIR,e),D=p.join(d,`${e}-v${l}.zip`);if(t.existsSync(D))i(e,"INFO",`Backup file already exists, skipping backup: ${D}`,{projectId:e});else try{E.GIT_ENABLED||await S(e,l,m),i(e,"INFO",`Current version backed up: ${D}`,{projectId:e})}catch(a){throw i(e,"ERROR",`Failed to backup current version: ${a.message}`,{projectId:e}),new P(`Failed to backup current version: ${a.message}`,{projectId:e,originalError:a.message})}if(s&&!isNaN(Number(s))){const a=Number(s);i(e,"INFO",`Stopping old version dev server, PID: ${a}`,{projectId:e});try{await B(c,e,a,{strict:!0}),i(e,"INFO","Old version dev server stopped",{projectId:e})}catch(h){i(e,"WARN",`Failed to stop old version dev server: ${h.message}`,{projectId:e,pid:a})}}t.existsSync(f)&&(i(e,"INFO",`Cleaning project directory: ${f}`,{projectId:e}),await t.promises.rm(f,{recursive:!0,force:!0}))}if(t.mkdirSync(f,{recursive:!0}),i(e,"INFO",`Project directory created successfully: ${f}`,{projectId:e}),i(e,"DEBUG","Start extracting zip file to project directory",{projectId:e,zipFilePath:r}),await _(r,f),i(e,"DEBUG","Zip file extracted successfully",{projectId:e}),i(e,"DEBUG","Check and remove top level folder",{projectId:e}),await re(f),i(e,"DEBUG","Check and remove node_modules folder",{projectId:e}),await j(f),i(e,"DEBUG","Try copying node_modules from template cache",{projectId:e}),await C(f,e),i(e,"DEBUG","Start creating .npmrc configuration file",{projectId:e}),await L(f,e),E.GIT_ENABLED)try{const l=await import("./gitService.js");await l.init({workspaceType:"pageApp",projectId:e,isolationContext:m}),await l.commit({workspaceType:"pageApp",projectId:e,isolationContext:m,message:`upload project v${o}`})}catch(l){i(e,"WARN","Git commit failed after upload, skipping",{error:l.message})}return i(e,"INFO",`Project ${e} uploaded successfully`,{projectId:e,codeVersion:o,elapsedMs:Date.now()-u}),{success:!0,message:`Project ${e} uploaded successfully`,projectId:e,codeVersion:o}}catch(w){i(e,"ERROR",`Failed to upload project: ${w.message}`,{projectId:e,elapsedMs:Date.now()-u});try{await U(e,m),i(e,"INFO","Failed to upload project, project directory cleaned up",{projectId:e})}catch(l){i(e,"ERROR",`Failed to clean project directory: ${l.message}`,{projectId:e,originalError:l.message})}throw w.isOperational?w:new P(`Failed to upload project: ${w.message}`,{projectId:e,projectPath:f,zipFilePath:r,originalError:w.message})}}async function S(e,r,c={}){if(!e)throw new y("Project ID cannot be empty",{field:"projectId"});if(r==null)throw new y("codeVersion cannot be empty",{field:"codeVersion"});const o=Number(r);if(!Number.isFinite(o))throw new y("codeVersion must be a number",{field:"codeVersion"});const s=F(e,c);if(!t.existsSync(s))throw new A("Project does not exist",{projectId:e});const n=p.join(E.UPLOAD_PROJECT_DIR,e);t.existsSync(n)||t.mkdirSync(n,{recursive:!0});const m=`${e}-v${o}.zip`,u=p.join(n,m);return i(e,"DEBUG","Start backing up project to zip",{projectId:e,versionNum:o,outZipPath:u}),await I(e,s,u)}async function V(e,r,c){if(!e)throw new y("Project ID cannot be empty",{field:"projectId"});if(!r)throw new y("codeVersion cannot be empty",{field:"codeVersion"});if(!c)throw new y("Please upload a zip file",{field:"zipFile"});const o=p.join(E.UPLOAD_PROJECT_DIR,e);t.existsSync(o)||t.mkdirSync(o,{recursive:!0});const s=c.path,n=p.join(o,`${e}-v${r}.zip`);try{try{t.renameSync(s,n)}catch(m){if(m.code==="EXDEV")t.copyFileSync(s,n),t.unlinkSync(s);else throw m}return i(e,"INFO","File saved successfully",{projectId:e,codeVersion:r,filePath:n}),{success:!0,filePath:n}}catch(m){if(i(e,"ERROR","Failed to move file",{projectId:e,codeVersion:r,error:m.message}),t.existsSync(s))try{t.unlinkSync(s)}catch(u){i(e,"ERROR","Failed to clean temporary file",{projectId:e,error:u.message})}throw new P("Failed to save file",{projectId:e,codeVersion:r,originalError:m.message})}}function ae(e){if(!e)return[];if(Array.isArray(e))return e.map(r=>typeof r=="string"?r.trim():"").filter(Boolean);if(typeof e=="string"){const r=e.trim();if(!r)return[];try{const c=JSON.parse(r);if(Array.isArray(c))return c.map(o=>typeof o=="string"?o.trim():"").filter(Boolean)}catch{}return[r]}return[]}async function X(e){t.existsSync(e)&&await t.promises.rm(e,{recursive:!0,force:!0})}async function q(e,r){try{await t.promises.rename(e,r)}catch(c){if(c.code==="EXDEV"){async function o(s,n){if((await t.promises.lstat(s)).isDirectory()){await t.promises.mkdir(n,{recursive:!0});const u=await t.promises.readdir(s);for(const f of u)await o(p.join(s,f),p.join(n,f))}else await t.promises.copyFile(s,n)}await o(e,r),await t.promises.rm(e,{recursive:!0,force:!0})}else throw c}}async function oe(e,r){const c=p.join(e,r);if(t.existsSync(c)&&(await t.promises.lstat(c)).isDirectory())return c;const o=await t.promises.readdir(e,{withFileTypes:!0});for(const s of o){if(!s.isDirectory())continue;const n=p.join(e,s.name,r);if(t.existsSync(n)&&(await t.promises.lstat(n)).isDirectory())return n}return null}async function ne(e,r,c){let o;try{o=await fetch(e)}catch(u){throw new b(`Failed to download skill zip from url: ${e}`,{url:e,reason:u.message})}if(!o.ok)throw new b(`Failed to download skill zip from url: ${e}`,{url:e,status:o.status,statusText:o.statusText});const s=o.headers.get("content-type")||"";s&&!s.includes("zip")&&!s.includes("octet-stream")&&i(c,"WARN","Downloaded skill url content-type is not typical zip",{url:e,contentType:s});const n=await o.arrayBuffer(),m=Buffer.from(n);await t.promises.writeFile(r,m)}async function H(e,r,c,o={}){const s=String(e),n=Date.now(),m=ae(c),u=[],f=[];if(!e)throw new y("Project ID cannot be empty",{field:"projectId"});if(!r&&m.length===0)throw new y("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(r){if(!r.path)throw new y("Uploaded file has no valid path",{field:"file.path"});if(p.extname(r.originalname||r.filename||"").toLowerCase()!==".zip")throw new y("Only zip files are supported",{field:"file",originalName:r?.originalname})}const w=F(String(e),o);if(!t.existsSync(w))throw new y("Project does not exist",{field:"projectId"});const{skillsDir:l,agentTypes:d}=await te(w),D=p.join(E.UPLOAD_PROJECT_DIR,"temp");try{await t.promises.mkdir(l,{recursive:!0}),await t.promises.mkdir(D,{recursive:!0});const a=new Set;if(r){const k=p.join(D,`project_skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);f.push(k),await t.promises.mkdir(k,{recursive:!0}),await _(r.path,k);const $=await oe(k,"skills");if(!$)i(s,"WARN","skills directory not found in uploaded zip",{projectId:e,extractRoot:k});else{const R=(await t.promises.readdir($,{withFileTypes:!0})).filter(v=>v.isDirectory()&&!v.name.startsWith("."));for(const v of R){const T=p.join($,v.name),x=p.join(l,v.name);t.existsSync(x)&&await X(x),await q(T,x),a.add(v.name)}}}for(let k=0;k<m.length;k+=1){const $=m[k],O=p.join(D,`project_skill_url_${Date.now()}_${k}_${Math.round(Math.random()*1e6)}.zip`);u.push(O);const R=p.join(D,`project_skill_url_extract_${Date.now()}_${k}_${Math.round(Math.random()*1e6)}`);f.push(R),await t.promises.mkdir(R,{recursive:!0}),await ne($,O,s),await _(O,R);const T=(await t.promises.readdir(R,{withFileTypes:!0})).filter(g=>g.isDirectory()&&!g.name.startsWith(".")),M=T.find(g=>g.name==="skills")?(await t.promises.readdir(p.join(R,"skills"),{withFileTypes:!0})).filter(g=>g.isDirectory()&&!g.name.startsWith(".")).map(g=>({name:g.name,sourcePath:p.join(R,"skills",g.name)})):T.map(g=>({name:g.name,sourcePath:p.join(R,g.name)}));if(M.length===0){i(s,"WARN","No skill directory found after extracting skill url zip",{projectId:e,skillUrl:$,extractRoot:R});continue}for(const g of M){const z=p.join(l,g.name);t.existsSync(z)&&await X(z),await q(g.sourcePath,z),a.add(g.name)}}const h=Array.from(a),N=h.length>0?`Pushed ${h.length} skills: ${h.join(", ")}`:"No valid skill directories found in file or skillUrls";return i(s,"INFO","Push skills to project workspace completed",{projectId:e,updatedSkills:h,skillUrlsCount:m.length,hasFile:!!r,agentTypes:d,elapsedMs:Date.now()-n}),await ie(w),{message:N,projectPath:w,updatedSkills:h}}catch(a){throw i(s,"ERROR","Push skills to project workspace failed",{projectId:e,error:a.message,elapsedMs:Date.now()-n}),a instanceof y||a instanceof b||a instanceof W||a instanceof P?a:new P(`Failed to push skills to project workspace: ${a.message}`,{projectId:e})}finally{for(const a of f)try{t.existsSync(a)&&await t.promises.rm(a,{recursive:!0,force:!0})}catch(h){i(s,"WARN","Failed to clean extracted skill temp dir",{extractRoot:a,error:h.message})}for(const a of u)try{t.existsSync(a)&&await t.promises.unlink(a)}catch(h){i(s,"WARN","Failed to clean downloaded skill zip",{zipPath:a,error:h.message})}try{r?.path&&t.existsSync(r.path)&&await t.promises.unlink(r.path)}catch(a){i(s,"WARN","Failed to clean uploaded skill zip",{tempZipPath:r?.path,error:a.message})}}}async function K(e,r,c,o={}){const s=Date.now();if(!e)throw new y("Project ID cannot be empty",{field:"projectId"});const n=null;try{if(r&&!isNaN(Number(r))){const l=Number(r);i(n,"INFO",`[delete-project] Stopping development server, PID: ${l}`,{projectId:e,pid:l});try{await B(c,e,l,{strict:!0}),i(n,"INFO","[delete-project] Development server stopped",{projectId:e})}catch(d){i(n,"WARN",`[delete-project] Failed to stop development server: ${d.message}`,{projectId:e,pid:l})}}const m=[p.join(E.UPLOAD_PROJECT_DIR,e),F(e,o),p.join(E.DIST_TARGET_DIR,e),p.join(E.LOG_BASE_DIR,e)],u=[],f=[];for(const l of m)if(t.existsSync(l))try{await t.promises.rm(l,{recursive:!0,force:!0}),u.push(l),i(n,"INFO",`[delete-project] Directory deleted successfully: ${l}`,{projectId:e})}catch(d){f.push({path:l,error:d.message}),i(n,"ERROR",`[delete-project] Directory deleted failed: ${l}`,{projectId:e,error:d.message})}else i(n,"INFO",`[delete-project] Directory does not exist, skipping deletion: ${l}`,{projectId:e});const w={success:!0,message:`Project ${e} deleted successfully`,projectId:e,deletedDirectories:u,failedDirectories:f};return f.length>0&&(w.message+=`, but ${f.length} directories deleted failed`,i(n,"WARN","[delete-project] Some directories deleted failed",{projectId:e,failedDirs:f})),i(n,"INFO",`[delete-project] Project deleted successfully: ${e}`,{projectId:e,elapsedMs:Date.now()-s}),w}catch(m){throw i(n,"ERROR",`[delete-project] Failed to delete project: ${m.message}`,{projectId:e,originalError:m.message,elapsedMs:Date.now()-s}),m.isOperational?m:new P(`Failed to delete project: ${m.message}`,{projectId:e,originalError:m.message})}}async function Q(e,r,c,o,s={}){const n=Date.now();if(!e)throw new y("Project ID cannot be empty",{field:"projectId"});if(r==null)throw new y("codeVersion cannot be empty",{field:"codeVersion"});const m=Number(r);if(!Number.isFinite(m))throw new y("codeVersion must be a number",{field:"codeVersion"});const u=F(e,s);if(!t.existsSync(u))throw new A("Project does not exist",{projectId:e});const f=p.join(E.UPLOAD_PROJECT_DIR,e),w=`${e}-v${m}.zip`,l=p.join(f,w);if(c!=="LATEST"){if(t.existsSync(l))return i(e,"INFO",`Using existing export file: ${l}`,{projectId:e,zipPath:l}),{success:!0,projectId:e,zipPath:l};throw new A(`Specified version zip file does not exist: ${l}`,{projectId:e,zipPath:l})}const d=p.join(u,"cpage_config.json");let D=!1;try{if(o)try{const h=JSON.stringify(o,null,2);await t.promises.writeFile(d,h,"utf8"),D=!0,i(e,"INFO",`Configuration file created successfully: ${d}`,{projectId:e,configFilePath:d})}catch(h){throw i(e,"ERROR",`Failed to create configuration file: ${h.message}`,{projectId:e,error:h.message}),new b("Failed to create configuration file",{projectId:e,configFilePath:d,originalError:h.message})}i(e,"DEBUG","Start executing export and packaging",{projectId:e,codeVersion:r});const a=await S(e,r,s);return i(e,"INFO",`Project exported successfully: ${a}`,{projectId:e,zipPath:a,elapsedMs:Date.now()-n}),{success:!0,projectId:e,zipPath:a}}catch(a){throw i(e,"ERROR",`Failed to export project: ${a?.message}`,{projectId:e,elapsedMs:Date.now()-n}),a.isOperational?a:new P("Failed to export project",{projectId:e,originalError:a&&a.message?G(a.message):a&&a.message})}finally{if(D&&t.existsSync(d))try{await t.promises.unlink(d),i(e,"INFO",`Temporary configuration file deleted successfully: ${d}`,{projectId:e,configFilePath:d})}catch(a){i(e,"WARN",`Failed to delete temporary configuration file: ${a.message}`,{projectId:e,error:a.message})}}}async function Y(e,r,c={}){const o=Date.now();if(!e)throw new y("Project ID cannot be empty",{field:"projectId"});if(r==null)throw new y("codeVersion cannot be empty",{field:"codeVersion"});try{const s=await S(e,r,c);return i(e,"INFO",`Current version backed up successfully: ${s}`,{projectId:e,zipPath:s,elapsedMs:Date.now()-o}),{success:!0,projectId:e,zipPath:s}}catch(s){throw i(e,"ERROR",`Failed to backup current version: ${s?.message}`,{projectId:e,elapsedMs:Date.now()-o}),s.isOperational?s:new P("Failed to backup current version",{projectId:e,originalError:s&&s.message?G(s.message):s&&s.message})}}export{J as createProject,Z as uploadProject,Y as backupCurrentVersion,Q as exportProject,S as backupProjectOfVersion,U as cleanupProjectDirectory,V as handleFileUpload,H as pushSkillsToWorkspace,K as deleteProject};export default{createProject:J,uploadProject:Z,backupCurrentVersion:Y,exportProject:Q,backupProjectOfVersion:S,cleanupProjectDirectory:U,handleFileUpload:V,pushSkillsToWorkspace:H,deleteProject:K};
|
|
1
|
+
import{log as i}from"../utils/log/logUtils.js";import E from"../appConfig/index.js";import p from"path";import t from"fs";import{extractZip as _}from"../utils/common/zipUtils.js";import"../utils/build/startDevUtils.js";import"../utils/build/restartDevUtils.js";import{stopDevServer as W}from"../utils/build/stopDevUtils.js";import{ValidationError as h,BusinessError as G,SystemError as P,FileError as b,ResourceError as A}from"../utils/error/errorHandler.js";import{sanitizeSensitivePaths as C}from"../utils/common/sensitiveUtils.js";import{removeNodeModules as ee}from"../utils/buildDependency/dependencyManager.js";import{backupProjectToZip as te,copyDirectoryFiltered as ie}from"../utils/project/backupUtils.js";import{createPnpmNpmrc as L}from"../utils/common/npmrcUtils.js";import{copyNodeModulesFromCache as J}from"../utils/common/templateCacheUtils.js";import{resolveProjectPath as N}from"../utils/common/projectPathUtils.js";import{ensurePrimaryAgentDirs as se,syncAgents as re}from"../utils/common/AgentWorkspaceUtils.js";async function Z(e,s="react",c={}){const a=Date.now();if(!e)throw new h("Project ID cannot be empty",{field:"projectId"});const r=["react","vue3"];if(!r.includes(s))throw new h("Template type is invalid, only supports react or vue3",{field:"templateType",templateType:s,allowedValues:r});const m={react:E.INIT_PROJECT_NAME_REACT||"react-vite-template",vue3:E.INIT_PROJECT_NAME_VUE3||"vue3-vite-template"}[s],u=N(e,c);if(t.existsSync(u))throw new G(`Project directory ${e} already exists`,{projectId:e,projectPath:u});try{t.mkdirSync(u,{recursive:!0}),i(e,"INFO",`Project directory created successfully: ${u}`,{projectId:e});const f=E.INIT_PROJECT_DIR,w=p.join(f,`${m}.zip`),l=p.join(f,m);if(i(e,"DEBUG","Start checking template directory",{templateDir:l,templateZipPath:w}),!t.existsSync(l)){if(!t.existsSync(w))throw i(e,"ERROR",`Initialization template does not exist: ${w}`,{projectId:e,templateZipPath:w}),new A("Initialization template does not exist",{});if(i(e,"INFO",`Template directory does not exist, starting to unzip template: ${w}`,{projectId:e,templateZipPath:w}),await _(w,l),i(e,"INFO","Template unzip completed",{projectId:e}),!t.existsSync(l))throw new P("Template unzip directory still does not exist",{})}i(e,"DEBUG","Start copying template content to project directory",{templateDir:l,projectPath:u});const d=await t.promises.readdir(l,{withFileTypes:!0});for(const n of d){const y=p.join(l,n.name),R=p.join(u,n.name);n.isDirectory()?(await t.promises.mkdir(R,{recursive:!0}),await ie(y,R)):n.isFile()&&(await t.promises.mkdir(p.dirname(R),{recursive:!0}),await t.promises.copyFile(y,R))}i(e,"DEBUG","Try copying node_modules from template cache",{projectPath:u});const D=await J(u,e);if(D.cached&&i(e,"INFO",`node_modules copied from cache: ${D.templateType}`,{elapsed:D.elapsed}),i(e,"DEBUG","Start creating .npmrc configuration file",{projectPath:u}),await L(u,e),i(e,"INFO",`Project ${e} initialized successfully`,{projectId:e,elapsedMs:Date.now()-a}),E.GIT_ENABLED)try{const n=await import("./gitService.js");await n.init({workspaceType:"pageApp",projectId:e,isolationContext:c}),await n.commit({workspaceType:"pageApp",projectId:e,isolationContext:c,message:`init project: ${e}`})}catch(n){i(e,"WARN","Git init/commit failed, skipping",{error:n.message})}return{success:!0,message:`Project ${e} created successfully`,projectPath:u}}catch(f){throw i(e,"ERROR",`Project ${e} initialization failed: ${f.message}`,{projectId:e,elapsedMs:Date.now()-a}),new P(`Project ${e} initialization failed: ${f.message}`,{projectId:e,projectPath:u,originalError:f.message})}}async function ae(e){const s=await t.promises.readdir(e,{withFileTypes:!0}),c=E.TOP_LEVEL_NOISE_PATTERNS,a=s.filter(r=>{const o=r.name;return o.startsWith(".")?!1:!c.some(m=>m.endsWith("*")?o.startsWith(m.slice(0,-1)):o===m)});if(a.length===1&&a[0].isDirectory()){const r=p.join(e,a[0].name),o=p.join(e,`temp_${Date.now()}`);try{await t.promises.rename(r,o)}catch(u){if(u.code==="EXDEV")await t.promises.cp(r,o,{recursive:!0}),await t.promises.rm(r,{recursive:!0,force:!0});else throw u}const m=await t.promises.readdir(o);for(const u of m){const f=p.join(o,u),w=p.join(e,u);try{await t.promises.rename(f,w)}catch(l){if(l.code==="EXDEV")await t.promises.cp(f,w,{recursive:!0}),await t.promises.rm(f,{recursive:!0,force:!0});else throw l}}await t.promises.rm(o,{recursive:!0,force:!0})}}async function M(e,s={}){if(!e)throw new h("Project ID cannot be empty",{field:"projectId"});const c=N(e,s);if(t.existsSync(c))try{i(e,"INFO",`Start cleaning project directory: ${c}`,{projectId:e}),await t.promises.rm(c,{recursive:!0,force:!0}),i(e,"INFO",`Project directory cleaned up: ${c}`,{projectId:e})}catch(a){throw i(e,"ERROR",`Failed to clean project directory: ${a.message}`,{projectId:e,projectPath:c,originalError:a.message}),new P(`Failed to clean project directory: ${a.message}`,{projectId:e,projectPath:c,originalError:a.message})}else i(e,"INFO",`Project directory does not exist, no need to clean: ${c}`,{projectId:e})}function oe(e){if(!t.existsSync(e))return!0;try{return t.readdirSync(e).filter(a=>!a.startsWith(".")&&a!=="node_modules").length===0}catch(s){const c=p.basename(e);return i(c,"ERROR",`Failed to check if directory is empty: ${s.message}`,{dirPath:e}),!0}}async function V(e,s,c,a,r,o,m={}){const u=Date.now(),f=N(e,m);try{if(oe(f))i(e,"INFO","Project directory is empty, directly deploying new project",{projectId:e});else{i(e,"INFO","Project directory is not empty, starting to backup current version",{projectId:e});const l=parseInt(a)-1,d=p.join(E.UPLOAD_PROJECT_DIR,e),D=p.join(d,`${e}-v${l}.zip`);if(t.existsSync(D))i(e,"INFO",`Backup file already exists, skipping backup: ${D}`,{projectId:e});else try{E.GIT_ENABLED||await O(e,l,m),i(e,"INFO",`Current version backed up: ${D}`,{projectId:e})}catch(n){throw i(e,"ERROR",`Failed to backup current version: ${n.message}`,{projectId:e}),new P(`Failed to backup current version: ${n.message}`,{projectId:e,originalError:n.message})}if(r&&!isNaN(Number(r))){const n=Number(r);i(e,"INFO",`Stopping old version dev server, PID: ${n}`,{projectId:e});try{await W(c,e,n,{strict:!0}),i(e,"INFO","Old version dev server stopped",{projectId:e})}catch(y){i(e,"WARN",`Failed to stop old version dev server: ${y.message}`,{projectId:e,pid:n})}}t.existsSync(f)&&(i(e,"INFO",`Cleaning project directory: ${f}`,{projectId:e}),await t.promises.rm(f,{recursive:!0,force:!0}))}if(t.mkdirSync(f,{recursive:!0}),i(e,"INFO",`Project directory created successfully: ${f}`,{projectId:e}),i(e,"DEBUG","Start extracting zip file to project directory",{projectId:e,zipFilePath:s}),await _(s,f),i(e,"DEBUG","Zip file extracted successfully",{projectId:e}),i(e,"DEBUG","Check and remove top level folder",{projectId:e}),await ae(f),i(e,"DEBUG","Check and remove node_modules folder",{projectId:e}),await ee(f),i(e,"DEBUG","Try copying node_modules from template cache",{projectId:e}),await J(f,e),i(e,"DEBUG","Start creating .npmrc configuration file",{projectId:e}),await L(f,e),E.GIT_ENABLED)try{const l=await import("./gitService.js");await l.init({workspaceType:"pageApp",projectId:e,isolationContext:m}),await l.commit({workspaceType:"pageApp",projectId:e,isolationContext:m,message:`upload project v${a}`})}catch(l){i(e,"WARN","Git commit failed after upload, skipping",{error:l.message})}return i(e,"INFO",`Project ${e} uploaded successfully`,{projectId:e,codeVersion:a,elapsedMs:Date.now()-u}),{success:!0,message:`Project ${e} uploaded successfully`,projectId:e,codeVersion:a}}catch(w){i(e,"ERROR",`Failed to upload project: ${w.message}`,{projectId:e,elapsedMs:Date.now()-u});try{await M(e,m),i(e,"INFO","Failed to upload project, project directory cleaned up",{projectId:e})}catch(l){i(e,"ERROR",`Failed to clean project directory: ${l.message}`,{projectId:e,originalError:l.message})}throw w.isOperational?w:new P(`Failed to upload project: ${w.message}`,{projectId:e,projectPath:f,zipFilePath:s,originalError:w.message})}}async function O(e,s,c={}){if(!e)throw new h("Project ID cannot be empty",{field:"projectId"});if(s==null)throw new h("codeVersion cannot be empty",{field:"codeVersion"});const a=Number(s);if(!Number.isFinite(a))throw new h("codeVersion must be a number",{field:"codeVersion"});const r=N(e,c);if(!t.existsSync(r))throw new A("Project does not exist",{projectId:e});const o=p.join(E.UPLOAD_PROJECT_DIR,e);t.existsSync(o)||t.mkdirSync(o,{recursive:!0});const m=`${e}-v${a}.zip`,u=p.join(o,m);return i(e,"DEBUG","Start backing up project to zip",{projectId:e,versionNum:a,outZipPath:u}),await te(e,r,u)}async function X(e,s,c){if(!e)throw new h("Project ID cannot be empty",{field:"projectId"});if(!s)throw new h("codeVersion cannot be empty",{field:"codeVersion"});if(!c)throw new h("Please upload a zip file",{field:"zipFile"});const a=p.join(E.UPLOAD_PROJECT_DIR,e);t.existsSync(a)||t.mkdirSync(a,{recursive:!0});const r=c.path,o=p.join(a,`${e}-v${s}.zip`);try{try{t.renameSync(r,o)}catch(m){if(m.code==="EXDEV")t.copyFileSync(r,o),t.unlinkSync(r);else throw m}return i(e,"INFO","File saved successfully",{projectId:e,codeVersion:s,filePath:o}),{success:!0,filePath:o}}catch(m){if(i(e,"ERROR","Failed to move file",{projectId:e,codeVersion:s,error:m.message}),t.existsSync(r))try{t.unlinkSync(r)}catch(u){i(e,"ERROR","Failed to clean temporary file",{projectId:e,error:u.message})}throw new P("Failed to save file",{projectId:e,codeVersion:s,originalError:m.message})}}function ne(e){if(!e)return[];if(Array.isArray(e))return e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean);if(typeof e=="string"){const s=e.trim();if(!s)return[];try{const c=JSON.parse(s);if(Array.isArray(c))return c.map(a=>typeof a=="string"?a.trim():"").filter(Boolean)}catch{}return[s]}return[]}async function q(e){t.existsSync(e)&&await t.promises.rm(e,{recursive:!0,force:!0})}async function H(e,s){try{await t.promises.rename(e,s)}catch(c){if(c.code==="EXDEV"){async function a(r,o){if((await t.promises.lstat(r)).isDirectory()){await t.promises.mkdir(o,{recursive:!0});const u=await t.promises.readdir(r);for(const f of u)await a(p.join(r,f),p.join(o,f))}else await t.promises.copyFile(r,o)}await a(e,s),await t.promises.rm(e,{recursive:!0,force:!0})}else throw c}}async function le(e,s){const c=p.join(e,s);if(t.existsSync(c)&&(await t.promises.lstat(c)).isDirectory())return c;const a=await t.promises.readdir(e,{withFileTypes:!0});for(const r of a){if(!r.isDirectory())continue;const o=p.join(e,r.name,s);if(t.existsSync(o)&&(await t.promises.lstat(o)).isDirectory())return o}return null}async function ce(e,s,c){let a;try{a=await fetch(e)}catch(u){throw new b(`Failed to download skill zip from url: ${e}`,{url:e,reason:u.message})}if(!a.ok)throw new b(`Failed to download skill zip from url: ${e}`,{url:e,status:a.status,statusText:a.statusText});const r=a.headers.get("content-type")||"";r&&!r.includes("zip")&&!r.includes("octet-stream")&&i(c,"WARN","Downloaded skill url content-type is not typical zip",{url:e,contentType:r});const o=await a.arrayBuffer(),m=Buffer.from(o);await t.promises.writeFile(s,m)}async function K(e,s,c,a={}){const r=String(e),o=Date.now(),m=ne(c),u=[],f=[];if(!e)throw new h("Project ID cannot be empty",{field:"projectId"});if(!s&&m.length===0)throw new h("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(s){if(!s.path)throw new h("Uploaded file has no valid path",{field:"file.path"});if(p.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new h("Only zip files are supported",{field:"file",originalName:s?.originalname})}const w=N(String(e),a);if(!t.existsSync(w))throw new h("Project does not exist",{field:"projectId"});const{skillsDir:l,agentTypes:d}=await se(w),D=p.join(E.UPLOAD_PROJECT_DIR,"temp");try{await t.promises.mkdir(l,{recursive:!0}),await t.promises.mkdir(D,{recursive:!0});const n=new Set;if(s){const k=p.join(D,`project_skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);f.push(k),await t.promises.mkdir(k,{recursive:!0}),await _(s.path,k);const $=await le(k,"skills");if(!$)i(r,"WARN","skills directory not found in uploaded zip",{projectId:e,extractRoot:k});else{const F=(await t.promises.readdir($,{withFileTypes:!0})).filter(v=>v.isDirectory()&&!v.name.startsWith("."));for(const v of F){const T=p.join($,v.name),x=p.join(l,v.name);t.existsSync(x)&&await q(x),await H(T,x),n.add(v.name)}}}for(let k=0;k<m.length;k+=1){const $=m[k],S=p.join(D,`project_skill_url_${Date.now()}_${k}_${Math.round(Math.random()*1e6)}.zip`);u.push(S);const F=p.join(D,`project_skill_url_extract_${Date.now()}_${k}_${Math.round(Math.random()*1e6)}`);f.push(F),await t.promises.mkdir(F,{recursive:!0}),await ce($,S,r),await _(S,F);const T=(await t.promises.readdir(F,{withFileTypes:!0})).filter(g=>g.isDirectory()&&!g.name.startsWith(".")),B=T.find(g=>g.name==="skills")?(await t.promises.readdir(p.join(F,"skills"),{withFileTypes:!0})).filter(g=>g.isDirectory()&&!g.name.startsWith(".")).map(g=>({name:g.name,sourcePath:p.join(F,"skills",g.name)})):T.map(g=>({name:g.name,sourcePath:p.join(F,g.name)}));if(B.length===0){i(r,"WARN","No skill directory found after extracting skill url zip",{projectId:e,skillUrl:$,extractRoot:F});continue}for(const g of B){const z=p.join(l,g.name);t.existsSync(z)&&await q(z),await H(g.sourcePath,z),n.add(g.name)}}const y=Array.from(n),R=y.length>0?`Pushed ${y.length} skills: ${y.join(", ")}`:"No valid skill directories found in file or skillUrls",U=Date.now()-o;i(r,"INFO","Push skills to project workspace resources prepared",{projectId:e,updatedSkills:y,skillUrlsCount:m.length,hasFile:!!s,agentTypes:d,prepareElapsedMs:U});const I=await re(w,r);return i(r,"INFO","Push skills to project workspace completed",{projectId:e,updatedSkills:y,skillUrlsCount:m.length,hasFile:!!s,agentTypes:d,prepareElapsedMs:U,syncAgentsElapsedMs:I?.elapsedMs,elapsedMs:Date.now()-o}),{message:R,projectPath:w,updatedSkills:y}}catch(n){throw i(r,"ERROR","Push skills to project workspace failed",{projectId:e,error:n.message,elapsedMs:Date.now()-o}),n instanceof h||n instanceof b||n instanceof G||n instanceof P?n:new P(`Failed to push skills to project workspace: ${n.message}`,{projectId:e})}finally{const n=Date.now();for(const y of f)try{t.existsSync(y)&&await t.promises.rm(y,{recursive:!0,force:!0})}catch(R){i(r,"WARN","Failed to clean extracted skill temp dir",{extractRoot:y,error:R.message})}for(const y of u)try{t.existsSync(y)&&await t.promises.unlink(y)}catch(R){i(r,"WARN","Failed to clean downloaded skill zip",{zipPath:y,error:R.message})}try{s?.path&&t.existsSync(s.path)&&await t.promises.unlink(s.path)}catch(y){i(r,"WARN","Failed to clean uploaded skill zip",{tempZipPath:s?.path,error:y.message})}i(r,"INFO","Push skills to project workspace temp cleanup completed",{projectId:e,elapsedMs:Date.now()-n,totalElapsedMs:Date.now()-o})}}async function Q(e,s,c,a={}){const r=Date.now();if(!e)throw new h("Project ID cannot be empty",{field:"projectId"});const o=null;try{if(s&&!isNaN(Number(s))){const l=Number(s);i(o,"INFO",`[delete-project] Stopping development server, PID: ${l}`,{projectId:e,pid:l});try{await W(c,e,l,{strict:!0}),i(o,"INFO","[delete-project] Development server stopped",{projectId:e})}catch(d){i(o,"WARN",`[delete-project] Failed to stop development server: ${d.message}`,{projectId:e,pid:l})}}const m=[p.join(E.UPLOAD_PROJECT_DIR,e),N(e,a),p.join(E.DIST_TARGET_DIR,e),p.join(E.LOG_BASE_DIR,e)],u=[],f=[];for(const l of m)if(t.existsSync(l))try{await t.promises.rm(l,{recursive:!0,force:!0}),u.push(l),i(o,"INFO",`[delete-project] Directory deleted successfully: ${l}`,{projectId:e})}catch(d){f.push({path:l,error:d.message}),i(o,"ERROR",`[delete-project] Directory deleted failed: ${l}`,{projectId:e,error:d.message})}else i(o,"INFO",`[delete-project] Directory does not exist, skipping deletion: ${l}`,{projectId:e});const w={success:!0,message:`Project ${e} deleted successfully`,projectId:e,deletedDirectories:u,failedDirectories:f};return f.length>0&&(w.message+=`, but ${f.length} directories deleted failed`,i(o,"WARN","[delete-project] Some directories deleted failed",{projectId:e,failedDirs:f})),i(o,"INFO",`[delete-project] Project deleted successfully: ${e}`,{projectId:e,elapsedMs:Date.now()-r}),w}catch(m){throw i(o,"ERROR",`[delete-project] Failed to delete project: ${m.message}`,{projectId:e,originalError:m.message,elapsedMs:Date.now()-r}),m.isOperational?m:new P(`Failed to delete project: ${m.message}`,{projectId:e,originalError:m.message})}}async function Y(e,s,c,a,r={}){const o=Date.now();if(!e)throw new h("Project ID cannot be empty",{field:"projectId"});if(s==null)throw new h("codeVersion cannot be empty",{field:"codeVersion"});const m=Number(s);if(!Number.isFinite(m))throw new h("codeVersion must be a number",{field:"codeVersion"});const u=N(e,r);if(!t.existsSync(u))throw new A("Project does not exist",{projectId:e});const f=p.join(E.UPLOAD_PROJECT_DIR,e),w=`${e}-v${m}.zip`,l=p.join(f,w);if(c!=="LATEST"){if(t.existsSync(l))return i(e,"INFO",`Using existing export file: ${l}`,{projectId:e,zipPath:l}),{success:!0,projectId:e,zipPath:l};throw new A(`Specified version zip file does not exist: ${l}`,{projectId:e,zipPath:l})}const d=p.join(u,"cpage_config.json");let D=!1;try{if(a)try{const y=JSON.stringify(a,null,2);await t.promises.writeFile(d,y,"utf8"),D=!0,i(e,"INFO",`Configuration file created successfully: ${d}`,{projectId:e,configFilePath:d})}catch(y){throw i(e,"ERROR",`Failed to create configuration file: ${y.message}`,{projectId:e,error:y.message}),new b("Failed to create configuration file",{projectId:e,configFilePath:d,originalError:y.message})}i(e,"DEBUG","Start executing export and packaging",{projectId:e,codeVersion:s});const n=await O(e,s,r);return i(e,"INFO",`Project exported successfully: ${n}`,{projectId:e,zipPath:n,elapsedMs:Date.now()-o}),{success:!0,projectId:e,zipPath:n}}catch(n){throw i(e,"ERROR",`Failed to export project: ${n?.message}`,{projectId:e,elapsedMs:Date.now()-o}),n.isOperational?n:new P("Failed to export project",{projectId:e,originalError:n&&n.message?C(n.message):n&&n.message})}finally{if(D&&t.existsSync(d))try{await t.promises.unlink(d),i(e,"INFO",`Temporary configuration file deleted successfully: ${d}`,{projectId:e,configFilePath:d})}catch(n){i(e,"WARN",`Failed to delete temporary configuration file: ${n.message}`,{projectId:e,error:n.message})}}}async function j(e,s,c={}){const a=Date.now();if(!e)throw new h("Project ID cannot be empty",{field:"projectId"});if(s==null)throw new h("codeVersion cannot be empty",{field:"codeVersion"});try{const r=await O(e,s,c);return i(e,"INFO",`Current version backed up successfully: ${r}`,{projectId:e,zipPath:r,elapsedMs:Date.now()-a}),{success:!0,projectId:e,zipPath:r}}catch(r){throw i(e,"ERROR",`Failed to backup current version: ${r?.message}`,{projectId:e,elapsedMs:Date.now()-a}),r.isOperational?r:new P("Failed to backup current version",{projectId:e,originalError:r&&r.message?C(r.message):r&&r.message})}}export{Z as createProject,V as uploadProject,j as backupCurrentVersion,Y as exportProject,O as backupProjectOfVersion,M as cleanupProjectDirectory,X as handleFileUpload,K as pushSkillsToWorkspace,Q as deleteProject};export default{createProject:Z,uploadProject:V,backupCurrentVersion:j,exportProject:Y,backupProjectOfVersion:O,cleanupProjectDirectory:M,handleFileUpload:X,pushSkillsToWorkspace:K,deleteProject:Q};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"fs";import n from"path";import{log as D}from"../log/logUtils.js";const d={agents:".agents",claudecode:".claude",opencode:".opencode",codex:".codex"},y=Object.keys(d),A="agents";async function x(t){e.existsSync(t)&&await e.promises.rm(t,{recursive:!0,force:!0})}async function a(t){e.existsSync(t)||await e.promises.mkdir(t,{recursive:!0})}async function j(t,s){if((await e.promises.lstat(t)).isDirectory()){await a(s);const o=await e.promises.readdir(t);for(const i of o)await j(n.join(t,i),n.join(s,i))}else await a(n.dirname(s)),await e.promises.copyFile(t,s)}async function P(t){const s=n.join(t,d[A]),r=n.join(s,"skills"),o=n.join(s,"agents");return await a(s),await a(r),await a(o),{rootDir:s,skillsDir:r,agentsDir:o,agentTypes:y}}async function S(t,s){const r=Date.now(),o=s||n.basename(t)||"syncAgents";D(o,"INFO","Start syncAgents",{workspaceRoot:t,targetAgentTypes:y.filter(f=>f!==A)});const i=await P(t);for(const f of y){if(f===A)continue;const l=n.join(t,d[f]),m=n.join(l,"skills"),g=n.join(l,"agents");if(await a(l),await x(m),await a(m),e.existsSync(i.skillsDir)){const p=await e.promises.readdir(i.skillsDir,{withFileTypes:!0});for(const c of p){const u=n.join(i.skillsDir,c.name),w=n.join(m,c.name);await j(u,w)}}if(await x(g),await a(g),e.existsSync(i.agentsDir)){const p=await e.promises.readdir(i.agentsDir,{withFileTypes:!0});for(const c of p){const u=n.join(i.agentsDir,c.name),w=n.join(g,c.name);await j(u,w)}}}const T=Date.now()-r;return D(o,"INFO","syncAgents completed",{workspaceRoot:t,agentTypes:y,elapsedMs:T}),{agentTypes:y,elapsedMs:T}}export{P as ensurePrimaryAgentDirs,S as syncAgents};
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import n from"fs";import l from"path";import{exec as ae}from"child_process";import le from"cross-spawn";import ce from"archiver";import M from"../../appConfig/index.js";import{extractZip as L}from"../common/zipUtils.js";import{ValidationError as u,SystemError as $,FileError as U}from"../error/errorHandler.js";import{log as r}from"../log/logUtils.js";import{createPnpmNpmrc as pe}from"../common/npmrcUtils.js";import{ensurePrimaryAgentDirs as I,syncAgents as V}from"../common/AgentWorkspaceUtils.js";import{writeAgentHookConfigs as de}from"./hookConfigUtils.js";function ee(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{const i=JSON.parse(t);if(Array.isArray(i))return i.map(o=>typeof o=="string"?o.trim():"").filter(Boolean)}catch{}return[t]}return[]}async function te(e,t,i){let o;try{o=await fetch(e)}catch(y){throw new U(`Failed to download skill zip from url: ${e}`,{url:e,reason:y.message})}if(!o.ok)throw new U(`Failed to download skill zip from url: ${e}`,{url:e,status:o.status,statusText:o.statusText});const s=o.headers.get("content-type")||"";s&&!s.includes("zip")&&!s.includes("octet-stream")&&r(i,"WARN","Downloaded skill url content-type is not typical zip",{url:e,contentType:s});const a=await o.arrayBuffer(),d=Buffer.from(a);await n.promises.writeFile(t,d)}async function A(e="computer"){const t=M.COMPUTER_WORKSPACE_DIR;if(!t)throw new u("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});return n.existsSync(t)||(await n.promises.mkdir(t,{recursive:!0}),r(e,"INFO","Created user workspace root directory",{workspaceRoot:t})),t}async function q(e,t){const i=l.join(e,t);if(n.existsSync(i)&&(await n.promises.lstat(i)).isDirectory())return i;const o=await n.promises.readdir(e,{withFileTypes:!0});for(const s of o){if(!s.isDirectory())continue;const a=l.join(e,s.name),d=l.join(a,t);if(n.existsSync(d)&&(await n.promises.lstat(d)).isDirectory())return d}return null}async function Le(e){return q(e,"skills")}const me=".dynamic_add.lock";function fe(e){const t=l.join(e,me);return n.existsSync(t)&&n.statSync(t).isFile()}async function b(e){n.existsSync(e)&&await n.promises.rm(e,{recursive:!0,force:!0})}async function T(e,t){try{await n.promises.rename(e,t)}catch(i){if(i.code==="EXDEV"){async function o(s,a){if((await n.promises.lstat(s)).isDirectory()){await n.promises.mkdir(a,{recursive:!0});const y=await n.promises.readdir(s);for(const c of y)await o(l.join(s,c),l.join(a,c))}else await n.promises.copyFile(s,a)}await o(e,t),await n.promises.rm(e,{recursive:!0,force:!0})}else throw i}}async function ue(e,t,i,o,s,a,d,y){const c=Date.now(),p=`computer:${e}:${t}`,w=ee(o),m=[],g=[],R=new Set;if(!e)throw new u("userId cannot be empty",{field:"userId"});if(!t)throw new u("cId cannot be empty",{field:"cId"});const f=await A(p),D=l.join(f,String(e),String(t),".tmp"),E=l.join(f,String(e),String(t)),{skillsDir:k,agentsDir:_,agentTypes:F}=await I(E);n.existsSync(E)||await n.promises.mkdir(E,{recursive:!0});const N=l.join(D,`preserved_skills_${Date.now()}_${Math.round(Math.random()*1e6)}`);if(n.existsSync(k)){const P=(await n.promises.readdir(k,{withFileTypes:!0})).filter(S=>S.isDirectory()&&fe(l.join(k,S.name)));if(P.length>0){await n.promises.mkdir(N,{recursive:!0});for(const S of P){const x=l.join(k,S.name),z=l.join(N,S.name);await T(x,z)}r(p,"INFO","\u4FDD\u7559\u542B .dynamic_add.lock \u7684 skill",{preserved:P.map(S=>S.name)})}}if(await b(k),await b(_),await n.promises.mkdir(k,{recursive:!0}),await n.promises.mkdir(_,{recursive:!0}),n.existsSync(N)){const h=await n.promises.readdir(N,{withFileTypes:!0});for(const P of h)if(P.isDirectory()){const S=l.join(N,P.name),x=l.join(k,P.name);await T(S,x)}await b(N)}const O=n.existsSync(k),C=n.existsSync(_);if(r(p,"INFO","Deleted old skills and agents directories completed",{userId:e,cId:t,targetSkillsDir:k,targetAgentsDir:_,agentTypes:F,skillsExists:O,agentsExists:C}),await de(E,{mcpServersConfig:s,hooksConfig:d,permissionsConfig:a,hookScripts:y},p),!i&&w.length===0)return await V(E),r(p,"INFO","Created workspace (no uploaded file, no skills and agents)",{userId:e,cId:t,workspaceRoot:f,skillsDir:null,agentsDir:null,agentTypes:F,elapsedMs:Date.now()-c}),{message:"Workspace created (no uploaded file, no skills and agents)",workspaceRoot:f};if(i){if(!i.path)throw new u("Uploaded file has no valid path",{field:"file.path"});if(l.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new u("Only zip files are supported",{field:"file",originalName:i.originalname})}r(p,"DEBUG","Start processing workspace resources",{userId:e,cId:t,workspaceRoot:f,hasUploadedZip:!!i,skillUrlsCount:w.length});try{n.existsSync(D)||await n.promises.mkdir(D,{recursive:!0});const h=[];if(i){const x=l.join(D,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);g.push(x),await n.promises.mkdir(x,{recursive:!0}),r(p,"DEBUG","Start extracting uploaded zip file",{extractRoot:x}),await L(i.path,x),r(p,"DEBUG","Uploaded zip file extracted successfully",{extractRoot:x});const z=await q(x,"skills"),W=await q(x,"agents");if(z){await n.promises.mkdir(k,{recursive:!0});const v=await n.promises.readdir(z,{withFileTypes:!0});for(const B of v){if(!B.isDirectory())continue;const G=l.join(z,B.name),Z=l.join(k,B.name);n.existsSync(Z)&&await b(Z),await T(G,Z),R.add(B.name)}h.push("skills"),r(p,"INFO","skills updated to workspace",{userId:e,cId:t,workspaceRoot:f,targetSkillsDir:k,agentTypes:F})}else r(p,"INFO","skills directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:x});W?(await b(_),await T(W,_),h.push("agents"),r(p,"INFO","agents updated to workspace",{userId:e,cId:t,workspaceRoot:f,targetAgentsDir:_,agentTypes:F})):r(p,"INFO","agents directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:x})}for(let x=0;x<w.length;x+=1){const z=w[x],W=l.join(D,`skill_url_${Date.now()}_${x}_${Math.round(Math.random()*1e6)}.zip`);m.push(W);const v=l.join(D,`skill_url_extract_${Date.now()}_${x}_${Math.round(Math.random()*1e6)}`);g.push(v),await n.promises.mkdir(v,{recursive:!0}),r(p,"INFO","Start download skill zip from url",{userId:e,cId:t,skillUrl:z}),await te(z,W,p),r(p,"INFO","Skill zip downloaded, start extracting",{userId:e,cId:t,skillUrl:z,downloadedZipPath:W}),await L(W,v);const G=(await n.promises.readdir(v,{withFileTypes:!0})).filter(j=>j.isDirectory()&&!j.name.startsWith(".")),Q=G.find(j=>j.name==="skills")?(await n.promises.readdir(l.join(v,"skills"),{withFileTypes:!0})).filter(j=>j.isDirectory()&&!j.name.startsWith(".")).map(j=>({name:j.name,sourcePath:l.join(v,"skills",j.name)})):G.map(j=>({name:j.name,sourcePath:l.join(v,j.name)}));if(Q.length===0){r(p,"WARN","No skill directory found after extracting skill url zip",{userId:e,cId:t,skillUrl:z,extractRoot:v});continue}await n.promises.mkdir(k,{recursive:!0});for(const j of Q){const K=l.join(k,j.name);n.existsSync(K)&&await b(K),await T(j.sourcePath,K),R.add(j.name),r(p,"INFO","Skill from url updated to workspace",{userId:e,cId:t,skillUrl:z,skillName:j.name,destSkillPath:K})}h.includes("skills")||h.push("skills")}h.length===0&&r(p,"WARN","No valid skills or agents directories found",{userId:e,cId:t,hasUploadedZip:!!i,skillUrlsCount:w.length});const P=Array.from(R),S=h.length>0?`Workspace created successfully, ${h.join(" and ")} updated`:"Workspace created successfully (skills and agents directories not found)";return r(p,"INFO",S,{userId:e,cId:t,updatedDirs:h,updatedSkills:P,agentTypes:F,elapsedMs:Date.now()-c}),await V(E),{message:S,workspaceRoot:f,updatedSkills:P}}catch(h){throw r(p,"ERROR","Failed to process workspace resources",{userId:e,cId:t,error:h.message,elapsedMs:Date.now()-c}),h instanceof u||h instanceof U||h instanceof $?h:new $(`Failed to create workspace: ${h.message}`,{userId:e,cId:t})}finally{try{for(const h of g)n.existsSync(h)&&await n.promises.rm(h,{recursive:!0,force:!0})}catch(h){r(p,"WARN","Failed to clean up temporary extracted zip",{error:h.message})}for(const h of m)try{n.existsSync(h)&&await n.promises.unlink(h)}catch(P){r(p,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:h,error:P.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(h){r(p,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:h.message})}}}async function we(e,t,i,o){const s=Date.now(),a=`computer:${e}:${t}`,d=ee(o),y=[],c=[];if(!e)throw new u("userId cannot be empty",{field:"userId"});if(!t)throw new u("cId cannot be empty",{field:"cId"});if(!i&&d.length===0)throw new u("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(i){if(!i.path)throw new u("Uploaded file has no valid path",{field:"file.path"});if(l.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new u("Only zip files are supported",{field:"file",originalName:i?.originalname})}const p=await A(a),w=l.join(p,String(e),String(t),".tmp"),m=l.join(p,String(e),String(t)),{skillsDir:g,agentTypes:R}=await I(m);try{n.existsSync(m)||await n.promises.mkdir(m,{recursive:!0}),n.existsSync(g)||await n.promises.mkdir(g,{recursive:!0}),n.existsSync(w)||await n.promises.mkdir(w,{recursive:!0});const f=[],D=new Set;if(i){const k=l.join(w,`skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);c.push(k),await n.promises.mkdir(k,{recursive:!0}),r(a,"DEBUG","Start extracting skill zip file",{extractRoot:k}),await L(i.path,k),r(a,"DEBUG","Skill zip file extracted successfully",{extractRoot:k});const _=await q(k,"skills");if(!_)r(a,"WARN","skills directory not found in uploaded zip",{userId:e,cId:t,extractRoot:k});else{const N=(await n.promises.readdir(_,{withFileTypes:!0})).filter(O=>O.isDirectory()&&!O.name.startsWith("."));if(N.length===0)r(a,"WARN","skills directory in uploaded zip has no skill subdirectories",{userId:e,cId:t,skillsDir:_});else for(const O of N){const C=l.join(_,O.name),h=l.join(g,O.name);n.existsSync(h)&&await b(h),await T(C,h),D.add(O.name),r(a,"INFO","skill pushed to workspace from uploaded zip",{userId:e,cId:t,skillName:O.name,destSkillPath:h})}}}for(let k=0;k<d.length;k+=1){const _=d[k],F=l.join(w,`skill_push_url_${Date.now()}_${k}_${Math.round(Math.random()*1e6)}.zip`);y.push(F);const N=l.join(w,`skill_push_url_extract_${Date.now()}_${k}_${Math.round(Math.random()*1e6)}`);c.push(N),await n.promises.mkdir(N,{recursive:!0}),r(a,"INFO","Start download skill zip for push from url",{userId:e,cId:t,skillUrl:_}),await te(_,F,a),await L(F,N);const C=(await n.promises.readdir(N,{withFileTypes:!0})).filter(S=>S.isDirectory()&&!S.name.startsWith(".")),P=C.find(S=>S.name==="skills")?(await n.promises.readdir(l.join(N,"skills"),{withFileTypes:!0})).filter(S=>S.isDirectory()&&!S.name.startsWith(".")).map(S=>({name:S.name,sourcePath:l.join(N,"skills",S.name)})):C.map(S=>({name:S.name,sourcePath:l.join(N,S.name)}));if(P.length===0){r(a,"WARN","No skill directory found after extracting push skill url zip",{userId:e,cId:t,skillUrl:_,extractRoot:N});continue}for(const S of P){const x=l.join(g,S.name);n.existsSync(x)&&await b(x),await T(S.sourcePath,x),D.add(S.name),r(a,"INFO","skill pushed to workspace from url zip",{userId:e,cId:t,skillUrl:_,skillName:S.name,destSkillPath:x})}}for(const k of D)f.push(k);const E=f.length>0?`Pushed ${f.length} skills: ${f.join(", ")}`:"No valid skill directories found in file or skillUrls";return r(a,"INFO",E,{userId:e,cId:t,updatedSkills:f,agentTypes:R,elapsedMs:Date.now()-s}),await V(m),{message:E,workspaceRoot:p,updatedSkills:f}}catch(f){throw r(a,"ERROR","Failed to push skill to workspace",{userId:e,cId:t,error:f.message,elapsedMs:Date.now()-s}),f instanceof u||f instanceof U||f instanceof $?f:new $(`Failed to push skill to workspace: ${f.message}`,{userId:e,cId:t})}finally{try{for(const f of c)n.existsSync(f)&&await n.promises.rm(f,{recursive:!0,force:!0})}catch(f){r(a,"WARN","Failed to clean up temporary extracted zip",{error:f.message})}for(const f of y)try{n.existsSync(f)&&await n.promises.unlink(f)}catch(D){r(a,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:f,error:D.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(f){r(a,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:f.message})}}}async function ge(e,t,i,o){const s=Date.now(),a=`computer:${e}:${t}`;if(!e)throw new u("userId cannot be empty",{field:"userId"});if(!t)throw new u("cId cannot be empty",{field:"cId"});if(!i||!i.path)throw new u("file is required",{field:"file"});if(l.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new u("Only zip files are supported",{field:"file",originalName:i.originalname});const y=await A(a),c=l.join(y,String(e),String(t)),p=l.join(c,".tmp"),w=l.join(p,`template_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{n.existsSync(c)||await n.promises.mkdir(c,{recursive:!0}),n.existsSync(p)||await n.promises.mkdir(p,{recursive:!0}),await n.promises.mkdir(w,{recursive:!0}),r(a,"DEBUG","Start extracting template zip file",{extractRoot:w}),await L(i.path,w),r(a,"DEBUG","Template zip file extracted successfully",{extractRoot:w});const m=await n.promises.readdir(w,{withFileTypes:!0});for(const g of m){const R=l.join(w,g.name),f=l.join(c,g.name);if(g.isDirectory())await T(R,f);else{const D=l.dirname(f);n.existsSync(D)||await n.promises.mkdir(D,{recursive:!0}),await n.promises.copyFile(R,f)}}if(r(a,"INFO","Template files extracted to workspace",{userId:e,cId:t,targetDir:c,fileCount:m.length}),M.GIT_ENABLED&&(o==="true"||o===!0)){const g=await import("../../service/gitService.js");await g.default.init({workspaceType:"taskAgent",userId:e,cId:t}),await g.default.commit({workspaceType:"taskAgent",userId:e,cId:t,message:"Initial commit"}),r(a,"INFO","Git init and initial commit done",{userId:e,cId:t})}return r(a,"INFO","Init project template completed",{userId:e,cId:t,targetDir:c,elapsedMs:Date.now()-s}),{message:"Project template initialized successfully",workspaceRoot:c}}catch(m){throw r(a,"ERROR","Failed to init project template",{userId:e,cId:t,error:m.message,elapsedMs:Date.now()-s}),m instanceof u||m instanceof U||m instanceof $?m:new $(`Failed to init project template: ${m.message}`,{userId:e,cId:t})}finally{try{n.existsSync(w)&&await n.promises.rm(w,{recursive:!0,force:!0})}catch(m){r(a,"WARN","Failed to clean up temporary extracted zip",{error:m.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(m){r(a,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:m.message})}}}async function he(e,t,i){if(!e)throw new u("userId cannot be empty",{field:"userId"});if(!t)throw new u("cId cannot be empty",{field:"cId"});if(!i||typeof i!="string"||!i.trim())throw new u("command cannot be empty",{field:"command"});const o=await A("computer"),s=l.join(o,String(e),String(t));if(!n.existsSync(s))throw new u("workspace directory does not exist",{field:"workDir",workDir:s});const a=`computer:${e}:${t}`;r(a,"INFO","Execute command in workspace",{userId:e,cId:t,workDir:s,command:i});const d=10*60*1e3,y={cwd:s,timeout:d,maxBuffer:50*1024*1024};return M.BASH_PATH&&(y.shell=M.BASH_PATH),new Promise((c,p)=>{ae(i,y,(w,m,g)=>{const R=w?w.killed?-1:w.code||1:0,f=w&&w.killed?(g||"")+`
|
|
2
|
-
Command timed out after ${d/1e3}s`:
|
|
3
|
-
Failed to spawn ${e}: ${
|
|
4
|
-
Process killed by signal ${
|
|
5
|
-
`);for(const
|
|
6
|
-
`,"utf8"),
|
|
7
|
-
`),
|
|
8
|
-
`),"utf8"),
|
|
1
|
+
import n from"fs";import l from"path";import{exec as ce}from"child_process";import pe from"cross-spawn";import de from"archiver";import L from"../../appConfig/index.js";import{extractZip as G}from"../common/zipUtils.js";import{ValidationError as f,SystemError as C,FileError as Z}from"../error/errorHandler.js";import{log as a}from"../log/logUtils.js";import{createPnpmNpmrc as me}from"../common/npmrcUtils.js";import{ensurePrimaryAgentDirs as te,syncAgents as X}from"../common/AgentWorkspaceUtils.js";import{writeAgentHookConfigs as fe}from"./hookConfigUtils.js";function ie(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{const i=JSON.parse(t);if(Array.isArray(i))return i.map(o=>typeof o=="string"?o.trim():"").filter(Boolean)}catch{}return[t]}return[]}async function ne(e,t,i){let o;try{o=await fetch(e)}catch(h){throw new Z(`Failed to download skill zip from url: ${e}`,{url:e,reason:h.message})}if(!o.ok)throw new Z(`Failed to download skill zip from url: ${e}`,{url:e,status:o.status,statusText:o.statusText});const s=o.headers.get("content-type")||"";s&&!s.includes("zip")&&!s.includes("octet-stream")&&a(i,"WARN","Downloaded skill url content-type is not typical zip",{url:e,contentType:s});const r=await o.arrayBuffer(),d=Buffer.from(r);await n.promises.writeFile(t,d)}async function T(e="computer"){const t=L.COMPUTER_WORKSPACE_DIR;if(!t)throw new f("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});return n.existsSync(t)||(await n.promises.mkdir(t,{recursive:!0}),a(e,"INFO","Created user workspace root directory",{workspaceRoot:t})),t}async function H(e,t){const i=l.join(e,t);if(n.existsSync(i)&&(await n.promises.lstat(i)).isDirectory())return i;const o=await n.promises.readdir(e,{withFileTypes:!0});for(const s of o){if(!s.isDirectory())continue;const r=l.join(e,s.name),d=l.join(r,t);if(n.existsSync(d)&&(await n.promises.lstat(d)).isDirectory())return d}return null}async function Ge(e){return H(e,"skills")}const ue=".dynamic_add.lock";function we(e){const t=l.join(e,ue);return n.existsSync(t)&&n.statSync(t).isFile()}async function W(e){n.existsSync(e)&&await n.promises.rm(e,{recursive:!0,force:!0})}async function M(e,t){try{await n.promises.rename(e,t)}catch(i){if(i.code==="EXDEV"){async function o(s,r){if((await n.promises.lstat(s)).isDirectory()){await n.promises.mkdir(r,{recursive:!0});const h=await n.promises.readdir(s);for(const p of h)await o(l.join(s,p),l.join(r,p))}else await n.promises.copyFile(s,r)}await o(e,t),await n.promises.rm(e,{recursive:!0,force:!0})}else throw i}}async function ge(e,t,i,o,s,r,d,h){const p=Date.now(),c=`computer:${e}:${t}`,u=ie(o),m=[],w=[],N=new Set;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});const g=await T(c),k=l.join(g,String(e),String(t),".tmp"),F=l.join(g,String(e),String(t)),{skillsDir:P,agentsDir:z,agentTypes:x}=await te(F);n.existsSync(F)||await n.promises.mkdir(F,{recursive:!0});const j=l.join(k,`preserved_skills_${Date.now()}_${Math.round(Math.random()*1e6)}`);if(n.existsSync(P)){const S=(await n.promises.readdir(P,{withFileTypes:!0})).filter(R=>R.isDirectory()&&we(l.join(P,R.name)));if(S.length>0){await n.promises.mkdir(j,{recursive:!0});for(const R of S){const A=l.join(P,R.name),D=l.join(j,R.name);await M(A,D)}a(c,"INFO","\u4FDD\u7559\u542B .dynamic_add.lock \u7684 skill",{preserved:S.map(R=>R.name)})}}if(await W(P),await W(z),await n.promises.mkdir(P,{recursive:!0}),await n.promises.mkdir(z,{recursive:!0}),n.existsSync(j)){const y=await n.promises.readdir(j,{withFileTypes:!0});for(const S of y)if(S.isDirectory()){const R=l.join(j,S.name),A=l.join(P,S.name);await M(R,A)}await W(j)}const b=n.existsSync(P),O=n.existsSync(z);if(a(c,"INFO","Deleted old skills and agents directories completed",{userId:e,cId:t,targetSkillsDir:P,targetAgentsDir:z,agentTypes:x,skillsExists:b,agentsExists:O}),await fe(F,{mcpServersConfig:s,hooksConfig:d,permissionsConfig:r,hookScripts:h},c),!i&&u.length===0){const y=await X(F,c);return a(c,"INFO","Created workspace (no uploaded file, no skills and agents)",{userId:e,cId:t,workspaceRoot:g,skillsDir:null,agentsDir:null,agentTypes:x,syncAgentsElapsedMs:y?.elapsedMs,elapsedMs:Date.now()-p}),{message:"Workspace created (no uploaded file, no skills and agents)",workspaceRoot:g}}if(i){if(!i.path)throw new f("Uploaded file has no valid path",{field:"file.path"});if(l.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new f("Only zip files are supported",{field:"file",originalName:i.originalname})}a(c,"DEBUG","Start processing workspace resources",{userId:e,cId:t,workspaceRoot:g,hasUploadedZip:!!i,skillUrlsCount:u.length});try{n.existsSync(k)||await n.promises.mkdir(k,{recursive:!0});const y=[];if(i){const _=l.join(k,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);w.push(_),await n.promises.mkdir(_,{recursive:!0}),a(c,"DEBUG","Start extracting uploaded zip file",{extractRoot:_}),await G(i.path,_),a(c,"DEBUG","Uploaded zip file extracted successfully",{extractRoot:_});const $=await H(_,"skills"),B=await H(_,"agents");if($){await n.promises.mkdir(P,{recursive:!0});const v=await n.promises.readdir($,{withFileTypes:!0});for(const U of v){if(!U.isDirectory())continue;const K=l.join($,U.name),q=l.join(P,U.name);n.existsSync(q)&&await W(q),await M(K,q),N.add(U.name)}y.push("skills"),a(c,"INFO","skills updated to workspace",{userId:e,cId:t,workspaceRoot:g,targetSkillsDir:P,agentTypes:x})}else a(c,"INFO","skills directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:_});B?(await W(z),await M(B,z),y.push("agents"),a(c,"INFO","agents updated to workspace",{userId:e,cId:t,workspaceRoot:g,targetAgentsDir:z,agentTypes:x})):a(c,"INFO","agents directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:_})}for(let _=0;_<u.length;_+=1){const $=u[_],B=l.join(k,`skill_url_${Date.now()}_${_}_${Math.round(Math.random()*1e6)}.zip`);m.push(B);const v=l.join(k,`skill_url_extract_${Date.now()}_${_}_${Math.round(Math.random()*1e6)}`);w.push(v),await n.promises.mkdir(v,{recursive:!0}),a(c,"INFO","Start download skill zip from url",{userId:e,cId:t,skillUrl:$}),await ne($,B,c),a(c,"INFO","Skill zip downloaded, start extracting",{userId:e,cId:t,skillUrl:$,downloadedZipPath:B}),await G(B,v);const K=(await n.promises.readdir(v,{withFileTypes:!0})).filter(E=>E.isDirectory()&&!E.name.startsWith(".")),ee=K.find(E=>E.name==="skills")?(await n.promises.readdir(l.join(v,"skills"),{withFileTypes:!0})).filter(E=>E.isDirectory()&&!E.name.startsWith(".")).map(E=>({name:E.name,sourcePath:l.join(v,"skills",E.name)})):K.map(E=>({name:E.name,sourcePath:l.join(v,E.name)}));if(ee.length===0){a(c,"WARN","No skill directory found after extracting skill url zip",{userId:e,cId:t,skillUrl:$,extractRoot:v});continue}await n.promises.mkdir(P,{recursive:!0});for(const E of ee){const J=l.join(P,E.name);n.existsSync(J)&&await W(J),await M(E.sourcePath,J),N.add(E.name),a(c,"INFO","Skill from url updated to workspace",{userId:e,cId:t,skillUrl:$,skillName:E.name,destSkillPath:J})}y.includes("skills")||y.push("skills")}y.length===0&&a(c,"WARN","No valid skills or agents directories found",{userId:e,cId:t,hasUploadedZip:!!i,skillUrlsCount:u.length});const S=Array.from(N),R=y.length>0?`Workspace created successfully, ${y.join(" and ")} updated`:"Workspace created successfully (skills and agents directories not found)",A=Date.now()-p;a(c,"INFO","Workspace resources prepared",{userId:e,cId:t,updatedDirs:y,updatedSkills:S,agentTypes:x,prepareElapsedMs:A});const D=await X(F,c);return a(c,"INFO",R,{userId:e,cId:t,updatedDirs:y,updatedSkills:S,agentTypes:x,prepareElapsedMs:A,syncAgentsElapsedMs:D?.elapsedMs,elapsedMs:Date.now()-p}),{message:R,workspaceRoot:g,updatedSkills:S}}catch(y){throw a(c,"ERROR","Failed to process workspace resources",{userId:e,cId:t,error:y.message,elapsedMs:Date.now()-p}),y instanceof f||y instanceof Z||y instanceof C?y:new C(`Failed to create workspace: ${y.message}`,{userId:e,cId:t})}finally{const y=Date.now();try{for(const S of w)n.existsSync(S)&&await n.promises.rm(S,{recursive:!0,force:!0})}catch(S){a(c,"WARN","Failed to clean up temporary extracted zip",{error:S.message})}for(const S of m)try{n.existsSync(S)&&await n.promises.unlink(S)}catch(R){a(c,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:S,error:R.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(S){a(c,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:S.message})}a(c,"INFO","Workspace temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-y,totalElapsedMs:Date.now()-p})}}async function he(e,t,i,o){const s=Date.now(),r=`computer:${e}:${t}`,d=ie(o),h=[],p=[];if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!i&&d.length===0)throw new f("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(i){if(!i.path)throw new f("Uploaded file has no valid path",{field:"file.path"});if(l.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new f("Only zip files are supported",{field:"file",originalName:i?.originalname})}const c=await T(r),u=l.join(c,String(e),String(t),".tmp"),m=l.join(c,String(e),String(t)),{skillsDir:w,agentTypes:N}=await te(m);try{n.existsSync(m)||await n.promises.mkdir(m,{recursive:!0}),n.existsSync(w)||await n.promises.mkdir(w,{recursive:!0}),n.existsSync(u)||await n.promises.mkdir(u,{recursive:!0});const g=[],k=new Set;if(i){const x=l.join(u,`skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);p.push(x),await n.promises.mkdir(x,{recursive:!0}),a(r,"DEBUG","Start extracting skill zip file",{extractRoot:x}),await G(i.path,x),a(r,"DEBUG","Skill zip file extracted successfully",{extractRoot:x});const j=await H(x,"skills");if(!j)a(r,"WARN","skills directory not found in uploaded zip",{userId:e,cId:t,extractRoot:x});else{const O=(await n.promises.readdir(j,{withFileTypes:!0})).filter(y=>y.isDirectory()&&!y.name.startsWith("."));if(O.length===0)a(r,"WARN","skills directory in uploaded zip has no skill subdirectories",{userId:e,cId:t,skillsDir:j});else for(const y of O){const S=l.join(j,y.name),R=l.join(w,y.name);n.existsSync(R)&&await W(R),await M(S,R),k.add(y.name),a(r,"INFO","skill pushed to workspace from uploaded zip",{userId:e,cId:t,skillName:y.name,destSkillPath:R})}}}for(let x=0;x<d.length;x+=1){const j=d[x],b=l.join(u,`skill_push_url_${Date.now()}_${x}_${Math.round(Math.random()*1e6)}.zip`);h.push(b);const O=l.join(u,`skill_push_url_extract_${Date.now()}_${x}_${Math.round(Math.random()*1e6)}`);p.push(O),await n.promises.mkdir(O,{recursive:!0}),a(r,"INFO","Start download skill zip for push from url",{userId:e,cId:t,skillUrl:j}),await ne(j,b,r),await G(b,O);const S=(await n.promises.readdir(O,{withFileTypes:!0})).filter(D=>D.isDirectory()&&!D.name.startsWith(".")),A=S.find(D=>D.name==="skills")?(await n.promises.readdir(l.join(O,"skills"),{withFileTypes:!0})).filter(D=>D.isDirectory()&&!D.name.startsWith(".")).map(D=>({name:D.name,sourcePath:l.join(O,"skills",D.name)})):S.map(D=>({name:D.name,sourcePath:l.join(O,D.name)}));if(A.length===0){a(r,"WARN","No skill directory found after extracting push skill url zip",{userId:e,cId:t,skillUrl:j,extractRoot:O});continue}for(const D of A){const _=l.join(w,D.name);n.existsSync(_)&&await W(_),await M(D.sourcePath,_),k.add(D.name),a(r,"INFO","skill pushed to workspace from url zip",{userId:e,cId:t,skillUrl:j,skillName:D.name,destSkillPath:_})}}for(const x of k)g.push(x);const F=g.length>0?`Pushed ${g.length} skills: ${g.join(", ")}`:"No valid skill directories found in file or skillUrls",P=Date.now()-s;a(r,"INFO","Push skills resources prepared",{userId:e,cId:t,updatedSkills:g,agentTypes:N,prepareElapsedMs:P});const z=await X(m,r);return a(r,"INFO",F,{userId:e,cId:t,updatedSkills:g,agentTypes:N,prepareElapsedMs:P,syncAgentsElapsedMs:z?.elapsedMs,elapsedMs:Date.now()-s}),{message:F,workspaceRoot:c,updatedSkills:g}}catch(g){throw a(r,"ERROR","Failed to push skill to workspace",{userId:e,cId:t,error:g.message,elapsedMs:Date.now()-s}),g instanceof f||g instanceof Z||g instanceof C?g:new C(`Failed to push skill to workspace: ${g.message}`,{userId:e,cId:t})}finally{const g=Date.now();try{for(const k of p)n.existsSync(k)&&await n.promises.rm(k,{recursive:!0,force:!0})}catch(k){a(r,"WARN","Failed to clean up temporary extracted zip",{error:k.message})}for(const k of h)try{n.existsSync(k)&&await n.promises.unlink(k)}catch(F){a(r,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:k,error:F.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(k){a(r,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:k.message})}a(r,"INFO","Push skills temp cleanup completed",{userId:e,cId:t,elapsedMs:Date.now()-g,totalElapsedMs:Date.now()-s})}}async function ye(e,t,i,o){const s=Date.now(),r=`computer:${e}:${t}`;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!i||!i.path)throw new f("file is required",{field:"file"});if(l.extname(i.originalname||i.filename||"").toLowerCase()!==".zip")throw new f("Only zip files are supported",{field:"file",originalName:i.originalname});const h=await T(r),p=l.join(h,String(e),String(t)),c=l.join(p,".tmp"),u=l.join(c,`template_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{n.existsSync(p)||await n.promises.mkdir(p,{recursive:!0}),n.existsSync(c)||await n.promises.mkdir(c,{recursive:!0}),await n.promises.mkdir(u,{recursive:!0}),a(r,"DEBUG","Start extracting template zip file",{extractRoot:u}),await G(i.path,u),a(r,"DEBUG","Template zip file extracted successfully",{extractRoot:u});const m=await n.promises.readdir(u,{withFileTypes:!0});for(const w of m){const N=l.join(u,w.name),g=l.join(p,w.name);if(w.isDirectory())await M(N,g);else{const k=l.dirname(g);n.existsSync(k)||await n.promises.mkdir(k,{recursive:!0}),await n.promises.copyFile(N,g)}}if(a(r,"INFO","Template files extracted to workspace",{userId:e,cId:t,targetDir:p,fileCount:m.length}),L.GIT_ENABLED&&(o==="true"||o===!0)){const w=await import("../../service/gitService.js");await w.default.init({workspaceType:"taskAgent",userId:e,cId:t}),await w.default.commit({workspaceType:"taskAgent",userId:e,cId:t,message:"Initial commit"}),a(r,"INFO","Git init and initial commit done",{userId:e,cId:t})}return a(r,"INFO","Init project template completed",{userId:e,cId:t,targetDir:p,elapsedMs:Date.now()-s}),{message:"Project template initialized successfully",workspaceRoot:p}}catch(m){throw a(r,"ERROR","Failed to init project template",{userId:e,cId:t,error:m.message,elapsedMs:Date.now()-s}),m instanceof f||m instanceof Z||m instanceof C?m:new C(`Failed to init project template: ${m.message}`,{userId:e,cId:t})}finally{try{n.existsSync(u)&&await n.promises.rm(u,{recursive:!0,force:!0})}catch(m){a(r,"WARN","Failed to clean up temporary extracted zip",{error:m.message})}try{i&&i.path&&n.existsSync(i.path)&&await n.promises.unlink(i.path)}catch(m){a(r,"WARN","Failed to clean up uploaded zip file",{tempZipPath:i?.path,error:m.message})}}}async function ke(e,t,i){if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!i||typeof i!="string"||!i.trim())throw new f("command cannot be empty",{field:"command"});const o=await T("computer"),s=l.join(o,String(e),String(t));if(!n.existsSync(s))throw new f("workspace directory does not exist",{field:"workDir",workDir:s});const r=`computer:${e}:${t}`;a(r,"INFO","Execute command in workspace",{userId:e,cId:t,workDir:s,command:i});const d=10*60*1e3,h={cwd:s,timeout:d,maxBuffer:50*1024*1024};return L.BASH_PATH&&(h.shell=L.BASH_PATH),new Promise((p,c)=>{ce(i,h,(u,m,w)=>{const N=u?u.killed?-1:u.code||1:0,g=u&&u.killed?(w||"")+`
|
|
2
|
+
Command timed out after ${d/1e3}s`:w||"";a(r,"INFO","Execute command completed",{userId:e,cId:t,exitCode:N,killed:u?u.killed:!1,stdoutLength:m?m.length:0,stderrLength:g.length}),p({stdout:m||"",stderr:g,exitCode:N})})})}async function Se(e,t,i){const o=`computer:${e}:${t}`;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});const s=await T(o),r=l.join(s,String(e),String(t));if(!n.existsSync(r))throw new f("workspace directory does not exist",{field:"workDir",workDir:r});const d=L.ZIP_WORKSPACE_EXCLUDE||[],h=Array.isArray(i)?i:[],p=new Set([...d,...h]),c=`${e}_${t}.zip`,u=Date.now();a(o,"INFO","Zip workspace request",{userId:e,cId:t,targetDir:r,excludeDirs:[...p]});const m=de("zip",{zlib:{level:9}});return m.directory(r,!1,w=>{const N=w.name||"";if(N.split(/[\/\\]/).filter(Boolean).some(k=>p.has(k)))return!1;try{const k=l.join(r,N);if(n.lstatSync(k).isSymbolicLink())return!1}catch{return!1}return w}),m.on("warning",w=>{w.code==="ENOENT"?a(o,"WARN","Encountered file problem when creating zip",{message:w.message,code:w.code}):a(o,"ERROR","Encountered warning when creating zip",{message:w.message,code:w.code})}),m.on("error",w=>{a(o,"ERROR","Failed to create zip",{message:w.message,elapsedMs:Date.now()-u})}),m.on("end",()=>{a(o,"INFO","Workspace zip created successfully",{targetDir:r,zipFileName:c,elapsedMs:Date.now()-u})}),{archive:m,zipFileName:c}}const Q=new Set([...L.ZIP_WORKSPACE_EXCLUDE||[],"dist-packages"]);function V(e){let t;try{t=n.readdirSync(e,{withFileTypes:!0})}catch{return null}const i=l.join(e,"scripts","package-platforms.mjs");if(n.existsSync(i))return e;for(const o of t)if(o.isDirectory()&&!Q.has(o.name)){const s=V(l.join(e,o.name));if(s)return s}return null}function Y(e,t,i,o=10*60*1e3){return new Promise(s=>{const r=pe(e,t,{...i,timeout:o});let d="",h="";r.stdout?.on("data",p=>{d+=p.toString()}),r.stderr?.on("data",p=>{h+=p.toString()}),r.on("error",p=>{s({stdout:d,stderr:h+`
|
|
3
|
+
Failed to spawn ${e}: ${p.message}`,exitCode:1})}),r.on("close",(p,c)=>{s(p===null&&c?{stdout:d,stderr:h+`
|
|
4
|
+
Process killed by signal ${c} (timeout after ${o/1e3}s)`,exitCode:-1}:{stdout:d,stderr:h,exitCode:p??1})})})}function xe(e){if(!e)return null;let t=e;t.endsWith(".tar.gz")?t=t.slice(0,-7):t.endsWith(".tar.bz2")?t=t.slice(0,-8):(t.endsWith(".tgz")||t.endsWith(".zip"))&&(t=t.slice(0,-4));const i=t.split("-");if(i.length<4)return null;let o=-1;for(let s=i.length-1;s>=2;s--)if(/^\d+\.\d+\.\d+$/.test(i[s])){o=s;break}return o<3?null:i.slice(2,o).join("-")}async function De(e,t,i,o){const s=`computer:${e}:${t}`;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!i)throw new f("agentId cannot be empty",{field:"agentId"});if(!o)throw new f("version cannot be empty",{field:"version"});const r=await T(s),d=l.join(r,String(e),String(t));if(!n.existsSync(d))throw new f("workspace directory does not exist",{field:"workDir",workDir:d});a(s,"INFO","Build agent package request",{userId:e,cId:t,agentId:i,version:o});const h=V(d);if(!h)throw new f("package-platforms.mjs not found in workspace",{field:"script"});a(s,"INFO","Found package script",{projectDir:h});const p=await re(h,s);if(a(s,"INFO","pnpm install completed",{exitCode:p.exitCode,stderrLength:p.stderr.length}),p.exitCode!==0)throw a(s,"ERROR","pnpm install failed",{stderr:p.stderr}),new C(`pnpm install failed: ${p.stderr}`);const c=l.join(h,"dist-packages"),u=["scripts/package-platforms.mjs",`agent-${i}`,o,c,"--print-artifacts"],m=await Y("node",u,{cwd:h,env:I()});if(a(s,"INFO","Build completed",{exitCode:m.exitCode,stdoutLength:m.stdout.length}),m.exitCode!==0)throw a(s,"ERROR","Build failed",{stderr:m.stderr}),new C(`Build failed: ${m.stderr}`);const w=[".tar.gz",".tar.bz2",".zip",".tgz"],N=[],g=m.stdout.split(`
|
|
5
|
+
`);for(const k of g){const F=k.trim();if(!F)continue;const P=F.toLowerCase();if(!w.some(O=>P.endsWith(O)))continue;const z=l.resolve(h,F);let x=l.relative(d,z);x=x.split(l.sep).join("/");const j=l.basename(F),b=xe(j);N.push({path:x,fileName:j,platform:b||""})}return a(s,"INFO","Build agent package completed",{artifactsCount:N.length,artifacts:N}),{artifacts:N}}async function Ne(e,t){const i=`computer:${e}:${t}`;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});const o=await T(i),s=l.join(o,String(e),String(t));if(!n.existsSync(s))return a(i,"WARN","Workspace not found, skip cleanup",{userId:e,cId:t}),{cleaned:!1};const r=V(s);if(!r)return a(i,"WARN","package-platforms.mjs not found, skip cleanup",{userId:e,cId:t}),{cleaned:!1};const d=l.join(r,"dist-packages");return n.existsSync(d)?(n.rmSync(d,{recursive:!0,force:!0}),a(i,"INFO","Cleaned dist-packages",{distPackagesDir:d}),{cleaned:!0}):(a(i,"INFO","dist-packages not found, nothing to clean",{distPackagesDir:d}),{cleaned:!1})}async function Re(e,t){const i=`computer:${e}:${t}`;if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});const o=await T(i),s=l.join(o,String(e),String(t));return n.existsSync(s)?(await n.promises.rm(s,{recursive:!0,force:!0}),a(i,"INFO","Workspace deleted",{userId:e,cId:t,targetDir:s})):a(i,"WARN","Workspace not found, skip delete",{userId:e,cId:t,targetDir:s}),{deleted:!0}}function se(e){const t=l.join(e,"package.json");if(n.existsSync(t))return e;let i;try{i=n.readdirSync(e,{withFileTypes:!0})}catch{return null}for(const o of i)if(o.isDirectory()&&!Q.has(o.name)&&o.name!=="node_modules"){const s=se(l.join(e,o.name));if(s)return s}return null}const oe=["neverBuiltDependencies","onlyBuiltDependencies","ignoredBuiltDependencies"],_e=["NPM_CONFIG_NEVER_BUILT_DEPENDENCIES","npm_config_never_built_dependencies","NPM_CONFIG_ONLY_BUILT_DEPENDENCIES","npm_config_only_built_dependencies","NPM_CONFIG_IGNORED_BUILT_DEPENDENCIES","npm_config_ignored_built_dependencies"];async function Pe(e,t){const i=l.join(e,"package.json");if(!n.existsSync(i))return;const o=await n.promises.readFile(i,"utf8");let s;try{s=JSON.parse(o)}catch{a(t,"WARN","Skip sanitizing package.json: invalid JSON",{projectDir:e});return}if(!s.pnpm||typeof s.pnpm!="object")return;const r=oe.filter(d=>d in s.pnpm);if(r.length!==0){for(const d of r)delete s.pnpm[d];Object.keys(s.pnpm).length===0&&delete s.pnpm,await n.promises.writeFile(i,`${JSON.stringify(s,null,2)}
|
|
6
|
+
`,"utf8"),a(t,"INFO","Removed conflicting pnpm built dependency settings from package.json",{projectDir:e,removedKeys:r})}}async function je(e,t){const i=l.join(e,"pnpm-workspace.yaml");if(!n.existsSync(i))return;const s=(await n.promises.readFile(i,"utf8")).split(`
|
|
7
|
+
`),r=[];let d=-1,h=[];for(const p of s){const c=p.trimStart(),u=p.length-c.length,m=oe.find(w=>new RegExp(`^${w}:\\s*(.*)$`).test(c));if(m){h.push(m);const w=c.slice(m.length+1).trim();(!w||w==="|"||w===">")&&(d=u);continue}if(d>=0){if(c===""||u>d)continue;d=-1}r.push(p)}h.length!==0&&(await n.promises.writeFile(i,r.join(`
|
|
8
|
+
`),"utf8"),a(t,"INFO","Removed conflicting pnpm built dependency settings from pnpm-workspace.yaml",{projectDir:e,removedKeys:h}))}async function ae(e){if(!n.existsSync(e))return"";const t=await n.promises.readFile(e,"utf8"),i=t.split(`
|
|
9
9
|
`).filter(o=>!/^\s*(never-built-dependencies|only-built-dependencies|ignored-built-dependencies)\b/.test(o)).join(`
|
|
10
|
-
`);return i!==t&&await n.promises.writeFile(e,i,"utf8"),i}async function
|
|
10
|
+
`);return i!==t&&await n.promises.writeFile(e,i,"utf8"),i}async function Ee(e,t){await Pe(e,t),await je(e,t),await ae(l.join(e,".npmrc"))}async function Fe(e,t){await me(e,t),await Ee(e,t);const i=l.join(e,".npmrc");let o=await ae(i);const s=[];if(/dangerously-allow-all-builds\s*=/.test(o)||s.push("dangerously-allow-all-builds=true"),/production\s*=/.test(o)||s.push("production=false"),/confirm-modules-purge\s*=/.test(o)||s.push("confirm-modules-purge=false"),s.length>0){const r=o&&!o.endsWith(`
|
|
11
11
|
`)?`
|
|
12
|
-
`:"";await n.promises.writeFile(i,`${o}${
|
|
12
|
+
`:"";await n.promises.writeFile(i,`${o}${r}${s.join(`
|
|
13
13
|
`)}
|
|
14
|
-
`,"utf8"),
|
|
14
|
+
`,"utf8"),a(t,"INFO","Updated .npmrc for pnpm install",{projectDir:e,additions:s})}}function I(){const e={...process.env};delete e.CI,delete e.NPM_CONFIG_PRODUCTION,delete e.npm_config_production;for(const t of _e)delete e[t];return e.NODE_ENV="development",e.NPM_CONFIG_PRODUCTION="false",e}async function re(e,t){await Fe(e,t);const i=I();return Y("pnpm",["install","--prefer-offline","--config.production=false","--config.confirmModulesPurge=false","--config.dangerouslyAllowAllBuilds=true"],{cwd:e,env:i})}function le(e){const t=l.join(e,"pyproject.toml"),i=l.join(e,"requirements.txt");if(n.existsSync(t)||n.existsSync(i))return e;let o;try{o=n.readdirSync(e,{withFileTypes:!0})}catch{return null}for(const s of o)if(s.isDirectory()&&!Q.has(s.name)&&s.name!==".venv"&&s.name!=="venv"&&s.name!=="__pycache__"){const r=le(l.join(e,s.name));if(r)return r}return null}async function Oe(e,t,i){const o=`computer:${e}:${t}`,s=String(i||"").trim().toLowerCase();if(!e)throw new f("userId cannot be empty",{field:"userId"});if(!t)throw new f("cId cannot be empty",{field:"cId"});if(!s)throw new f("programmingLanguage cannot be empty",{field:"programmingLanguage"});const r=await T(o),d=l.join(r,String(e),String(t));if(!n.existsSync(d))throw new f("workspace directory does not exist",{field:"workDir",workDir:d});a(o,"INFO","Install project dependencies request",{userId:e,cId:t,programmingLanguage:s});const h=I();let p=null,c=null;if(s==="typescript"||s==="ts"){if(p=V(d)||se(d),!p)throw new f("TypeScript project not found in workspace",{field:"projectDir"});c=await re(p,o)}else if(s==="python"||s==="py"){if(p=le(d),!p)throw new f("Python project not found in workspace",{field:"projectDir"});const u=l.join(p,"pyproject.toml"),m=l.join(p,"requirements.txt");if(n.existsSync(u))c=await Y("pip",["install","-e","."],{cwd:p,env:h});else if(n.existsSync(m))c=await Y("pip",["install","-r","requirements.txt"],{cwd:p,env:h});else throw new f("No pyproject.toml or requirements.txt found in workspace",{field:"projectDir"})}else throw new f("Unsupported programmingLanguage",{field:"programmingLanguage",programmingLanguage:s});if(a(o,"INFO","Project dependencies install completed",{projectDir:p,programmingLanguage:s,exitCode:c.exitCode,stderrLength:c.stderr.length}),c.exitCode!==0)throw a(o,"ERROR","Project dependencies install failed",{projectDir:p,programmingLanguage:s,stderr:c.stderr}),new C(`Project dependencies install failed: ${c.stderr||c.stdout}`);return{message:"Project dependencies installed successfully",projectDir:p,programmingLanguage:s}}export{ge as createWorkspace,he as pushSkillsToWorkspace,ye as initProjectTemplate,ke as executeCommand,Re as deleteWorkspace,Se as zipWorkspace,De as buildAgentPackage,Ne as cleanupBuildArtifacts,Oe as installProjectDependencies};
|
package/package.json
CHANGED