nuwax-file-server 1.4.9 → 1.5.1
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.4.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();
|
|
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.5.1",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 +1 @@
|
|
|
1
|
-
import x from"express";import b from"multer";import g from"fs";import A from"path";import{ValidationError as P,asyncHandler as c}from"../utils/error/errorHandler.js";import{log as u}from"../utils/log/logUtils.js";import z from"../appConfig/index.js";import{createWorkspace as O,pushSkillsToWorkspace as T,initProjectTemplate as R,installProjectDependencies as _,executeCommand as M,deleteWorkspace as H,zipWorkspace as L,buildAgentPackage as W,cleanupBuildArtifacts as B}from"../utils/computer/computerUtils.js";import{getFileList as J,resolveExistingFile as K,searchFiles as V,updateFiles as G,uploadFile as Z,uploadFiles as X,generateFile as Y,downloadAllFiles as Q,getLatestLogs as q,importProject as ee}from"../utils/computer/computerFileUtils.js";import{resolveServiceContext as p}from"../utils/computer/workspaceContext.js";import{listFsRoots as te,listFsChildren as se}from"../utils/computer/fsBrowserUtils.js";const j=x.Router(),I=b({storage:b.diskStorage({destination:(e,n,s)=>{try{const t=typeof e.headers["x-workspace-type"]=="string"?e.headers["x-workspace-type"].trim().toLowerCase():"",a=typeof e.headers["x-app-id"]=="string"?e.headers["x-app-id"].trim():"";let o;if(t==="userapp"&&a){const i=z.USERAPP_WORKSPACE_DIR;if(!i)return s(new Error("USERAPP_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));o=A.join(i,String(a),".tmp")}else{const i=z.COMPUTER_WORKSPACE_DIR;if(!i)return s(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const r=e.body?.userId||"unknown",l=e.body?.cId||"unknown";o=A.join(i,String(r),String(l),".tmp")}g.existsSync(o)||g.mkdirSync(o,{recursive:!0}),s(null,o)}catch(t){s(t)}},filename:(e,n,s)=>{const t=A.extname(n.originalname)||".zip",a=A.basename(n.originalname,t),o=`${Date.now()}_${Math.round(Math.random()*1e6)}`;s(null,`${a}_${o}${t}`)}}),limits:{fileSize:z.UPLOAD_MAX_FILE_SIZE_BYTES}});function ae(e,n,s,t){if(e&&e.name==="MulterError"||e&&(e.name==="ValidationError"||e instanceof P))return t(e);t(e)}const oe=[{path:"/create-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=e.file||null,o=p(e),i=`computer:${s}:${t}`;u(i,"INFO","Create workspace request",{userId:s,cId:t,workspaceType:o.workspaceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const r=await O(s,t,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,o);n.status(200).json({success:!0,...r})})},{path:"/create-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,agentId:a,skillUrls:o,skillUrlMap:i,skillNames:r,updateSkillNames:l,mcpServersConfig:d,hooksConfig:f,permissionsConfig:m,hookScripts:h}=e.body||{},k=e.file||null,C=p(e),D=`computer:${s}:${t}`;let N=o;if(typeof o=="string")try{N=JSON.parse(o)}catch{N=[o]}let w=i;if(typeof i=="string")try{w=JSON.parse(i)}catch{w=null}let S=r;if(typeof r=="string")try{const y=JSON.parse(r);S=Array.isArray(y)?y:[r]}catch{S=r.split(",").map(y=>y.trim()).filter(Boolean)}let F=l;if(typeof l=="string")try{const y=JSON.parse(l);F=Array.isArray(y)?y:[l]}catch{F=l.split(",").map(y=>y.trim()).filter(Boolean)}let $=h;if(typeof h=="string")try{$=JSON.parse(h)}catch{$=null}const E=Array.isArray(N)?N.length:0,U=w&&typeof w=="object"&&!Array.isArray(w)?Object.keys(w).length:0;u(D,"INFO","Create workspace v2 request",{userId:s,cId:t,agentId:a,workspaceType:C.workspaceType,appId:C.appId,hasFile:!!k,fileName:k?.originalname,fileSize:k?.size,skillUrlsCount:E,skillUrlMapCount:U,skillNamesCount:Array.isArray(S)?S.length:0,updateSkillNamesCount:Array.isArray(F)?F.length:0,hasMcpServersConfig:!!d,hasHooksConfig:!!f,hasPermissionsConfig:!!m,hookScriptsCount:Array.isArray($)?$.length:0});const v=await O(s,t,k,N,d,m,f,$,a,S,F,w,C);n.status(200).json({success:!0,...v})})},{path:"/push-skills-to-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=e.file||null,o=p(e),i=`computer:${s}:${t}`;u(i,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:s,cId:t,workspaceType:o.workspaceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const r=await T(s,t,a,void 0,void 0,o);n.status(200).json({success:!0,...r})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,agentId:a,skillUrls:o}=e.body||{},i=e.file||null,r=p(e),l=`computer:${s}:${t}`;let d=o;if(typeof o=="string")try{const m=JSON.parse(o);d=Array.isArray(m)?m:[o]}catch{d=[o]}u(l,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:s,cId:t,agentId:a,workspaceType:r.workspaceType,appId:r.appId,hasFile:!!i,fileName:i?.originalname,fileSize:i?.size,skillUrlsCount:Array.isArray(d)?d.length:0});const f=await T(s,t,i,d,a,r);n.status(200).json({success:!0,...f})})},{path:"/fs/roots",method:"get",handler:c(async(e,n)=>{const s=await te();n.status(200).json({success:!0,...s})})},{path:"/fs/children",method:"get",handler:c(async(e,n)=>{const{path:s}=e.query,t=await se(s);n.status(200).json({success:!0,...t})})},{path:"/get-file-list",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:i,recursive:r}=e.query,l=await J(s,t,a,o,i,r,p(e));n.status(200).json({success:!0,...l})})},{path:"/resolve-file",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,filePath:i}=e.query,r=await K(s,t,i,a,o,p(e));n.status(200).json({success:!0,...r})})},{path:"/search-files",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:i,kw:r,limit:l,maxVisit:d,timeoutMs:f}=e.query,m=await V(s,t,a,r,o,i,l,d,f,p(e));n.status(200).json({success:!0,...m})})},{path:"/files-update",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,files:a,customTargetDir:o}=e.body||{},i=`computer:${s}:${t}`;u(i,"INFO","Files update",{userId:s,cId:t,filesCount:a?a.length:0}),a&&Array.isArray(a)&&a.forEach(l=>{if(l&&typeof l.contents=="string"&&l.contents)try{l.contents=decodeURIComponent(l.contents)}catch(d){u(i,"WARN","Decode file content failed",{fileName:l.name,error:d.message})}});const r=await G(s,t,a,o,p(e));n.status(200).json(r)})},{path:"/upload-file",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,filePath:a,customTargetDir:o}=e.body||{},i=e.file,r=`computer:${s}:${t}`;u(r,"INFO","Upload single file",{userId:s,cId:t,filePath:a});const d={buffer:await g.promises.readFile(i.path),originalname:i.originalname,mimetype:i.mimetype,size:i.size};try{const f=await Z(s,t,d,a,o,p(e));n.status(200).json(f)}finally{g.existsSync(i.path)&&await g.promises.unlink(i.path)}})},{path:"/generate-file",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,fileName:a,content:o,customTargetDir:i}=e.body||{},r=`computer:${s}:${t}`;u(r,"INFO","Generate file request",{userId:s,cId:t,fileName:a,contentLength:typeof o=="string"?o.length:0});const l=await Y(s,t,a,o,i,p(e));n.status(200).json(l)})},{path:"/import-project",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,customTargetDir:a}=e.body||{},o=e.file,i=`computer:${s}:${t}`;if(u(i,"INFO","Import project request",{userId:s,cId:t,fileName:o?.originalname,fileSize:o?.size}),!o)throw new P("file is required",{field:"file"});const r=await ee(s,t,o,a,p(e));n.status(200).json(r)})},{path:"/upload-files",method:"post",middleware:I.array("files"),handler:c(async(e,n)=>{const{userId:s,cId:t,filePaths:a,customTargetDir:o}=e.body||{},i=e.files||[],r=`computer:${s}:${t}`,l=Array.isArray(a)?a:typeof a=="string"?[a]:a;u(r,"INFO","Batch upload files request",{userId:s,cId:t,filesCount:i.length,filePathsCount:Array.isArray(l)?l.length:0});const d=[],f=[];try{for(const h of i){f.push(h.path);const k=await g.promises.readFile(h.path);d.push({buffer:k,originalname:h.originalname,mimetype:h.mimetype,size:h.size})}const m=await X(s,t,d,l,o,p(e));n.status(200).json(m)}finally{for(const m of f)if(g.existsSync(m))try{await g.promises.unlink(m)}catch(h){u(r,"WARN","Clean temporary file failed",{tempPath:m,error:h.message})}}})},{path:"/install-project",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,programmingLanguage:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Install project request",{userId:s,cId:t,programmingLanguage:a});const i=await _(s,t,a,p(e));n.status(200).json({success:!0,...i})})},{path:"/init-project-template",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,enableGit:a}=e.body||{},o=e.file||null,i=`computer:${s}:${t}`;u(i,"INFO","Init project template request",{userId:s,cId:t,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size,enableGit:a});const r=await R(s,t,o,a,p(e));n.status(200).json({success:!0,...r})})},{path:"/download-all-files",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,customTargetDir:a}=e.query||{},o=`computer:${s}:${t}`;u(o,"INFO","Download all files request",{userId:s,cId:t});const{archive:i,zipFileName:r}=await Q(s,t,a,p(e));n.setHeader("Content-Type","application/zip");const l=encodeURIComponent(r);n.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),i.on("error",d=>{n.destroy(d)}),i.pipe(n),i.finalize()})},{path:"/execute-command",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,command:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Execute command request",{userId:s,cId:t,command:a});const i=await M(s,t,a,p(e));n.status(200).json({success:!0,...i})})},{path:"/delete-workspace",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=`computer:${s}:${t}`;u(a,"INFO","Delete workspace request",{userId:s,cId:t});const o=await H(s,t,p(e));n.status(200).json({success:!0,...o})})},{path:"/get-logs",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,tailLines:a}=e.query,o=a?parseInt(a,10):200,i=Number.isFinite(o)&&o>0?o:200,r=await q(s,t,i,p(e));n.status(200).json(r)})},{path:"/zip-workspace",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,excludeDirs:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Zip workspace request",{userId:s,cId:t,hasExcludeDirs:!!a});const{archive:i,zipFileName:r}=await L(s,t,a||null,p(e));n.setHeader("Content-Type","application/zip");const l=encodeURIComponent(r);n.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),i.on("error",d=>{n.destroy(d)}),i.pipe(n),i.finalize()})},{path:"/build-agent-package",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,agentId:a,version:o}=e.body||{},i=`computer:${s}:${t}`;u(i,"INFO","Build agent package request",{userId:s,cId:t,agentId:a,version:o});const r=await W(s,t,a,o,p(e));n.status(200).json({success:!0,...r})})},{path:"/cleanup-build-artifacts",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=`computer:${s}:${t}`;u(a,"INFO","Cleanup build artifacts request",{userId:s,cId:t});const o=await B(s,t,p(e));n.status(200).json({success:!0,...o})})}];oe.forEach(e=>{if(e.middleware)j[e.method](e.path,e.middleware,e.handler);else if(e.customHandler){const n=[];e.handler&&n.push(e.handler),e.decodeMiddleware&&n.push(e.decodeMiddleware),n.push(ae),n.push(e.customHandler),j[e.method](e.path,...n)}else j[e.method](e.path,e.handler)});export default j;
|
|
1
|
+
import v from"express";import z from"multer";import g from"fs";import j from"path";import{ValidationError as P,asyncHandler as c}from"../utils/error/errorHandler.js";import{log as u}from"../utils/log/logUtils.js";import b from"../appConfig/index.js";import{createWorkspace as D,pushSkillsToWorkspace as T,initProjectTemplate as R,installProjectDependencies as M,executeCommand as _,deleteWorkspace as B,zipWorkspace as H,buildAgentPackage as L,cleanupBuildArtifacts as W}from"../utils/computer/computerUtils.js";import{getFileList as J,getFileMeta as K,resolveExistingFile as V,searchFiles as G,updateFiles as Z,uploadFile as X,uploadFiles as Y,generateFile as Q,downloadAllFiles as q,getLatestLogs as ee,importProject as te}from"../utils/computer/computerFileUtils.js";import{resolveServiceContext as d}from"../utils/computer/workspaceContext.js";import{listFsRoots as se,listFsChildren as ae,createFsDirectory as oe,renameFsDirectory as ne}from"../utils/computer/fsBrowserUtils.js";const A=v.Router(),I=z({storage:z.diskStorage({destination:(e,n,s)=>{try{const t=typeof e.headers["x-workspace-type"]=="string"?e.headers["x-workspace-type"].trim().toLowerCase():"",a=typeof e.headers["x-app-id"]=="string"?e.headers["x-app-id"].trim():"";let o;if(t==="userapp"&&a){const r=b.USERAPP_WORKSPACE_DIR;if(!r)return s(new Error("USERAPP_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));o=j.join(r,String(a),".tmp")}else{const r=b.COMPUTER_WORKSPACE_DIR;if(!r)return s(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const i=e.body?.userId||"unknown",l=e.body?.cId||"unknown";o=j.join(r,String(i),String(l),".tmp")}g.existsSync(o)||g.mkdirSync(o,{recursive:!0}),s(null,o)}catch(t){s(t)}},filename:(e,n,s)=>{const t=j.extname(n.originalname)||".zip",a=j.basename(n.originalname,t),o=`${Date.now()}_${Math.round(Math.random()*1e6)}`;s(null,`${a}_${o}${t}`)}}),limits:{fileSize:b.UPLOAD_MAX_FILE_SIZE_BYTES}});function re(e,n,s,t){if(e&&e.name==="MulterError"||e&&(e.name==="ValidationError"||e instanceof P))return t(e);t(e)}const ie=[{path:"/create-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=e.file||null,o=d(e),r=`computer:${s}:${t}`;u(r,"INFO","Create workspace request",{userId:s,cId:t,workspaceType:o.workspaceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await D(s,t,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,o);n.status(200).json({success:!0,...i})})},{path:"/create-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,agentId:a,skillUrls:o,skillUrlMap:r,skillNames:i,updateSkillNames:l,mcpServersConfig:p,hooksConfig:f,permissionsConfig:m,hookScripts:h}=e.body||{},k=e.file||null,C=d(e),O=`computer:${s}:${t}`;let N=o;if(typeof o=="string")try{N=JSON.parse(o)}catch{N=[o]}let w=r;if(typeof r=="string")try{w=JSON.parse(r)}catch{w=null}let F=i;if(typeof i=="string")try{const y=JSON.parse(i);F=Array.isArray(y)?y:[i]}catch{F=i.split(",").map(y=>y.trim()).filter(Boolean)}let S=l;if(typeof l=="string")try{const y=JSON.parse(l);S=Array.isArray(y)?y:[l]}catch{S=l.split(",").map(y=>y.trim()).filter(Boolean)}let $=h;if(typeof h=="string")try{$=JSON.parse(h)}catch{$=null}const x=Array.isArray(N)?N.length:0,E=w&&typeof w=="object"&&!Array.isArray(w)?Object.keys(w).length:0;u(O,"INFO","Create workspace v2 request",{userId:s,cId:t,agentId:a,workspaceType:C.workspaceType,appId:C.appId,hasFile:!!k,fileName:k?.originalname,fileSize:k?.size,skillUrlsCount:x,skillUrlMapCount:E,skillNamesCount:Array.isArray(F)?F.length:0,updateSkillNamesCount:Array.isArray(S)?S.length:0,hasMcpServersConfig:!!p,hasHooksConfig:!!f,hasPermissionsConfig:!!m,hookScriptsCount:Array.isArray($)?$.length:0});const U=await D(s,t,k,N,p,m,f,$,a,F,S,w,C);n.status(200).json({success:!0,...U})})},{path:"/push-skills-to-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=e.file||null,o=d(e),r=`computer:${s}:${t}`;u(r,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:s,cId:t,workspaceType:o.workspaceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await T(s,t,a,void 0,void 0,o);n.status(200).json({success:!0,...i})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,agentId:a,skillUrls:o}=e.body||{},r=e.file||null,i=d(e),l=`computer:${s}:${t}`;let p=o;if(typeof o=="string")try{const m=JSON.parse(o);p=Array.isArray(m)?m:[o]}catch{p=[o]}u(l,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:s,cId:t,agentId:a,workspaceType:i.workspaceType,appId:i.appId,hasFile:!!r,fileName:r?.originalname,fileSize:r?.size,skillUrlsCount:Array.isArray(p)?p.length:0});const f=await T(s,t,r,p,a,i);n.status(200).json({success:!0,...f})})},{path:"/fs/roots",method:"get",handler:c(async(e,n)=>{const s=await se();n.status(200).json({success:!0,...s})})},{path:"/fs/children",method:"get",handler:c(async(e,n)=>{const{path:s}=e.query,t=await ae(s);n.status(200).json({success:!0,...t})})},{path:"/fs/mkdir",method:"post",handler:c(async(e,n)=>{const{parentPath:s,dirName:t}=e.body||{},a=await oe(s,t);n.status(200).json({success:!0,...a})})},{path:"/fs/rename",method:"post",handler:c(async(e,n)=>{const{path:s,newName:t}=e.body||{},a=await ne(s,t);n.status(200).json({success:!0,...a})})},{path:"/get-file-list",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:r,recursive:i}=e.query,l=await J(s,t,a,o,r,i,d(e));n.status(200).json({success:!0,...l})})},{path:"/resolve-file",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,filePath:r}=e.query,i=await V(s,t,r,a,o,d(e));n.status(200).json({success:!0,...i})})},{path:"/get-file-meta",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,customTargetDir:a,filePaths:o,fileMetaMaxBatch:r}=e.body||{},i=await K(s,t,o,a,d(e),r);n.status(200).json({success:!0,...i})})},{path:"/search-files",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:r,kw:i,limit:l,maxVisit:p,timeoutMs:f}=e.query,m=await G(s,t,a,i,o,r,l,p,f,d(e));n.status(200).json({success:!0,...m})})},{path:"/files-update",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,files:a,customTargetDir:o}=e.body||{},r=`computer:${s}:${t}`;u(r,"INFO","Files update",{userId:s,cId:t,filesCount:a?a.length:0}),a&&Array.isArray(a)&&a.forEach(l=>{if(l&&typeof l.contents=="string"&&l.contents)try{l.contents=decodeURIComponent(l.contents)}catch(p){u(r,"WARN","Decode file content failed",{fileName:l.name,error:p.message})}});const i=await Z(s,t,a,o,d(e));n.status(200).json(i)})},{path:"/upload-file",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,filePath:a,customTargetDir:o}=e.body||{},r=e.file,i=`computer:${s}:${t}`;u(i,"INFO","Upload single file",{userId:s,cId:t,filePath:a});const p={buffer:await g.promises.readFile(r.path),originalname:r.originalname,mimetype:r.mimetype,size:r.size};try{const f=await X(s,t,p,a,o,d(e));n.status(200).json(f)}finally{g.existsSync(r.path)&&await g.promises.unlink(r.path)}})},{path:"/generate-file",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,fileName:a,content:o,customTargetDir:r}=e.body||{},i=`computer:${s}:${t}`;u(i,"INFO","Generate file request",{userId:s,cId:t,fileName:a,contentLength:typeof o=="string"?o.length:0});const l=await Q(s,t,a,o,r,d(e));n.status(200).json(l)})},{path:"/import-project",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,customTargetDir:a}=e.body||{},o=e.file,r=`computer:${s}:${t}`;if(u(r,"INFO","Import project request",{userId:s,cId:t,fileName:o?.originalname,fileSize:o?.size}),!o)throw new P("file is required",{field:"file"});const i=await te(s,t,o,a,d(e));n.status(200).json(i)})},{path:"/upload-files",method:"post",middleware:I.array("files"),handler:c(async(e,n)=>{const{userId:s,cId:t,filePaths:a,customTargetDir:o}=e.body||{},r=e.files||[],i=`computer:${s}:${t}`,l=Array.isArray(a)?a:typeof a=="string"?[a]:a;u(i,"INFO","Batch upload files request",{userId:s,cId:t,filesCount:r.length,filePathsCount:Array.isArray(l)?l.length:0});const p=[],f=[];try{for(const h of r){f.push(h.path);const k=await g.promises.readFile(h.path);p.push({buffer:k,originalname:h.originalname,mimetype:h.mimetype,size:h.size})}const m=await Y(s,t,p,l,o,d(e));n.status(200).json(m)}finally{for(const m of f)if(g.existsSync(m))try{await g.promises.unlink(m)}catch(h){u(i,"WARN","Clean temporary file failed",{tempPath:m,error:h.message})}}})},{path:"/install-project",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,programmingLanguage:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Install project request",{userId:s,cId:t,programmingLanguage:a});const r=await M(s,t,a,d(e));n.status(200).json({success:!0,...r})})},{path:"/init-project-template",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,enableGit:a}=e.body||{},o=e.file||null,r=`computer:${s}:${t}`;u(r,"INFO","Init project template request",{userId:s,cId:t,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size,enableGit:a});const i=await R(s,t,o,a,d(e));n.status(200).json({success:!0,...i})})},{path:"/download-all-files",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,customTargetDir:a}=e.query||{},o=`computer:${s}:${t}`;u(o,"INFO","Download all files request",{userId:s,cId:t});const{archive:r,zipFileName:i}=await q(s,t,a,d(e));n.setHeader("Content-Type","application/zip");const l=encodeURIComponent(i);n.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),r.on("error",p=>{n.destroy(p)}),r.pipe(n),r.finalize()})},{path:"/execute-command",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,command:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Execute command request",{userId:s,cId:t,command:a});const r=await _(s,t,a,d(e));n.status(200).json({success:!0,...r})})},{path:"/delete-workspace",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=`computer:${s}:${t}`;u(a,"INFO","Delete workspace request",{userId:s,cId:t});const o=await B(s,t,d(e));n.status(200).json({success:!0,...o})})},{path:"/get-logs",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,tailLines:a}=e.query,o=a?parseInt(a,10):200,r=Number.isFinite(o)&&o>0?o:200,i=await ee(s,t,r,d(e));n.status(200).json(i)})},{path:"/zip-workspace",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,excludeDirs:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Zip workspace request",{userId:s,cId:t,hasExcludeDirs:!!a});const{archive:r,zipFileName:i}=await H(s,t,a||null,d(e));n.setHeader("Content-Type","application/zip");const l=encodeURIComponent(i);n.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),r.on("error",p=>{n.destroy(p)}),r.pipe(n),r.finalize()})},{path:"/build-agent-package",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,agentId:a,version:o}=e.body||{},r=`computer:${s}:${t}`;u(r,"INFO","Build agent package request",{userId:s,cId:t,agentId:a,version:o});const i=await L(s,t,a,o,d(e));n.status(200).json({success:!0,...i})})},{path:"/cleanup-build-artifacts",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=`computer:${s}:${t}`;u(a,"INFO","Cleanup build artifacts request",{userId:s,cId:t});const o=await W(s,t,d(e));n.status(200).json({success:!0,...o})})}];ie.forEach(e=>{if(e.middleware)A[e.method](e.path,e.middleware,e.handler);else if(e.customHandler){const n=[];e.handler&&n.push(e.handler),e.decodeMiddleware&&n.push(e.decodeMiddleware),n.push(re),n.push(e.customHandler),A[e.method](e.path,...n)}else A[e.method](e.path,e.handler)});export default A;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import c from"fs";import d from"path";import re from"archiver";import P from"../../appConfig/index.js";import{log as u}from"../log/logUtils.js";import{ValidationError as E,SystemError as O,FileError as pe}from"../error/errorHandler.js";import{extractZip as he}from"../common/zipUtils.js";import{moveDirectory as we,movePath as J}from"../common/fileSystemUtils.js";import{resolveLogDir as ge,resolveWorkspaceDir as _,resolveWorkspaceRoot as ie}from"./workspaceContext.js";const j=new Set([".git",".agents",".claude",".codex",".opencode",".tmp",".logs"]),ye=100*1024*1024,X=P.DOWNLOAD_MAX_FILE_SIZE_BYTES||ye;async function Ee(t,i,e,l,a){const o=[],m=await c.promises.readdir(t,{withFileTypes:!0});m.sort((s,n)=>s.isDirectory()&&!n.isDirectory()?-1:!s.isDirectory()&&n.isDirectory()?1:s.name.toLowerCase().localeCompare(n.name.toLowerCase()));for(const s of m){const n=d.join(t,s.name);if(s.name.startsWith(".")&&s.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(s.name)||s.isDirectory()&&P.TRAVERSE_EXCLUDE_DIRS.includes(s.name))continue;const f=d.relative(i,n).replace(/\\/g,"/");if(s.isDirectory()){o.push({name:f,isDir:!0});continue}try{o.push({name:f,isDir:!1,fileProxyUrl:G(l,f,a),isLink:s.isSymbolicLink()})}catch(r){u(e,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${n}`,{error:r.message})}}return o}async function se(t,i,e,l,a){const o=[],m=await c.promises.readdir(t,{withFileTypes:!0});m.sort((s,n)=>s.isDirectory()&&!n.isDirectory()?-1:!s.isDirectory()&&n.isDirectory()?1:s.name.toLowerCase().localeCompare(n.name.toLowerCase()));for(const s of m){const n=d.join(t,s.name);if(!(s.name.startsWith(".")&&s.name!==".gitignore"||(P.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(s.name))&&!(s.isDirectory()&&P.TRAVERSE_EXCLUDE_DIRS.includes(s.name)))if(s.isDirectory()){const f=await se(n,i,e,l,a);if(f.length===0){const r=i||t,h=d.relative(r,n).replace(/\\/g,"/");o.push({name:h,isDir:!0})}else o.push(...f)}else try{const f=i||t,r=d.relative(f,n).replace(/\\/g,"/");o.push({name:r,isDir:!1,fileProxyUrl:G(l,r,a),isLink:s.isSymbolicLink()})}catch(f){u(e,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${n}`,{error:f.message})}}return o}function ne(t,i){const e=(i==null?"":String(i)).trim();if(!e||e==="."||e==="/")return d.resolve(t);const l=d.normalize(e).replace(/^[\/\\]+/,"");if(!l||l===".")return d.resolve(t);if(d.isAbsolute(e)||l.split(d.sep).includes(".."))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:i});const a=d.resolve(t),o=d.resolve(t,l);if(o!==a&&!o.startsWith(a+d.sep))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:i});return o}function oe(t,i){const e=(i==null?"":String(i)).trim();if(!e)return null;const l=d.resolve(t);let a;if(d.isAbsolute(e))a=d.resolve(e);else{const m=d.normalize(e).replace(/^[\/\\]+/,"");if(!m||m==="."||m.split(d.sep).includes(".."))return null;a=d.resolve(t,m)}if(a!==l&&!a.startsWith(l+d.sep))return null;const o=d.relative(l,a).replace(/\\/g,"/");return!o||o.startsWith("..")?null:{absPath:a,name:o}}function G(t,i,e){if(!t||!i)return null;const l=i.split("/").map(o=>encodeURIComponent(o)).join("/");let a=`${t}/${l}`;return e&&(a+=`?customTargetDir=${encodeURIComponent(e)}`),a}async function Se(t,i,e,l,a,o=null){if(!t)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!i)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});if(!e||!String(e).trim())throw new E("filePath \u4E0D\u80FD\u4E3A\u7A7A",{field:"filePath"});const m=String(t),s=String(i),n=a&&a.trim()?a.trim():null,y=n||_(o,m,s);if(!c.existsSync(y))return{exists:!1};let f=oe(y,e);if(!f){const r=String(e).trim().replace(/^[\/\\]+/,"");r&&r!==String(e).trim()&&(f=oe(y,r))}if(!f)return{exists:!1};try{if(!(await c.promises.stat(f.absPath)).isFile())return{exists:!1}}catch{return{exists:!1}}return{exists:!0,name:f.name,fileProxyUrl:G(l,f.name,n)}}async function ae(t,i,e,l,a=""){const o=await c.promises.readdir(d.join(t,a),{withFileTypes:!0});let m=0;for(const s of o){const n=a?d.join(a,s.name):s.name,y=n.split(d.sep).filter(Boolean);if(y.some(w=>w.startsWith(".")))continue;const f=y[y.length-1];if(i.includes(f)||y.some(w=>e.includes(w)))continue;const r=d.join(t,n);let h;try{h=await c.promises.lstat(r)}catch(w){u(l,"WARN","Error occurred when getting file stats, skipping",{filePath:n.replace(/\\/g,"/"),error:w.message});continue}h.isSymbolicLink()||h.nlink>1||(h.isDirectory()?m+=await ae(t,i,e,l,n):h.isFile()&&(m+=h.size))}return m}async function Re(t,i,e,l,a,o,m=null){const s=Date.now(),n=`computer:${t}:${i}`,y=!(o===!1||o==="false");if(!t)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!i)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const f=String(t),r=String(i),h=l&&l.trim()?l.trim():null,w=h||_(m,f,r);if(!c.existsSync(w))return u(n,"INFO","Directory does not exist, returning empty list",{targetDir:w,userId:f,cId:r}),{files:[],recursive:y};const p=ne(w,a);if(!c.existsSync(p))return u(n,"INFO","List path does not exist, returning empty list",{targetDir:w,listDir:p,relativePath:a||"",userId:f,cId:r}),{files:[],recursive:y};if(!(await c.promises.stat(p)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:a});u(n,"DEBUG","Start getting user file list",{targetDir:w,listDir:p,relativePath:a||"",recursive:y,userId:f,cId:r});try{const S=y?await se(p,w,n,e,h):await Ee(p,w,n,e,h);return u(n,"INFO","User file list obtained successfully",{fileCount:S.length,targetDir:w,listDir:p,relativePath:a||"",recursive:y,userId:f,cId:r,elapsedMs:Date.now()-s}),{files:S,recursive:y}}catch(S){throw S instanceof E?S:(u(n,"ERROR","Failed to get user file list",{targetDir:w,listDir:p,relativePath:a||"",recursive:y,userId:f,cId:r,error:S.message,elapsedMs:Date.now()-s}),new O(`Failed to get file list: ${S.message}`,{targetDir:w,originalError:S.message}))}}const Fe=5e3;function Q(t,i){const e=Number.parseInt(t,10);if(!Number.isFinite(e)||e<=0)throw new E(`${i} \u5FC5\u987B\u4E3A\u6B63\u6574\u6570`,{field:i,value:t});return e}function ce(t,i,e){return e?i.toLowerCase().includes(e)?!0:t.toLowerCase().includes(e):!1}function le(t,i,e){return!!(t.name.startsWith(".")&&t.name!==".gitignore"||i.includes(t.name)||t.isDirectory()&&e.includes(t.name))}function me(t,i,e,l){for(let a=i;a<t.length;a++)if(!le(t[a],e,l))return!0;return!1}function ue(t,i){return Date.now()-t>=i}async function Ie(t,i,e,l,a,o,m,s,n,y=null){const f=Date.now(),r=`computer:${t}:${i}`;if(!t)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!i)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const h=(l==null?"":String(l)).trim();if(!h)throw new E("kw \u4E0D\u80FD\u4E3A\u7A7A",{field:"kw"});const w=Q(m,"limit"),p=Q(s,"maxVisit"),g=Q(n,"timeoutMs"),S=h.toLowerCase(),D=String(t),R=String(i),v=a&&a.trim()?a.trim():null,F=v||_(y,D,R);if(!c.existsSync(F))return{files:[],truncated:!1,visited:0};const I=ne(F,o);if(!c.existsSync(I))return{files:[],truncated:!1,visited:0};if(!(await c.promises.stat(I)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:o});const $=d.relative(F,I).replace(/\\/g,"/"),q=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],Z=P.TRAVERSE_EXCLUDE_DIRS||[],b=[],K=new Set;let A=0,Y=!1,C=!1;const L=[$],U=()=>A>=p||ue(f,g);for(;L.length>0;){if(U()){C=!0;break}if(b.length>=w){L.length>0&&(C=!0);break}const N=L.shift();if(K.has(N))continue;K.add(N);const M=N?d.join(F,N):F;let W;try{W=await c.promises.readdir(M,{withFileTypes:!0})}catch(k){u(r,"WARN","search readdir failed",{dirRel:N,error:k.message});continue}W.sort((k,x)=>k.isDirectory()&&!x.isDirectory()?-1:!k.isDirectory()&&x.isDirectory()?1:k.name.toLowerCase().localeCompare(x.name.toLowerCase()));const H=[];let B=!1,V=!1;for(let k=0;k<W.length;k++){const x=W[k];if(le(x,q,Z))continue;if(U()){C=!0,B=!0,V=!0;break}A+=1;const te=d.join(M,x.name),T=d.relative(F,te).replace(/\\/g,"/");if(x.isDirectory()){if(H.push(T),b.length<w&&ce(T,x.name,S)&&(b.push({name:T,isDir:!0}),b.length>=w)){B=!0,V=me(W,k+1,q,Z);break}continue}try{if(b.length<w&&ce(T,x.name,S)&&(b.push({name:T,isDir:!1,fileProxyUrl:G(e,T,v),isLink:x.isSymbolicLink()}),b.length>=w)){B=!0,V=me(W,k+1,q,Z);break}}catch(de){u(r,"WARN",`search \u5904\u7406\u6587\u4EF6\u5931\u8D25: ${te}`,{error:de.message})}}if(B||U()){(U()||V||H.length>0||L.length>0)&&(C=!0);continue}for(const k of H){if(U()){C=!0;break}if(L.length>=Fe){C=!0;break}if(A+L.length>=p){C=!0;break}K.has(k)||L.push(k)}}return b.sort((N,M)=>N.isDir!==M.isDir?N.isDir?-1:1:String(N.name).localeCompare(String(M.name))),Y=C||L.length>0||A>=p||ue(f,g),u(r,"INFO","File search completed",{kw:h,matchCount:b.length,visited:A,truncated:Y,relativePath:o||"",elapsedMs:Date.now()-f}),{files:b,truncated:Y,visited:A}}async function De(t,i,e,l,a=null){const o=Date.now(),m=`computer:${t}:${i}`;if(!t)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(e))throw new E("files must be an array",{field:"files"});const s=String(t),n=String(i),y=l&&l.trim()?l.trim():null,f=y||_(a,s,n);c.existsSync(f)||c.mkdirSync(f,{recursive:!0});for(let r=0;r<e.length;r++){const h=e[r];if(!h||typeof h.operation!="string")throw new E(`files[${r}].operation cannot be empty`,{field:`files[${r}].operation`});if(!h.name||typeof h.name!="string")throw new E(`files[${r}].name cannot be empty`,{field:`files[${r}].name`});const w=h.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(w))throw new E(`files[${r}].operation must be one of create, delete, rename or modify`,{field:`files[${r}].operation`});if(w==="rename"&&!h.renameFrom)throw new E(`files[${r}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${r}].renameFrom`});if(w==="modify"&&h.isDir!==!0&&typeof h.contents!="string")throw new E(`files[${r}].contents must be a string (modify operation requires)`,{field:`files[${r}].contents`})}u(m,"DEBUG","Start updating user files",{userId:s,cId:n,filesCount:e.length});try{for(const r of e){const h=r.operation.toLowerCase(),w=r.name,p=d.normalize(w).replace(/^[\/\\]+/,""),g=d.join(f,p),S=d.resolve(g),D=d.resolve(f);if(!S.startsWith(D+d.sep)&&S!==D){u(m,"WARN","File path is not secure, skipping",{filePath:p,resolvedPath:S});continue}switch(h){case"create":{if(r.isDir===!0){if(c.existsSync(g)){if((await c.promises.stat(g)).isFile())throw new E("Cannot create directory, file with the same name already exists",{filePath:p});u(m,"INFO","Directory already exists, skipping creation",{filePath:p});break}await c.promises.mkdir(g,{recursive:!0}),u(m,"INFO","Directory created successfully",{filePath:p});break}if(c.existsSync(g)){if((await c.promises.stat(g)).isDirectory())throw new E("Cannot create file, directory with the same name already exists",{filePath:p});u(m,"INFO","File already exists, skipping creation",{filePath:p});break}await c.promises.mkdir(d.dirname(g),{recursive:!0});const R=r.contents||"";await c.promises.writeFile(g,R,"utf8"),u(m,"INFO","File created successfully",{filePath:p});break}case"delete":{c.existsSync(g)?(await c.promises.stat(g)).isDirectory()?(await c.promises.rm(g,{recursive:!0,force:!0}),u(m,"INFO","Directory deleted successfully",{filePath:p})):(await c.promises.unlink(g),u(m,"INFO","File deleted successfully",{filePath:p})):u(m,"WARN","The file or directory to be deleted does not exist",{filePath:p});break}case"rename":{const R=r.renameFrom;if(!R||typeof R!="string"){u(m,"WARN","Rename operation missing renameFrom",{filePath:p});break}const v=d.normalize(R).replace(/^[\/\\]+/,""),F=d.join(f,v),I=d.resolve(F);if(!I.startsWith(D+d.sep)&&I!==D){u(m,"WARN","Source path is not secure, skipping rename",{sourcePath:v,targetPath:p});break}if(c.existsSync(F)){const $=(await c.promises.stat(F)).isDirectory();await c.promises.mkdir(d.dirname(g),{recursive:!0}),await c.promises.rename(F,g),u(m,"INFO",$?"Directory renamed successfully":"File renamed successfully",{sourcePath:v,targetPath:p})}else u(m,"WARN","The file or directory to be renamed does not exist",{sourcePath:v});break}case"modify":{if(!c.existsSync(g)){u(m,"WARN","The file to be modified does not exist",{filePath:p});break}if((await c.promises.stat(g)).isDirectory()){u(m,"INFO","The target is a directory, skipping modification",{filePath:p});break}const v=typeof r.contents=="string"?r.contents:"";if(await c.promises.readFile(g,"utf8")===v){u(m,"INFO","File content has no changes, skipping write",{filePath:p});break}await c.promises.writeFile(g,v,"utf8"),u(m,"INFO","File modified successfully",{filePath:p});break}default:{u(m,"WARN","Unsupported operation type",{operation:h,filePath:p});break}}}return u(m,"INFO","User files updated successfully",{userId:s,cId:n,filesCount:e.length,elapsedMs:Date.now()-o}),{success:!0,message:"User files updated successfully",userId:s,cId:n,filesCount:e.length}}catch(r){throw u(m,"ERROR","User files updated failed",{userId:s,cId:n,error:r.message,elapsedMs:Date.now()-o}),new O(`User files updated failed: ${r.message}`,{userId:s,cId:n,originalError:r.message})}}async function ee(t,i,e,l,a,o=null){const m=Date.now(),s=`computer:${t}:${i}`;if(!t)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!e)throw new E("file cannot be empty",{field:"file"});if(!l||typeof l!="string")throw new E("filePath cannot be empty",{field:"filePath"});const n=String(t),y=String(i),f=a&&a.trim()?a.trim():null,r=f||_(o,n,y);c.existsSync(r)||c.mkdirSync(r,{recursive:!0});const h=d.normalize(l).replace(/^[\/\\]+/,""),w=d.join(r,h),p=d.resolve(w),g=d.resolve(r);if(!p.startsWith(g+d.sep)&&p!==g)throw new E("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:l,resolvedPath:p});try{if(await c.promises.mkdir(d.dirname(w),{recursive:!0}),e.buffer)await c.promises.writeFile(w,e.buffer);else if(typeof e.contents=="string")await c.promises.writeFile(w,e.contents,"utf8");else throw new E("File content format is incorrect",{field:"file",hasBuffer:!!e.buffer,hasContents:typeof e.contents});return u(s,"INFO","File uploaded successfully",{userId:n,cId:y,filePath:h,targetPath:p,fileSize:e.buffer?e.buffer.length:e.contents?e.contents.length:0,elapsedMs:Date.now()-m}),{success:!0,message:"File uploaded successfully",fileSize:e.buffer?e.buffer.length:e.contents?e.contents.length:0}}catch(S){throw u(s,"ERROR","File upload failed",{userId:n,cId:y,filePath:h,error:S.message,elapsedMs:Date.now()-m}),new O(`File upload failed: ${S.message}`,{userId:n,cId:y,filePath:h,originalError:S.message})}}async function ve(t,i,e,l,a,o=null){const m=Date.now(),s=`computer:${t}:${i}`;if(!t)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(e))throw new E("files must be an array",{field:"files"});if(!Array.isArray(l))throw new E("filePaths must be an array",{field:"filePaths"});if(e.length!==l.length)throw new E(`File count (${e.length}) does not match path count (${l.length})`,{field:"filePaths"});u(s,"DEBUG","Start batch uploading files",{userId:t,cId:i,filesCount:e.length});const n=[];try{for(let r=0;r<e.length;r++){const h=e[r],w=l[r];if(!h){u(s,"WARN","Empty file object encountered in batch upload, skipping",{index:r,filePath:w}),n.push({success:!1,filePath:w,error:"Empty file object"});continue}if(!w||typeof w!="string"){u(s,"WARN","Invalid file path in batch upload, skipping",{index:r,originalname:h.originalname}),n.push({success:!1,filePath:w||"",originalname:h.originalname,error:"Invalid file path"});continue}try{const p=await ee(t,i,h,w,a,o);n.push({success:!0,filePath:w,originalname:h.originalname,...p})}catch(p){u(s,"ERROR","Single file upload failed in batch upload",{filePath:w,originalname:h.originalname,error:p.message}),n.push({success:!1,filePath:w,originalname:h.originalname,error:p.message})}}const y=n.filter(r=>r.success).length,f=n.filter(r=>!r.success).length;return u(s,"INFO","Batch upload files completed",{userId:t,cId:i,totalCount:e.length,successCount:y,failCount:f,elapsedMs:Date.now()-m}),{success:!0,message:"Batch upload completed",totalCount:e.length,successCount:y,failCount:f,results:n}}catch(y){throw u(s,"ERROR","Batch upload files failed",{userId:t,cId:i,error:y.message,elapsedMs:Date.now()-m}),new O(`Batch upload files failed: ${y.message}`,{userId:t,cId:i,originalError:y.message})}}async function ke(t,i,e,l=null){const a=Date.now(),o=`computer:${t}:${i}`,m=ie(l);if(!t)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!m&&!l?.workspacePath)throw new O("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const s=String(t),n=String(i),y=e&&e.trim()?e.trim():null,f=y||_(l,s,n);if(!c.existsSync(f)){const S=`${s}_${n}.zip`;u(o,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:f,userId:s,cId:n,zipFileName:S});const D=re("zip",{zlib:{level:9}});return D.append(null,{name:`${s}_${n}/`,type:"directory"}),D.on("warning",R=>{if(R.code==="ENOENT")u(o,"WARN","Encountered file problem when creating empty zip",{message:R.message,code:R.code});else throw u(o,"ERROR","Encountered warning when creating empty zip",{message:R.message,code:R.code}),R}),D.on("error",R=>{u(o,"ERROR","Failed to create empty zip",{message:R.message})}),{archive:D,zipFileName:S}}const r=`${s}_${n}.zip`;u(o,"DEBUG","Start creating workspace directory zip",{targetDir:f,zipFileName:r});const h=re("zip",{zlib:{level:9}}),w=P.CONTENT_TRAVERSE_EXCLUDE_FILES||[],p=P.TRAVERSE_EXCLUDE_DIRS||[],g=await ae(f,w,p,o);if(g>X){const S=X/1024/1024,D=(g/1024/1024).toFixed(2);throw u(o,"WARN","Download rejected due to oversized workspace",{targetDir:f,downloadableSize:g,maxSizeBytes:X}),new E(`Download failed: total file size ${D}MB exceeds limit ${S}MB`,{field:"downloadSize",downloadableSize:g,maxSizeBytes:X})}return h.directory(f,`${s}_${n}`,S=>{const D=S.name||"",R=D.split(/[\/\\]/).filter(Boolean);if(R.some(F=>F.startsWith(".")))return!1;const v=R[R.length-1];if(w.includes(v)||R.some(F=>p.includes(F)))return!1;try{const F=d.join(f,D),I=c.lstatSync(F);if(I.isSymbolicLink()||I.nlink>1)return!1}catch(F){return u(o,"WARN","Error occurred when detecting link file, skipping",{filePath:D,error:F.message}),!1}return S}),h.on("warning",S=>{if(S.code==="ENOENT")u(o,"WARN","Encountered file problem when creating zip",{message:S.message,code:S.code});else throw u(o,"ERROR","Encountered warning when creating zip",{message:S.message,code:S.code}),S}),h.on("error",S=>{u(o,"ERROR","Failed to create zip",{message:S.message,elapsedMs:Date.now()-a})}),h.on("end",()=>{u(o,"INFO","Workspace directory zip created successfully",{targetDir:f,zipFileName:r,elapsedMs:Date.now()-a})}),{archive:h,zipFileName:r}}async function be(t,i,e=200,l=null){const a=Date.now(),o=`computer:${t}:${i}`;if(!t)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});const m=String(t),s=String(i),n=ge(l,m,s);if(!n)return u(o,"WARN","COMPUTER_WORKSPACE_DIR is not configured"),{success:!0,message:"Log workspace is not configured",logs:[],totalLines:0,startIndex:1,logFileName:null};if(!c.existsSync(n))return u(o,"DEBUG","Log directory does not exist",{logDir:n}),{success:!0,message:"Log directory does not exist",logs:[],totalLines:0,startIndex:1,logFileName:null};const f=(await c.promises.readdir(n,{withFileTypes:!0})).filter(I=>I.isFile()).map(I=>I.name);if(f.length===0)return u(o,"DEBUG","No log file found",{logDir:n}),{success:!0,message:"No log file found",logs:[],totalLines:0,startIndex:1,logFileName:null};const r=[];for(const I of f){const z=d.join(n,I),$=await c.promises.stat(z);r.push({name:I,fullPath:z,mtime:$.mtimeMs,size:$.size})}r.sort((I,z)=>z.mtime-I.mtime);const h=r[0],p=(await c.promises.readFile(h.fullPath,"utf8")).split(`
|
|
2
|
-
`).filter(I=>I.length>0),
|
|
1
|
+
import c from"fs";import p from"path";import ne from"archiver";import{lookup as Ee}from"mime-types";import v from"../../appConfig/index.js";import{log as m}from"../log/logUtils.js";import{ValidationError as E,SystemError as L,FileError as Re}from"../error/errorHandler.js";import{extractZip as Fe}from"../common/zipUtils.js";import{moveDirectory as Se,movePath as ee}from"../common/fileSystemUtils.js";import{resolveLogDir as Ie,resolveWorkspaceDir as A,resolveWorkspaceRoot as se}from"./workspaceContext.js";const j=new Set([".git",".agents",".claude",".codex",".opencode",".tmp",".logs"]),De=100*1024*1024,V=v.DOWNLOAD_MAX_FILE_SIZE_BYTES||De;function G(e){return p.sep==="\\"?e.replace(/\\/g,"/"):e}function oe(e,r){return G(p.relative(e,r))}function ae(e,r){return e?`${e}/${r}`:r}async function xe(e,r,t,i,a){const n=[],l=await c.promises.readdir(e,{withFileTypes:!0});l.sort((s,h)=>s.isDirectory()&&!h.isDirectory()?-1:!s.isDirectory()&&h.isDirectory()?1:s.name.toLowerCase().localeCompare(h.name.toLowerCase()));const u=oe(r,e);for(const s of l){if(s.name.startsWith(".")&&s.name!==".gitignore"||(v.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(s.name)||s.isDirectory()&&v.TRAVERSE_EXCLUDE_DIRS.includes(s.name))continue;const f=ae(u,s.name);if(s.isDirectory()){n.push({name:f,isDir:!0});continue}try{n.push({name:f,isDir:!1,fileProxyUrl:H(i,f,a),isLink:s.isSymbolicLink()})}catch(o){m(t,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${e}/${s.name}`,{error:o.message})}}return n}async function le(e,r,t,i,a=""){const n=[],l=await c.promises.readdir(e,{withFileTypes:!0});l.sort((u,s)=>u.isDirectory()&&!s.isDirectory()?-1:!u.isDirectory()&&s.isDirectory()?1:u.name.toLowerCase().localeCompare(s.name.toLowerCase()));for(const u of l){const s=p.join(e,u.name);if(u.name.startsWith(".")&&u.name!==".gitignore"||(v.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(u.name)||u.isDirectory()&&v.TRAVERSE_EXCLUDE_DIRS.includes(u.name))continue;const f=ae(a,u.name);if(u.isDirectory()){const o=await le(s,r,t,i,f);o.length===0?n.push({name:f,isDir:!0}):n.push(...o)}else try{n.push({name:f,isDir:!1,fileProxyUrl:H(t,f,i),isLink:u.isSymbolicLink()})}catch(o){m(r,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${s}`,{error:o.message})}}return n}function ce(e,r){const t=(r==null?"":String(r)).trim();if(!t||t==="."||t==="/")return p.resolve(e);const i=p.normalize(t).replace(/^[\/\\]+/,"");if(!i||i===".")return p.resolve(e);if(p.isAbsolute(t)||i.split(p.sep).includes(".."))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:r});const a=p.resolve(e),n=p.resolve(e,i);if(n!==a&&!n.startsWith(a+p.sep))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:r});return n}function q(e,r){const t=(r==null?"":String(r)).trim();if(!t)return null;const i=p.resolve(e);let a;if(p.isAbsolute(t))a=p.resolve(t);else{const l=p.normalize(t).replace(/^[\/\\]+/,"");if(!l||l==="."||l.split(p.sep).includes(".."))return null;a=p.resolve(e,l)}if(a!==i&&!a.startsWith(i+p.sep))return null;const n=G(p.relative(i,a));return!n||n.startsWith("..")?null:{absPath:a,name:n}}function H(e,r,t){if(!e||!r)return null;const i=r.split("/").map(n=>encodeURIComponent(n)).join("/");let a=`${e}/${i}`;return t&&(a+=`?customTargetDir=${encodeURIComponent(t)}`),a}async function ke(e,r,t,i,a,n=null){if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});if(!t||!String(t).trim())throw new E("filePath \u4E0D\u80FD\u4E3A\u7A7A",{field:"filePath"});const l=String(e),u=String(r),s=a&&a.trim()?a.trim():null,h=s||A(n,l,u);if(!c.existsSync(h))return{exists:!1};let f=q(h,t);if(!f){const o=String(t).trim().replace(/^[\/\\]+/,"");o&&o!==String(t).trim()&&(f=q(h,o))}if(!f)return{exists:!1};try{if(!(await c.promises.stat(f.absPath)).isFile())return{exists:!1}}catch{return{exists:!1}}return{exists:!0,name:f.name,fileProxyUrl:H(i,f.name,s)}}const ve=100,be=1e3,Ne=8,ue=1e3;function Ce(e){return p.extname(e).replace(/^\./,"").toLowerCase()||""}async function Pe(e,r,t){const i=new Array(e.length),a=Math.max(1,Math.min(r,e.length));let n=0;return await Promise.all(Array.from({length:a},async()=>{for(;;){const l=n++;if(l>=e.length)return;i[l]=await t(e[l],l)}})),i}function _e(e){return!(e.startsWith(".")&&e!==".gitignore"||(v.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(e)||v.TRAVERSE_EXCLUDE_DIRS.includes(e))}async function ze(e){const r=await c.promises.opendir(e);let t=0;for await(const i of r)if(_e(i.name)&&(t+=1,t>=ue))return ue;return t}function me(e,r){return{path:e,isDir:null,isLink:null,size:null,mtimeMs:null,extension:null,mimeType:null,linkTarget:null,childCount:null,...r?{error:r}:{}}}async function Le(e,r,t){const i=(r==null?"":String(r)).trim();let a=i?q(e,i):null;if(!a&&i.startsWith("/")){const n=i.replace(/^[\/\\]+/,"");n&&n!==i&&(a=q(e,n))}if(!a)return me(i,"illegal path");try{const n=await c.promises.lstat(a.absPath),l=n.isDirectory(),u=n.isSymbolicLink(),s={path:i,isDir:l,isLink:u,size:l?null:n.size,mtimeMs:n.mtimeMs,extension:l?null:Ce(i),mimeType:l?null:Ee(i)||"application/octet-stream",linkTarget:null,childCount:null};if(u)try{s.linkTarget=await c.promises.readlink(a.absPath)}catch(h){m(t,"WARN","Readlink failed, linkTarget set to null",{filePath:i,error:h.message})}if(l)try{s.childCount=await ze(a.absPath)}catch(h){m(t,"WARN","Count directory entries failed, childCount set to null",{filePath:i,error:h.message})}return s}catch(n){return me(i,n.code||n.message)}}async function Ae(e,r,t,i,a=null,n=null){const l=Date.now(),u=`computer:${e}:${r}`;if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});if(!Array.isArray(t)||t.length===0)throw new E("filePaths \u5FC5\u987B\u4E3A\u975E\u7A7A\u6570\u7EC4",{field:"filePaths"});const s=Number.parseInt(n,10),h=Number.isFinite(s)&&s>0?Math.min(s,be):ve;if(t.length>h)throw new E(`filePaths \u5355\u6B21\u6700\u591A ${h} \u6761`,{field:"filePaths",count:t.length});const f=String(e),o=String(r),w=(i==null?"":String(i).trim())||null,d=w||A(a,f,o);if(!c.existsSync(d))return m(u,"INFO","Target directory does not exist, returning empty metas",{targetDir:d,userId:f,cId:o}),{metas:[]};const y=await Pe(t,Ne,R=>Le(d,R,u));return m(u,"INFO","File metadata queried",{targetDir:d,count:y.length,failed:y.filter(R=>R.error).length,customTargetDir:w,userId:f,cId:o,elapsedMs:Date.now()-l}),{metas:y}}async function fe(e,r,t,i,a=""){const n=await c.promises.readdir(p.join(e,a),{withFileTypes:!0});let l=0;for(const u of n){const s=a?p.join(a,u.name):u.name,h=s.split(p.sep).filter(Boolean);if(h.some(w=>w.startsWith(".")))continue;const f=h[h.length-1];if(r.includes(f)||h.some(w=>t.includes(w)))continue;const o=p.join(e,s);let g;try{g=await c.promises.lstat(o)}catch(w){m(i,"WARN","Error occurred when getting file stats, skipping",{filePath:s.replace(/\\/g,"/"),error:w.message});continue}g.isSymbolicLink()||g.nlink>1||(g.isDirectory()?l+=await fe(e,r,t,i,s):g.isFile()&&(l+=g.size))}return l}async function Te(e,r,t,i,a,n,l=null){const u=Date.now(),s=`computer:${e}:${r}`,h=!(n===!1||n==="false");if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const f=String(e),o=String(r),g=i&&i.trim()?i.trim():null,w=g||A(l,f,o);if(!c.existsSync(w))return m(s,"INFO","Directory does not exist, returning empty list",{targetDir:w,userId:f,cId:o}),{files:[],recursive:h};const d=ce(w,a);if(!c.existsSync(d))return m(s,"INFO","List path does not exist, returning empty list",{targetDir:w,listDir:d,relativePath:a||"",userId:f,cId:o}),{files:[],recursive:h};if(!(await c.promises.stat(d)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:a});m(s,"DEBUG","Start getting user file list",{targetDir:w,listDir:d,relativePath:a||"",recursive:h,userId:f,cId:o});try{const R=h?await le(d,s,t,g,oe(w,d)):await xe(d,w,s,t,g);return m(s,"INFO","User file list obtained successfully",{fileCount:R.length,targetDir:w,listDir:d,relativePath:a||"",recursive:h,userId:f,cId:o,elapsedMs:Date.now()-u}),{files:R,recursive:h}}catch(R){throw R instanceof E?R:(m(s,"ERROR","Failed to get user file list",{targetDir:w,listDir:d,relativePath:a||"",recursive:h,userId:f,cId:o,error:R.message,elapsedMs:Date.now()-u}),new L(`Failed to get file list: ${R.message}`,{targetDir:w,originalError:R.message}))}}const Oe=5e3;function te(e,r){const t=Number.parseInt(e,10);if(!Number.isFinite(t)||t<=0)throw new E(`${r} \u5FC5\u987B\u4E3A\u6B63\u6574\u6570`,{field:r,value:e});return t}function de(e,r,t){return t?r.toLowerCase().includes(t)?!0:e.toLowerCase().includes(t):!1}function pe(e,r,t){return!!(e.name.startsWith(".")&&e.name!==".gitignore"||r.includes(e.name)||e.isDirectory()&&t.includes(e.name))}function he(e,r,t,i){for(let a=r;a<e.length;a++)if(!pe(e[a],t,i))return!0;return!1}function we(e,r){return Date.now()-e>=r}async function $e(e,r,t,i,a,n,l,u,s,h=null){const f=Date.now(),o=`computer:${e}:${r}`;if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const g=(i==null?"":String(i)).trim();if(!g)throw new E("kw \u4E0D\u80FD\u4E3A\u7A7A",{field:"kw"});const w=te(l,"limit"),d=te(u,"maxVisit"),y=te(s,"timeoutMs"),R=g.toLowerCase(),D=String(e),F=String(r),x=a&&a.trim()?a.trim():null,S=x||A(h,D,F);if(!c.existsSync(S))return{files:[],truncated:!1,visited:0};const I=ce(S,n);if(!c.existsSync(I))return{files:[],truncated:!1,visited:0};if(!(await c.promises.stat(I)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:n});const T=G(p.relative(S,I)),Z=v.CONTENT_TRAVERSE_EXCLUDE_FILES||[],K=v.TRAVERSE_EXCLUDE_DIRS||[],b=[],Y=new Set;let O=0,J=!1,_=!1;const z=[T],W=()=>O>=d||we(f,y);for(;z.length>0;){if(W()){_=!0;break}if(b.length>=w){z.length>0&&(_=!0);break}const C=z.shift();if(Y.has(C))continue;Y.add(C);const U=C?p.join(S,C):S;let $;try{$=await c.promises.readdir(U,{withFileTypes:!0})}catch(k){m(o,"WARN","search readdir failed",{dirRel:C,error:k.message});continue}$.sort((k,N)=>k.isDirectory()&&!N.isDirectory()?-1:!k.isDirectory()&&N.isDirectory()?1:k.name.toLowerCase().localeCompare(N.name.toLowerCase()));const Q=[];let B=!1,X=!1;for(let k=0;k<$.length;k++){const N=$[k];if(pe(N,Z,K))continue;if(W()){_=!0,B=!0,X=!0;break}O+=1;const ie=p.join(U,N.name),M=G(p.relative(S,ie));if(N.isDirectory()){if(Q.push(M),b.length<w&&de(M,N.name,R)&&(b.push({name:M,isDir:!0}),b.length>=w)){B=!0,X=he($,k+1,Z,K);break}continue}try{if(b.length<w&&de(M,N.name,R)&&(b.push({name:M,isDir:!1,fileProxyUrl:H(t,M,x),isLink:N.isSymbolicLink()}),b.length>=w)){B=!0,X=he($,k+1,Z,K);break}}catch(ye){m(o,"WARN",`search \u5904\u7406\u6587\u4EF6\u5931\u8D25: ${ie}`,{error:ye.message})}}if(B||W()){(W()||X||Q.length>0||z.length>0)&&(_=!0);continue}for(const k of Q){if(W()){_=!0;break}if(z.length>=Oe){_=!0;break}if(O+z.length>=d){_=!0;break}Y.has(k)||z.push(k)}}return b.sort((C,U)=>C.isDir!==U.isDir?C.isDir?-1:1:String(C.name).localeCompare(String(U.name))),J=_||z.length>0||O>=d||we(f,y),m(o,"INFO","File search completed",{kw:g,matchCount:b.length,visited:O,truncated:J,relativePath:n||"",elapsedMs:Date.now()-f}),{files:b,truncated:J,visited:O}}async function Me(e,r,t,i,a=null){const n=Date.now(),l=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(t))throw new E("files must be an array",{field:"files"});const u=String(e),s=String(r),h=i&&i.trim()?i.trim():null,f=h||A(a,u,s);c.existsSync(f)||c.mkdirSync(f,{recursive:!0});for(let o=0;o<t.length;o++){const g=t[o];if(!g||typeof g.operation!="string")throw new E(`files[${o}].operation cannot be empty`,{field:`files[${o}].operation`});if(!g.name||typeof g.name!="string")throw new E(`files[${o}].name cannot be empty`,{field:`files[${o}].name`});const w=g.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(w))throw new E(`files[${o}].operation must be one of create, delete, rename or modify`,{field:`files[${o}].operation`});if(w==="rename"&&!g.renameFrom)throw new E(`files[${o}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${o}].renameFrom`});if(w==="modify"&&g.isDir!==!0&&typeof g.contents!="string")throw new E(`files[${o}].contents must be a string (modify operation requires)`,{field:`files[${o}].contents`})}m(l,"DEBUG","Start updating user files",{userId:u,cId:s,filesCount:t.length});try{for(const o of t){const g=o.operation.toLowerCase(),w=o.name,d=p.normalize(w).replace(/^[\/\\]+/,""),y=p.join(f,d),R=p.resolve(y),D=p.resolve(f);if(!R.startsWith(D+p.sep)&&R!==D){m(l,"WARN","File path is not secure, skipping",{filePath:d,resolvedPath:R});continue}switch(g){case"create":{if(o.isDir===!0){if(c.existsSync(y)){if((await c.promises.stat(y)).isFile())throw new E("Cannot create directory, file with the same name already exists",{filePath:d});m(l,"INFO","Directory already exists, skipping creation",{filePath:d});break}await c.promises.mkdir(y,{recursive:!0}),m(l,"INFO","Directory created successfully",{filePath:d});break}if(c.existsSync(y)){if((await c.promises.stat(y)).isDirectory())throw new E("Cannot create file, directory with the same name already exists",{filePath:d});m(l,"INFO","File already exists, skipping creation",{filePath:d});break}await c.promises.mkdir(p.dirname(y),{recursive:!0});const F=o.contents||"";await c.promises.writeFile(y,F,"utf8"),m(l,"INFO","File created successfully",{filePath:d});break}case"delete":{c.existsSync(y)?(await c.promises.stat(y)).isDirectory()?(await c.promises.rm(y,{recursive:!0,force:!0}),m(l,"INFO","Directory deleted successfully",{filePath:d})):(await c.promises.unlink(y),m(l,"INFO","File deleted successfully",{filePath:d})):m(l,"WARN","The file or directory to be deleted does not exist",{filePath:d});break}case"rename":{const F=o.renameFrom;if(!F||typeof F!="string"){m(l,"WARN","Rename operation missing renameFrom",{filePath:d});break}const x=p.normalize(F).replace(/^[\/\\]+/,""),S=p.join(f,x),I=p.resolve(S);if(!I.startsWith(D+p.sep)&&I!==D){m(l,"WARN","Source path is not secure, skipping rename",{sourcePath:x,targetPath:d});break}if(c.existsSync(S)){const T=(await c.promises.stat(S)).isDirectory();await c.promises.mkdir(p.dirname(y),{recursive:!0}),await c.promises.rename(S,y),m(l,"INFO",T?"Directory renamed successfully":"File renamed successfully",{sourcePath:x,targetPath:d})}else m(l,"WARN","The file or directory to be renamed does not exist",{sourcePath:x});break}case"modify":{if(!c.existsSync(y)){m(l,"WARN","The file to be modified does not exist",{filePath:d});break}if((await c.promises.stat(y)).isDirectory()){m(l,"INFO","The target is a directory, skipping modification",{filePath:d});break}const x=typeof o.contents=="string"?o.contents:"";if(await c.promises.readFile(y,"utf8")===x){m(l,"INFO","File content has no changes, skipping write",{filePath:d});break}await c.promises.writeFile(y,x,"utf8"),m(l,"INFO","File modified successfully",{filePath:d});break}default:{m(l,"WARN","Unsupported operation type",{operation:g,filePath:d});break}}}return m(l,"INFO","User files updated successfully",{userId:u,cId:s,filesCount:t.length,elapsedMs:Date.now()-n}),{success:!0,message:"User files updated successfully",userId:u,cId:s,filesCount:t.length}}catch(o){throw m(l,"ERROR","User files updated failed",{userId:u,cId:s,error:o.message,elapsedMs:Date.now()-n}),new L(`User files updated failed: ${o.message}`,{userId:u,cId:s,originalError:o.message})}}async function re(e,r,t,i,a,n=null){const l=Date.now(),u=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!t)throw new E("file cannot be empty",{field:"file"});if(!i||typeof i!="string")throw new E("filePath cannot be empty",{field:"filePath"});const s=String(e),h=String(r),f=a&&a.trim()?a.trim():null,o=f||A(n,s,h);c.existsSync(o)||c.mkdirSync(o,{recursive:!0});const g=p.normalize(i).replace(/^[\/\\]+/,""),w=p.join(o,g),d=p.resolve(w),y=p.resolve(o);if(!d.startsWith(y+p.sep)&&d!==y)throw new E("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:i,resolvedPath:d});try{if(await c.promises.mkdir(p.dirname(w),{recursive:!0}),t.buffer)await c.promises.writeFile(w,t.buffer);else if(typeof t.contents=="string")await c.promises.writeFile(w,t.contents,"utf8");else throw new E("File content format is incorrect",{field:"file",hasBuffer:!!t.buffer,hasContents:typeof t.contents});return m(u,"INFO","File uploaded successfully",{userId:s,cId:h,filePath:g,targetPath:d,fileSize:t.buffer?t.buffer.length:t.contents?t.contents.length:0,elapsedMs:Date.now()-l}),{success:!0,message:"File uploaded successfully",fileSize:t.buffer?t.buffer.length:t.contents?t.contents.length:0}}catch(R){throw m(u,"ERROR","File upload failed",{userId:s,cId:h,filePath:g,error:R.message,elapsedMs:Date.now()-l}),new L(`File upload failed: ${R.message}`,{userId:s,cId:h,filePath:g,originalError:R.message})}}async function We(e,r,t,i,a,n=null){const l=Date.now(),u=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(t))throw new E("files must be an array",{field:"files"});if(!Array.isArray(i))throw new E("filePaths must be an array",{field:"filePaths"});if(t.length!==i.length)throw new E(`File count (${t.length}) does not match path count (${i.length})`,{field:"filePaths"});m(u,"DEBUG","Start batch uploading files",{userId:e,cId:r,filesCount:t.length});const s=[];try{for(let o=0;o<t.length;o++){const g=t[o],w=i[o];if(!g){m(u,"WARN","Empty file object encountered in batch upload, skipping",{index:o,filePath:w}),s.push({success:!1,filePath:w,error:"Empty file object"});continue}if(!w||typeof w!="string"){m(u,"WARN","Invalid file path in batch upload, skipping",{index:o,originalname:g.originalname}),s.push({success:!1,filePath:w||"",originalname:g.originalname,error:"Invalid file path"});continue}try{const d=await re(e,r,g,w,a,n);s.push({success:!0,filePath:w,originalname:g.originalname,...d})}catch(d){m(u,"ERROR","Single file upload failed in batch upload",{filePath:w,originalname:g.originalname,error:d.message}),s.push({success:!1,filePath:w,originalname:g.originalname,error:d.message})}}const h=s.filter(o=>o.success).length,f=s.filter(o=>!o.success).length;return m(u,"INFO","Batch upload files completed",{userId:e,cId:r,totalCount:t.length,successCount:h,failCount:f,elapsedMs:Date.now()-l}),{success:!0,message:"Batch upload completed",totalCount:t.length,successCount:h,failCount:f,results:s}}catch(h){throw m(u,"ERROR","Batch upload files failed",{userId:e,cId:r,error:h.message,elapsedMs:Date.now()-l}),new L(`Batch upload files failed: ${h.message}`,{userId:e,cId:r,originalError:h.message})}}async function Ue(e,r,t,i=null){const a=Date.now(),n=`computer:${e}:${r}`,l=se(i);if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!l&&!i?.workspacePath)throw new L("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const u=String(e),s=String(r),h=t&&t.trim()?t.trim():null,f=h||A(i,u,s);if(!c.existsSync(f)){const R=`${u}_${s}.zip`;m(n,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:f,userId:u,cId:s,zipFileName:R});const D=ne("zip",{zlib:{level:9}});return D.append(null,{name:`${u}_${s}/`,type:"directory"}),D.on("warning",F=>{if(F.code==="ENOENT")m(n,"WARN","Encountered file problem when creating empty zip",{message:F.message,code:F.code});else throw m(n,"ERROR","Encountered warning when creating empty zip",{message:F.message,code:F.code}),F}),D.on("error",F=>{m(n,"ERROR","Failed to create empty zip",{message:F.message})}),{archive:D,zipFileName:R}}const o=`${u}_${s}.zip`;m(n,"DEBUG","Start creating workspace directory zip",{targetDir:f,zipFileName:o});const g=ne("zip",{zlib:{level:9}}),w=v.CONTENT_TRAVERSE_EXCLUDE_FILES||[],d=v.TRAVERSE_EXCLUDE_DIRS||[],y=await fe(f,w,d,n);if(y>V){const R=V/1024/1024,D=(y/1024/1024).toFixed(2);throw m(n,"WARN","Download rejected due to oversized workspace",{targetDir:f,downloadableSize:y,maxSizeBytes:V}),new E(`Download failed: total file size ${D}MB exceeds limit ${R}MB`,{field:"downloadSize",downloadableSize:y,maxSizeBytes:V})}return g.directory(f,`${u}_${s}`,R=>{const D=R.name||"",F=D.split(/[\/\\]/).filter(Boolean);if(F.some(S=>S.startsWith(".")))return!1;const x=F[F.length-1];if(w.includes(x)||F.some(S=>d.includes(S)))return!1;try{const S=p.join(f,D),I=c.lstatSync(S);if(I.isSymbolicLink()||I.nlink>1)return!1}catch(S){return m(n,"WARN","Error occurred when detecting link file, skipping",{filePath:D,error:S.message}),!1}return R}),g.on("warning",R=>{if(R.code==="ENOENT")m(n,"WARN","Encountered file problem when creating zip",{message:R.message,code:R.code});else throw m(n,"ERROR","Encountered warning when creating zip",{message:R.message,code:R.code}),R}),g.on("error",R=>{m(n,"ERROR","Failed to create zip",{message:R.message,elapsedMs:Date.now()-a})}),g.on("end",()=>{m(n,"INFO","Workspace directory zip created successfully",{targetDir:f,zipFileName:o,elapsedMs:Date.now()-a})}),{archive:g,zipFileName:o}}async function je(e,r,t=200,i=null){const a=Date.now(),n=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});const l=String(e),u=String(r),s=Ie(i,l,u);if(!s)return m(n,"WARN","COMPUTER_WORKSPACE_DIR is not configured"),{success:!0,message:"Log workspace is not configured",logs:[],totalLines:0,startIndex:1,logFileName:null};if(!c.existsSync(s))return m(n,"DEBUG","Log directory does not exist",{logDir:s}),{success:!0,message:"Log directory does not exist",logs:[],totalLines:0,startIndex:1,logFileName:null};const f=(await c.promises.readdir(s,{withFileTypes:!0})).filter(I=>I.isFile()).map(I=>I.name);if(f.length===0)return m(n,"DEBUG","No log file found",{logDir:s}),{success:!0,message:"No log file found",logs:[],totalLines:0,startIndex:1,logFileName:null};const o=[];for(const I of f){const P=p.join(s,I),T=await c.promises.stat(P);o.push({name:I,fullPath:P,mtime:T.mtimeMs,size:T.size})}o.sort((I,P)=>P.mtime-I.mtime);const g=o[0],d=(await c.promises.readFile(g.fullPath,"utf8")).split(`
|
|
2
|
+
`).filter(I=>I.length>0),y=d.length,R=Math.max(1,t),D=Math.max(0,y-R),F=D+1,S=d.slice(D).map((I,P)=>({line:F+P,content:I}));return m(n,"DEBUG","Get latest logs",{fileName:g.name,fileSize:g.size,totalLines:y,returnedLines:S.length,elapsedMs:Date.now()-a}),{success:!0,message:"Get log successfully",logs:S,totalLines:y,startIndex:F,logFileName:g.name}}async function ge(e,r){try{const i=(await c.promises.readdir(e,{withFileTypes:!0})).filter(u=>!u.name.startsWith(".")&&u.name!=="node_modules");if(i.length!==1||!i[0].isDirectory())return;const a=p.join(e,i[0].name),n=p.join(e,`..tmp_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{await c.promises.rename(a,n)}catch(u){if(u.code==="EXDEV")await c.promises.cp(a,n,{recursive:!0}),await c.promises.rm(a,{recursive:!0,force:!0});else throw u}const l=await c.promises.readdir(n);for(const u of l){const s=p.join(n,u),h=p.join(e,u);try{await c.promises.rename(s,h)}catch(f){if(f.code==="EXDEV")(await c.promises.lstat(s)).isDirectory()?await Se(s,h):(await c.promises.copyFile(s,h),await c.promises.unlink(s));else throw f}}await c.promises.rm(n,{recursive:!0,force:!0}),m(r,"INFO","Removed single top-level directory from imported zip",{removedDir:i[0].name})}catch(t){m(r,"WARN","Failed to remove top-level directory from imported zip, continuing",{error:t.message})}}async function Be(e,r){if(!c.existsSync(e)){await c.promises.mkdir(e,{recursive:!0});return}const t=await c.promises.readdir(e,{withFileTypes:!0});for(const i of t){if(j.has(i.name))continue;const a=p.join(e,i.name);await c.promises.rm(a,{recursive:!0,force:!0}),m(r,"DEBUG","Removed workspace entry during import",{name:i.name})}}async function Xe(e,r,t){if(await c.promises.mkdir(r,{recursive:!0}),!c.existsSync(e)){await c.promises.mkdir(e,{recursive:!0});return}const i=await c.promises.readdir(e,{withFileTypes:!0});for(const a of i){if(j.has(a.name))continue;const n=p.join(e,a.name),l=p.join(r,a.name);await ee(n,l),m(t,"DEBUG","Backed up workspace entry before import",{name:a.name})}}async function Ve(e,r,t){if(!c.existsSync(e))return;const i=await c.promises.readdir(e,{withFileTypes:!0});for(const a of i){if(j.has(a.name))continue;const n=p.join(e,a.name),l=p.join(r,a.name);await ee(n,l)}m(t,"INFO","Workspace restored from backup after import failure")}async function Ge(e,r,t){const i=await c.promises.readdir(e,{withFileTypes:!0}),a=[];try{for(const n of i){if(j.has(n.name)){m(t,"INFO","Skipping preserved entry from imported zip",{name:n.name});continue}const l=p.join(e,n.name),u=p.join(r,n.name);await ee(l,u),a.push(n.name)}}catch(n){throw n.mergedEntries=a,n}}async function qe(e,r,t,i,a=null){const n=Date.now(),l=`computer:${e}:${r}`,u=se(a);if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!t||!t.path)throw new E("file is required",{field:"file"});if(!u&&!a?.workspacePath)throw new L("COMPUTER_WORKSPACE_DIR is not configured");if(p.extname(t.originalname||t.filename||"").toLowerCase()!==".zip")throw new E("Only zip files are supported",{field:"file",originalName:t.originalname});const h=String(e),f=String(r),o=i&&i.trim()?i.trim():A(a,h,f),g=p.join(o,".tmp"),w=p.join(g,`import_project_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);let d=null;m(l,"INFO","Start importing project from zip",{userId:h,cId:f,targetDir:o,fileName:t.originalname});try{await c.promises.mkdir(o,{recursive:!0}),await c.promises.mkdir(g,{recursive:!0}),await c.promises.mkdir(w,{recursive:!0}),await Fe(t.path,w),await ge(w,l),d=p.join(g,`import_backup_${Date.now()}_${Math.round(Math.random()*1e6)}`),await Xe(o,d,l);try{await Ge(w,o,l)}catch(y){throw m(l,"ERROR","Merge imported project failed, restoring workspace",{error:y.message,mergedEntries:y.mergedEntries||[]}),await Be(o,l),await Ve(d,o,l),y}return c.existsSync(d)&&(await c.promises.rm(d,{recursive:!0,force:!0}),d=null),m(l,"INFO","Project imported successfully",{userId:h,cId:f,targetDir:o,elapsedMs:Date.now()-n}),{success:!0,message:"Project imported successfully",userId:h,cId:f,targetDir:o}}catch(y){throw m(l,"ERROR","Failed to import project",{userId:h,cId:f,targetDir:o,error:y.message,elapsedMs:Date.now()-n}),y instanceof E||y instanceof L||y instanceof Re?y:new L(`Failed to import project: ${y.message}`,{userId:h,cId:f,originalError:y.message})}finally{if(c.existsSync(w))try{await c.promises.rm(w,{recursive:!0,force:!0})}catch(y){m(l,"WARN","Failed to clean import extract directory",{extractRoot:w,error:y.message})}if(d&&c.existsSync(d))try{await c.promises.rm(d,{recursive:!0,force:!0})}catch(y){m(l,"WARN","Failed to clean import backup directory",{backupDir:d,error:y.message})}if(t?.path&&c.existsSync(t.path))try{await c.promises.unlink(t.path)}catch(y){m(l,"WARN","Failed to clean uploaded zip file",{tempZipPath:t.path,error:y.message})}}}async function He(e,r,t,i,a,n=null){const l=`computer:${e}:${r}`;if(!t||typeof t!="string"||!t.trim())throw new E("fileName cannot be empty",{field:"fileName"});if(i!=null&&typeof i!="string")throw new E("content must be a string",{field:"content"});const u=t.trim(),s=i??"";return m(l,"INFO","Generate file from text content",{userId:e,cId:r,fileName:u,contentLength:s.length}),{...await re(e,r,{contents:s,originalname:p.basename(u),size:Buffer.byteLength(s,"utf8")},u,a,n),message:"File generated successfully",fileName:u}}export{Te as getFileList,Ae as getFileMeta,ke as resolveExistingFile,$e as searchFiles,Me as updateFiles,re as uploadFile,We as uploadFiles,He as generateFile,Ue as downloadAllFiles,je as getLatestLogs,qe as importProject,j as IMPORT_PROJECT_PRESERVED_ENTRIES,ge as removeTopLevelDir};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import m from"fs";import w from"os";import h from"path";import{ValidationError as o}from"../error/errorHandler.js";function a(t){const r=t.startsWith("\\\\")||t.startsWith("//");let e=String(t).replace(/\\/g,"/").replace(/\/{2,}/g,"/");return r&&(e="/"+e),e}export async function listFsRoots(){const t=a(w.homedir()),r=[];if(process.platform==="win32")for(let e=65;e<=90;e++){const n=String.fromCharCode(e)+":/";try{await m.promises.stat(n),r.push({name:n,path:n,isDir:!0})}catch{}}else r.push({name:"/",path:"/",isDir:!0});return{roots:r,home:t}}function p(t,r="path"){if(!t||typeof t!="string"||t.includes("\0"))throw new o(`${r} is required`,{field:r});if(!h.isAbsolute(t))throw new o(`${r} must be absolute`,{field:r})}function u(t,r){const e=String(t??"").trim();if(!e||e.includes("\0"))throw new o(`${r} is required`,{field:r});if(e.includes("/")||e.includes("\\"))throw new o(`${r} must not contain path separators`,{field:r});if(e==="."||e==="..")throw new o(`${r} must not be a relative segment`,{field:r});if(e.length>255)throw new o(`${r} exceeds 255 characters`,{field:r});return e}export async function listFsChildren(t){p(t);let r;try{r=await m.promises.readdir(t,{withFileTypes:!0})}catch(n){throw new o(`cannot read directory (${n.code||n.message})`,{field:"path"})}const e=[];for(const n of r){let i=n.isDirectory();const c=n.isSymbolicLink();if(c)try{i=(await m.promises.stat(h.join(t,n.name))).isDirectory()}catch{}e.push({name:n.name,path:a(h.join(t,n.name)),isDir:i,isSymlink:c})}return e.sort((n,i)=>Number(i.isDir)-Number(n.isDir)||n.name.localeCompare(i.name,void 0,{sensitivity:"base",numeric:!0})),{path:a(t),entries:e}}export async function createFsDirectory(t,r){p(t,"parentPath");const e=u(r,"dirName"),n=h.join(t,e);try{await m.promises.mkdir(n)}catch(i){throw i.code==="EEXIST"?new o(`directory already exists: ${e}`,{field:"dirName"}):i.code==="ENOENT"?new o("parent directory does not exist",{field:"parentPath"}):new o(`cannot create directory (${i.code||i.message})`,{field:"dirName"})}return{path:a(n),name:e,parentPath:a(t),isDir:!0,isSymlink:!1}}export async function renameFsDirectory(t,r){p(t);const e=u(r,"newName"),n=h.dirname(t);if(n===t)throw new o("cannot rename the root directory",{field:"path"});const i=h.join(n,e);let c;try{await m.promises.stat(i),c=!0}catch(s){if(s.code!=="ENOENT")throw new o(`cannot rename (${s.code||s.message})`,{field:"path"});c=!1}if(c)throw new o(`name already exists: ${e}`,{field:"newName"});try{await m.promises.rename(t,i)}catch(s){throw s.code==="ENOENT"?new o("directory does not exist",{field:"path"}):new o(`cannot rename directory (${s.code||s.message})`,{field:"newName"})}return{path:a(i),name:e,parentPath:a(n),isDir:!0,isSymlink:!1}}
|
package/package.json
CHANGED