nuwax-file-server 1.3.0-beta.12 → 1.3.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.3.0-beta.12",d=new ee,w={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"};function j(e){console.error(`${w.red}ERROR: ${e}${w.reset}`)}function b(e){console.log(`${w.green}${e}${w.reset}`)}function oe(e){console.log(`${w.blue}${e}${w.reset}`)}function y(e){return async(...t)=>{try{let o=await e(...t);o&&o.success===!1?(j(o.message||"Command failed"),process.exitCode=1):process.exitCode=0}catch(o){j(o?.message||"Command failed with unexpected error"),process.exitCode=1}}}async function se(e){let t=await N({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(`Service started (PID: ${t.pid})`),t}async function re(e){let t=await T({force:e.force,timeout:Number(e.timeout)});return t.success&&b(t.message||"Service stopped"),t}async function ne(e){let t=await O({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(t.message||"Service restarted"),t}function ie(){let e=_();return oe(`${n.name} service status:`),console.log(""),console.log(` Service name: ${n.name}`),console.log(` Running status: ${e.running?"Running":"Stopped"}`),console.log(` Message: ${e.message}`),console.log(` PID file: ${$()}`),e.pidInfo&&(console.log(` Process ID: ${e.pidInfo.pid}`),console.log(` Environment: ${e.pidInfo.env||"Unknown"}`),console.log(` Port: ${e.pidInfo.port||"Unknown"}`),console.log(` Version: ${e.pidInfo.version||A}`),console.log(` Platform: ${e.pidInfo.platform||process.platform}`),console.log(` Started at: ${e.pidInfo.startedAt||"Unknown"}`),console.log(` Uptime: ${L(e.pidInfo.startedAt)}`)),console.log(""),{success:e.running,message:e.message}}function ce(){d.name("nuwax-file-server").description("Cross-platform file service deployment tool, supporting start/stop/restart/status").version(A,"-v, --version","Display version number").helpOption("-h, --help","Display help information"),d.command("start").allowUnknownOption().description("Start service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(se)),d.command("stop").description("Stop service").option("--force","Force stop").option("--timeout <ms>","\u505C\u6B62\u670D\u52A1\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).action(y(re)),d.command("restart").allowUnknownOption().description("Restart service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(ne)),d.command("status").description("View service status").action(y(ie)),d.command("help").description("Display help information").action(()=>{d.outputHelp()}),d.parse(process.argv),process.argv.slice(2).length||(d.outputHelp(),process.exitCode=0)}ce();
2
+ import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.3.0-beta.13",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 C from"express";import k from"multer";import u from"fs";import I from"path";import{ValidationError as z,asyncHandler as p}from"../utils/error/errorHandler.js";import{log as d}from"../utils/log/logUtils.js";import F from"../appConfig/index.js";import{createWorkspace as S,pushSkillsToWorkspace as $,initProjectTemplate as A,executeCommand as b,deleteWorkspace as j}from"../utils/computer/computerUtils.js";import{getFileList as O,updateFiles as E,uploadFile as P,uploadFiles as U,downloadAllFiles as R}from"../utils/computer/computerFileUtils.js";const g=C.Router(),y=k({storage:k.diskStorage({destination:(e,i,o)=>{try{const t=F.COMPUTER_WORKSPACE_DIR;if(!t)return o(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const s=e.body?.userId||"unknown",a=e.body?.cId||"unknown",n=I.join(t,String(s),String(a),".tmp");u.existsSync(n)||u.mkdirSync(n,{recursive:!0}),o(null,n)}catch(t){o(t)}},filename:(e,i,o)=>{const t=I.extname(i.originalname)||".zip",s=I.basename(i.originalname,t),a=`${Date.now()}_${Math.round(Math.random()*1e6)}`;o(null,`${s}_${a}${t}`)}}),limits:{fileSize:F.UPLOAD_MAX_FILE_SIZE_BYTES}});function x(e,i,o,t){if(e&&e.name==="MulterError"||e&&(e.name==="ValidationError"||e instanceof z))return t(e);t(e)}const D=[{path:"/create-workspace",method:"post",middleware:y.single("file"),handler:p(async(e,i)=>{const{userId:o,cId:t}=e.body||{},s=e.file||null,a=`computer:${o}:${t}`;d(a,"INFO","Create workspace request",{userId:o,cId:t,hasFile:!!s,fileName:s?.originalname,fileSize:s?.size});const n=await S(o,t,s);i.status(200).json({success:!0,...n})})},{path:"/create-workspace-v2",method:"post",middleware:y.single("file"),handler:p(async(e,i)=>{const{userId:o,cId:t,skillUrls:s,mcpServersConfig:a,hooksConfig:n,permissionsConfig:r,hookScripts:l}=e.body||{},m=e.file||null,f=`computer:${o}:${t}`;let c=s;if(typeof s=="string")try{const w=JSON.parse(s);c=Array.isArray(w)?w:[s]}catch{c=[s]}let h=l;if(typeof l=="string")try{h=JSON.parse(l)}catch{h=null}d(f,"INFO","Create workspace v2 request",{userId:o,cId:t,hasFile:!!m,fileName:m?.originalname,fileSize:m?.size,skillUrlsCount:Array.isArray(c)?c.length:0,hasMcpServersConfig:!!a,hasHooksConfig:!!n,hasPermissionsConfig:!!r,hookScriptsCount:Array.isArray(h)?h.length:0});const N=await S(o,t,m,c,a,r,n,h);i.status(200).json({success:!0,...N})})},{path:"/push-skills-to-workspace",method:"post",middleware:y.single("file"),handler:p(async(e,i)=>{const{userId:o,cId:t}=e.body||{},s=e.file||null,a=`computer:${o}:${t}`;d(a,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:o,cId:t,hasFile:!!s,fileName:s?.originalname,fileSize:s?.size});const n=await $(o,t,s);i.status(200).json({success:!0,...n})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:y.single("file"),handler:p(async(e,i)=>{const{userId:o,cId:t,skillUrls:s}=e.body||{},a=e.file||null,n=`computer:${o}:${t}`;let r=s;if(typeof s=="string")try{const m=JSON.parse(s);r=Array.isArray(m)?m:[s]}catch{r=[s]}d(n,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:o,cId:t,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size,skillUrlsCount:Array.isArray(r)?r.length:0});const l=await $(o,t,a,r);i.status(200).json({success:!0,...l})})},{path:"/get-file-list",method:"get",handler:p(async(e,i)=>{const{userId:o,cId:t,proxyPath:s}=e.query,a=await O(o,t,s);i.status(200).json({success:!0,...a})})},{path:"/files-update",method:"post",handler:p(async(e,i)=>{const{userId:o,cId:t,files:s}=e.body||{},a=`computer:${o}:${t}`;d(a,"INFO","Files update",{userId:o,cId:t,filesCount:s?s.length:0}),s&&Array.isArray(s)&&s.forEach(r=>{if(r&&typeof r.contents=="string"&&r.contents)try{r.contents=decodeURIComponent(r.contents)}catch(l){d(a,"WARN","Decode file content failed",{fileName:r.name,error:l.message})}});const n=await E(o,t,s);i.status(200).json(n)})},{path:"/upload-file",method:"post",middleware:y.single("file"),handler:p(async(e,i)=>{const{userId:o,cId:t,filePath:s}=e.body||{},a=e.file,n=`computer:${o}:${t}`;d(n,"INFO","Upload single file",{userId:o,cId:t,filePath:s});const l={buffer:await u.promises.readFile(a.path),originalname:a.originalname,mimetype:a.mimetype,size:a.size};try{const m=await P(o,t,l,s);i.status(200).json(m)}finally{u.existsSync(a.path)&&await u.promises.unlink(a.path)}})},{path:"/upload-files",method:"post",middleware:y.array("files"),handler:p(async(e,i)=>{const{userId:o,cId:t,filePaths:s}=e.body||{},a=e.files||[],n=`computer:${o}:${t}`,r=Array.isArray(s)?s:typeof s=="string"?[s]:s;d(n,"INFO","Batch upload files request",{userId:o,cId:t,filesCount:a.length,filePathsCount:Array.isArray(r)?r.length:0});const l=[],m=[];try{for(const c of a){m.push(c.path);const h=await u.promises.readFile(c.path);l.push({buffer:h,originalname:c.originalname,mimetype:c.mimetype,size:c.size})}const f=await U(o,t,l,r);i.status(200).json(f)}finally{for(const f of m)if(u.existsSync(f))try{await u.promises.unlink(f)}catch(c){d(n,"WARN","Clean temporary file failed",{tempPath:f,error:c.message})}}})},{path:"/init-project-template",method:"post",middleware:y.single("file"),handler:p(async(e,i)=>{const{userId:o,cId:t,enableGit:s}=e.body||{},a=e.file||null,n=`computer:${o}:${t}`;d(n,"INFO","Init project template request",{userId:o,cId:t,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size,enableGit:s});const r=await A(o,t,a,s);i.status(200).json({success:!0,...r})})},{path:"/download-all-files",method:"get",handler:p(async(e,i)=>{const{userId:o,cId:t}=e.query||{},s=`computer:${o}:${t}`;d(s,"INFO","Download all files request",{userId:o,cId:t});const{archive:a,zipFileName:n}=await R(o,t);i.setHeader("Content-Type","application/zip");const r=encodeURIComponent(n);i.setHeader("Content-Disposition",`attachment; filename="${r}"; filename*=UTF-8''${r}`),a.on("error",l=>{i.destroy(l)}),a.pipe(i),a.finalize()})},{path:"/execute-command",method:"post",handler:p(async(e,i)=>{const{userId:o,cId:t,command:s}=e.body||{},a=`computer:${o}:${t}`;d(a,"INFO","Execute command request",{userId:o,cId:t,command:s});const n=await b(o,t,s);i.status(200).json({success:!0,...n})})},{path:"/delete-workspace",method:"post",handler:p(async(e,i)=>{const{userId:o,cId:t}=e.body||{},s=`computer:${o}:${t}`;d(s,"INFO","Delete workspace request",{userId:o,cId:t});const a=await j(o,t);i.status(200).json({success:!0,...a})})}];D.forEach(e=>{if(e.middleware)g[e.method](e.path,e.middleware,e.handler);else if(e.customHandler){const i=[];e.handler&&i.push(e.handler),e.decodeMiddleware&&i.push(e.decodeMiddleware),i.push(x),i.push(e.customHandler),g[e.method](e.path,...i)}else g[e.method](e.path,e.handler)});export default g;
1
+ import C from"express";import k from"multer";import u from"fs";import I from"path";import{ValidationError as z,asyncHandler as d}from"../utils/error/errorHandler.js";import{log as m}from"../utils/log/logUtils.js";import F from"../appConfig/index.js";import{createWorkspace as S,pushSkillsToWorkspace as $,initProjectTemplate as A,executeCommand as b,deleteWorkspace as j}from"../utils/computer/computerUtils.js";import{getFileList as O,updateFiles as E,uploadFile as P,uploadFiles as U,downloadAllFiles as R,getLatestLogs as x}from"../utils/computer/computerFileUtils.js";const g=C.Router(),y=k({storage:k.diskStorage({destination:(e,i,o)=>{try{const s=F.COMPUTER_WORKSPACE_DIR;if(!s)return o(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const t=e.body?.userId||"unknown",a=e.body?.cId||"unknown",n=I.join(s,String(t),String(a),".tmp");u.existsSync(n)||u.mkdirSync(n,{recursive:!0}),o(null,n)}catch(s){o(s)}},filename:(e,i,o)=>{const s=I.extname(i.originalname)||".zip",t=I.basename(i.originalname,s),a=`${Date.now()}_${Math.round(Math.random()*1e6)}`;o(null,`${t}_${a}${s}`)}}),limits:{fileSize:F.UPLOAD_MAX_FILE_SIZE_BYTES}});function D(e,i,o,s){if(e&&e.name==="MulterError"||e&&(e.name==="ValidationError"||e instanceof z))return s(e);s(e)}const _=[{path:"/create-workspace",method:"post",middleware:y.single("file"),handler:d(async(e,i)=>{const{userId:o,cId:s}=e.body||{},t=e.file||null,a=`computer:${o}:${s}`;m(a,"INFO","Create workspace request",{userId:o,cId:s,hasFile:!!t,fileName:t?.originalname,fileSize:t?.size});const n=await S(o,s,t);i.status(200).json({success:!0,...n})})},{path:"/create-workspace-v2",method:"post",middleware:y.single("file"),handler:d(async(e,i)=>{const{userId:o,cId:s,skillUrls:t,mcpServersConfig:a,hooksConfig:n,permissionsConfig:r,hookScripts:l}=e.body||{},p=e.file||null,f=`computer:${o}:${s}`;let c=t;if(typeof t=="string")try{const w=JSON.parse(t);c=Array.isArray(w)?w:[t]}catch{c=[t]}let h=l;if(typeof l=="string")try{h=JSON.parse(l)}catch{h=null}m(f,"INFO","Create workspace v2 request",{userId:o,cId:s,hasFile:!!p,fileName:p?.originalname,fileSize:p?.size,skillUrlsCount:Array.isArray(c)?c.length:0,hasMcpServersConfig:!!a,hasHooksConfig:!!n,hasPermissionsConfig:!!r,hookScriptsCount:Array.isArray(h)?h.length:0});const N=await S(o,s,p,c,a,r,n,h);i.status(200).json({success:!0,...N})})},{path:"/push-skills-to-workspace",method:"post",middleware:y.single("file"),handler:d(async(e,i)=>{const{userId:o,cId:s}=e.body||{},t=e.file||null,a=`computer:${o}:${s}`;m(a,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:o,cId:s,hasFile:!!t,fileName:t?.originalname,fileSize:t?.size});const n=await $(o,s,t);i.status(200).json({success:!0,...n})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:y.single("file"),handler:d(async(e,i)=>{const{userId:o,cId:s,skillUrls:t}=e.body||{},a=e.file||null,n=`computer:${o}:${s}`;let r=t;if(typeof t=="string")try{const p=JSON.parse(t);r=Array.isArray(p)?p:[t]}catch{r=[t]}m(n,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:o,cId:s,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size,skillUrlsCount:Array.isArray(r)?r.length:0});const l=await $(o,s,a,r);i.status(200).json({success:!0,...l})})},{path:"/get-file-list",method:"get",handler:d(async(e,i)=>{const{userId:o,cId:s,proxyPath:t}=e.query,a=await O(o,s,t);i.status(200).json({success:!0,...a})})},{path:"/files-update",method:"post",handler:d(async(e,i)=>{const{userId:o,cId:s,files:t}=e.body||{},a=`computer:${o}:${s}`;m(a,"INFO","Files update",{userId:o,cId:s,filesCount:t?t.length:0}),t&&Array.isArray(t)&&t.forEach(r=>{if(r&&typeof r.contents=="string"&&r.contents)try{r.contents=decodeURIComponent(r.contents)}catch(l){m(a,"WARN","Decode file content failed",{fileName:r.name,error:l.message})}});const n=await E(o,s,t);i.status(200).json(n)})},{path:"/upload-file",method:"post",middleware:y.single("file"),handler:d(async(e,i)=>{const{userId:o,cId:s,filePath:t}=e.body||{},a=e.file,n=`computer:${o}:${s}`;m(n,"INFO","Upload single file",{userId:o,cId:s,filePath:t});const l={buffer:await u.promises.readFile(a.path),originalname:a.originalname,mimetype:a.mimetype,size:a.size};try{const p=await P(o,s,l,t);i.status(200).json(p)}finally{u.existsSync(a.path)&&await u.promises.unlink(a.path)}})},{path:"/upload-files",method:"post",middleware:y.array("files"),handler:d(async(e,i)=>{const{userId:o,cId:s,filePaths:t}=e.body||{},a=e.files||[],n=`computer:${o}:${s}`,r=Array.isArray(t)?t:typeof t=="string"?[t]:t;m(n,"INFO","Batch upload files request",{userId:o,cId:s,filesCount:a.length,filePathsCount:Array.isArray(r)?r.length:0});const l=[],p=[];try{for(const c of a){p.push(c.path);const h=await u.promises.readFile(c.path);l.push({buffer:h,originalname:c.originalname,mimetype:c.mimetype,size:c.size})}const f=await U(o,s,l,r);i.status(200).json(f)}finally{for(const f of p)if(u.existsSync(f))try{await u.promises.unlink(f)}catch(c){m(n,"WARN","Clean temporary file failed",{tempPath:f,error:c.message})}}})},{path:"/init-project-template",method:"post",middleware:y.single("file"),handler:d(async(e,i)=>{const{userId:o,cId:s,enableGit:t}=e.body||{},a=e.file||null,n=`computer:${o}:${s}`;m(n,"INFO","Init project template request",{userId:o,cId:s,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size,enableGit:t});const r=await A(o,s,a,t);i.status(200).json({success:!0,...r})})},{path:"/download-all-files",method:"get",handler:d(async(e,i)=>{const{userId:o,cId:s}=e.query||{},t=`computer:${o}:${s}`;m(t,"INFO","Download all files request",{userId:o,cId:s});const{archive:a,zipFileName:n}=await R(o,s);i.setHeader("Content-Type","application/zip");const r=encodeURIComponent(n);i.setHeader("Content-Disposition",`attachment; filename="${r}"; filename*=UTF-8''${r}`),a.on("error",l=>{i.destroy(l)}),a.pipe(i),a.finalize()})},{path:"/execute-command",method:"post",handler:d(async(e,i)=>{const{userId:o,cId:s,command:t}=e.body||{},a=`computer:${o}:${s}`;m(a,"INFO","Execute command request",{userId:o,cId:s,command:t});const n=await b(o,s,t);i.status(200).json({success:!0,...n})})},{path:"/delete-workspace",method:"post",handler:d(async(e,i)=>{const{userId:o,cId:s}=e.body||{},t=`computer:${o}:${s}`;m(t,"INFO","Delete workspace request",{userId:o,cId:s});const a=await j(o,s);i.status(200).json({success:!0,...a})})},{path:"/get-logs",method:"get",handler:d(async(e,i)=>{const{userId:o,cId:s,tailLines:t}=e.query,a=t?parseInt(t,10):200,n=Number.isFinite(a)&&a>0?a:200,r=await x(o,s,n);i.status(200).json({success:!0,...r})})}];_.forEach(e=>{if(e.middleware)g[e.method](e.path,e.middleware,e.handler);else if(e.customHandler){const i=[];e.handler&&i.push(e.handler),e.decodeMiddleware&&i.push(e.decodeMiddleware),i.push(D),i.push(e.customHandler),g[e.method](e.path,...i)}else g[e.method](e.path,e.handler)});export default g;
@@ -1 +1,2 @@
1
- import m from"fs";import h from"path";import N from"archiver";import I from"../../appConfig/index.js";import{log as r}from"../log/logUtils.js";import{ValidationError as g,SystemError as D}from"../error/errorHandler.js";const A=100*1024*1024,P=I.DOWNLOAD_MAX_FILE_SIZE_BYTES||A;async function O(f,u,a,c){const n=[],w=await m.promises.readdir(f,{withFileTypes:!0});w.sort((t,s)=>t.isDirectory()&&!s.isDirectory()?-1:!t.isDirectory()&&s.isDirectory()?1:t.name.toLowerCase().localeCompare(s.name.toLowerCase()));for(const t of w){const s=h.join(f,t.name);if(!(t.name.startsWith(".")&&t.name!==".gitignore"||(I.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(t.name))&&!(t.isDirectory()&&I.TRAVERSE_EXCLUDE_DIRS.includes(t.name)))if(t.isDirectory()){const e=await O(s,u,a,c);if(e.length===0){const l=u||f,p=h.relative(l,s).replace(/\\/g,"/");n.push({name:p,isDir:!0})}else n.push(...e)}else try{const e=u||f,l=h.relative(e,s).replace(/\\/g,"/"),p=t.isSymbolicLink();let o=null;if(c){const y=l.split("/").map(R=>encodeURIComponent(R)).join("/");o=`${c}/${y}`}const i={name:l,isDir:!1,fileProxyUrl:o,isLink:p};n.push(i)}catch(e){r(a,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${s}`,{error:e.message})}}return n}async function k(f,u,a,c,n=""){const w=await m.promises.readdir(h.join(f,n),{withFileTypes:!0});let t=0;for(const s of w){const d=n?h.join(n,s.name):s.name,e=d.split(h.sep).filter(Boolean);if(e.some(i=>i.startsWith(".")))continue;const l=e[e.length-1];if(u.includes(l)||e.some(i=>a.includes(i)))continue;const p=h.join(f,d);let o;try{o=await m.promises.lstat(p)}catch(i){r(c,"WARN","Error occurred when getting file stats, skipping",{filePath:d.replace(/\\/g,"/"),error:i.message});continue}o.isSymbolicLink()||o.nlink>1||(o.isDirectory()?t+=await k(f,u,a,c,d):o.isFile()&&(t+=o.size))}return t}async function $(f,u,a){const c=Date.now(),n=`computer:${f}:${u}`,w=I.COMPUTER_WORKSPACE_DIR;if(!f)throw new g("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!u)throw new g("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const t=String(f),s=String(u),d=h.join(w,t,s);if(!m.existsSync(d))return r(n,"INFO","Directory does not exist, returning empty list",{targetDir:d,userId:t,cId:s}),{files:[]};r(n,"DEBUG","Start getting user file list",{targetDir:d,userId:t,cId:s});try{const e=await O(d,d,n,a);return r(n,"INFO","User file list obtained successfully",{fileCount:e.length,targetDir:d,userId:t,cId:s,elapsedMs:Date.now()-c}),{files:e}}catch(e){throw r(n,"ERROR","Failed to get user file list",{targetDir:d,userId:t,cId:s,error:e.message,elapsedMs:Date.now()-c}),new D(`Failed to get file list: ${e.message}`,{targetDir:d,originalError:e.message})}}async function _(f,u,a){const c=Date.now(),n=`computer:${f}:${u}`,w=I.COMPUTER_WORKSPACE_DIR;if(!f)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!Array.isArray(a))throw new g("files must be an array",{field:"files"});const t=String(f),s=String(u),d=h.join(w,t,s);m.existsSync(d)||m.mkdirSync(d,{recursive:!0});for(let e=0;e<a.length;e++){const l=a[e];if(!l||typeof l.operation!="string")throw new g(`files[${e}].operation cannot be empty`,{field:`files[${e}].operation`});if(!l.name||typeof l.name!="string")throw new g(`files[${e}].name cannot be empty`,{field:`files[${e}].name`});const p=l.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(p))throw new g(`files[${e}].operation must be one of create, delete, rename or modify`,{field:`files[${e}].operation`});if(p==="rename"&&!l.renameFrom)throw new g(`files[${e}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${e}].renameFrom`});if(p==="modify"&&l.isDir!==!0&&typeof l.contents!="string")throw new g(`files[${e}].contents must be a string (modify operation requires)`,{field:`files[${e}].contents`})}r(n,"DEBUG","Start updating user files",{userId:t,cId:s,filesCount:a.length});try{for(const e of a){const l=e.operation.toLowerCase(),p=e.name,o=h.normalize(p).replace(/^[\/\\]+/,""),i=h.join(d,o),y=h.resolve(i),R=h.resolve(d);if(!y.startsWith(R+h.sep)&&y!==R){r(n,"WARN","File path is not secure, skipping",{filePath:o,resolvedPath:y});continue}switch(l){case"create":{if(e.isDir===!0){if(m.existsSync(i)){if((await m.promises.stat(i)).isFile())throw new g("Cannot create directory, file with the same name already exists",{filePath:o});r(n,"INFO","Directory already exists, skipping creation",{filePath:o});break}await m.promises.mkdir(i,{recursive:!0}),r(n,"INFO","Directory created successfully",{filePath:o});break}if(m.existsSync(i)){if((await m.promises.stat(i)).isDirectory())throw new g("Cannot create file, directory with the same name already exists",{filePath:o});r(n,"INFO","File already exists, skipping creation",{filePath:o});break}await m.promises.mkdir(h.dirname(i),{recursive:!0});const F=e.contents||"";await m.promises.writeFile(i,F,"utf8"),r(n,"INFO","File created successfully",{filePath:o});break}case"delete":{m.existsSync(i)?(await m.promises.stat(i)).isDirectory()?(await m.promises.rm(i,{recursive:!0,force:!0}),r(n,"INFO","Directory deleted successfully",{filePath:o})):(await m.promises.unlink(i),r(n,"INFO","File deleted successfully",{filePath:o})):r(n,"WARN","The file or directory to be deleted does not exist",{filePath:o});break}case"rename":{const F=e.renameFrom;if(!F||typeof F!="string"){r(n,"WARN","Rename operation missing renameFrom",{filePath:o});break}const E=h.normalize(F).replace(/^[\/\\]+/,""),S=h.join(d,E),b=h.resolve(S);if(!b.startsWith(R+h.sep)&&b!==R){r(n,"WARN","Source path is not secure, skipping rename",{sourcePath:E,targetPath:o});break}if(m.existsSync(S)){const C=(await m.promises.stat(S)).isDirectory();await m.promises.mkdir(h.dirname(i),{recursive:!0}),await m.promises.rename(S,i),r(n,"INFO",C?"Directory renamed successfully":"File renamed successfully",{sourcePath:E,targetPath:o})}else r(n,"WARN","The file or directory to be renamed does not exist",{sourcePath:E});break}case"modify":{if(!m.existsSync(i)){r(n,"WARN","The file to be modified does not exist",{filePath:o});break}if((await m.promises.stat(i)).isDirectory()){r(n,"INFO","The target is a directory, skipping modification",{filePath:o});break}const E=typeof e.contents=="string"?e.contents:"";if(await m.promises.readFile(i,"utf8")===E){r(n,"INFO","File content has no changes, skipping write",{filePath:o});break}await m.promises.writeFile(i,E,"utf8"),r(n,"INFO","File modified successfully",{filePath:o});break}default:{r(n,"WARN","Unsupported operation type",{operation:l,filePath:o});break}}}return r(n,"INFO","User files updated successfully",{userId:t,cId:s,filesCount:a.length,elapsedMs:Date.now()-c}),{success:!0,message:"User files updated successfully",userId:t,cId:s,filesCount:a.length}}catch(e){throw r(n,"ERROR","User files updated failed",{userId:t,cId:s,error:e.message,elapsedMs:Date.now()-c}),new D(`User files updated failed: ${e.message}`,{userId:t,cId:s,originalError:e.message})}}async function z(f,u,a,c){const n=Date.now(),w=`computer:${f}:${u}`,t=I.COMPUTER_WORKSPACE_DIR;if(!f)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!a)throw new g("file cannot be empty",{field:"file"});if(!c||typeof c!="string")throw new g("filePath cannot be empty",{field:"filePath"});const s=String(f),d=String(u),e=h.join(t,s,d);m.existsSync(e)||m.mkdirSync(e,{recursive:!0});const l=h.normalize(c).replace(/^[\/\\]+/,""),p=h.join(e,l),o=h.resolve(p),i=h.resolve(e);if(!o.startsWith(i+h.sep)&&o!==i)throw new g("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:c,resolvedPath:o});try{if(await m.promises.mkdir(h.dirname(p),{recursive:!0}),a.buffer)await m.promises.writeFile(p,a.buffer);else if(typeof a.contents=="string")await m.promises.writeFile(p,a.contents,"utf8");else throw new g("File content format is incorrect",{field:"file",hasBuffer:!!a.buffer,hasContents:typeof a.contents});return r(w,"INFO","File uploaded successfully",{userId:s,cId:d,filePath:l,targetPath:o,fileSize:a.buffer?a.buffer.length:a.contents?a.contents.length:0,elapsedMs:Date.now()-n}),{success:!0,message:"File uploaded successfully",fileSize:a.buffer?a.buffer.length:a.contents?a.contents.length:0}}catch(y){throw r(w,"ERROR","File upload failed",{userId:s,cId:d,filePath:l,error:y.message,elapsedMs:Date.now()-n}),new D(`File upload failed: ${y.message}`,{userId:s,cId:d,filePath:l,originalError:y.message})}}async function T(f,u,a,c){const n=Date.now(),w=`computer:${f}:${u}`;if(!f)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!Array.isArray(a))throw new g("files must be an array",{field:"files"});if(!Array.isArray(c))throw new g("filePaths must be an array",{field:"filePaths"});if(a.length!==c.length)throw new g(`File count (${a.length}) does not match path count (${c.length})`,{field:"filePaths"});r(w,"DEBUG","Start batch uploading files",{userId:f,cId:u,filesCount:a.length});const t=[];try{for(let e=0;e<a.length;e++){const l=a[e],p=c[e];if(!l){r(w,"WARN","Empty file object encountered in batch upload, skipping",{index:e,filePath:p}),t.push({success:!1,filePath:p,error:"Empty file object"});continue}if(!p||typeof p!="string"){r(w,"WARN","Invalid file path in batch upload, skipping",{index:e,originalname:l.originalname}),t.push({success:!1,filePath:p||"",originalname:l.originalname,error:"Invalid file path"});continue}try{const o=await z(f,u,l,p);t.push({success:!0,filePath:p,originalname:l.originalname,...o})}catch(o){r(w,"ERROR","Single file upload failed in batch upload",{filePath:p,originalname:l.originalname,error:o.message}),t.push({success:!1,filePath:p,originalname:l.originalname,error:o.message})}}const s=t.filter(e=>e.success).length,d=t.filter(e=>!e.success).length;return r(w,"INFO","Batch upload files completed",{userId:f,cId:u,totalCount:a.length,successCount:s,failCount:d,elapsedMs:Date.now()-n}),{success:!0,message:"Batch upload completed",totalCount:a.length,successCount:s,failCount:d,results:t}}catch(s){throw r(w,"ERROR","Batch upload files failed",{userId:f,cId:u,error:s.message,elapsedMs:Date.now()-n}),new D(`Batch upload files failed: ${s.message}`,{userId:f,cId:u,originalError:s.message})}}async function v(f,u){const a=Date.now(),c=`computer:${f}:${u}`,n=I.COMPUTER_WORKSPACE_DIR;if(!f)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!n)throw new D("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const w=String(f),t=String(u),s=h.join(n,w,t);if(!m.existsSync(s)){const i=`${w}_${t}.zip`;r(c,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:s,userId:w,cId:t,zipFileName:i});const y=N("zip",{zlib:{level:9}});return y.append(null,{name:`${w}_${t}/`,type:"directory"}),y.on("warning",R=>{if(R.code==="ENOENT")r(c,"WARN","Encountered file problem when creating empty zip",{message:R.message,code:R.code});else throw r(c,"ERROR","Encountered warning when creating empty zip",{message:R.message,code:R.code}),R}),y.on("error",R=>{r(c,"ERROR","Failed to create empty zip",{message:R.message})}),{archive:y,zipFileName:i}}const d=`${w}_${t}.zip`;r(c,"DEBUG","Start creating workspace directory zip",{targetDir:s,zipFileName:d});const e=N("zip",{zlib:{level:9}}),l=I.CONTENT_TRAVERSE_EXCLUDE_FILES||[],p=I.TRAVERSE_EXCLUDE_DIRS||[],o=await k(s,l,p,c);if(o>P){const i=P/1024/1024,y=(o/1024/1024).toFixed(2);throw r(c,"WARN","Download rejected due to oversized workspace",{targetDir:s,downloadableSize:o,maxSizeBytes:P}),new g(`Download failed: total file size ${y}MB exceeds limit ${i}MB`,{field:"downloadSize",downloadableSize:o,maxSizeBytes:P})}return e.directory(s,`${w}_${t}`,i=>{const y=i.name||"",R=y.split(/[\/\\]/).filter(Boolean);if(R.some(E=>E.startsWith(".")))return!1;const F=R[R.length-1];if(l.includes(F)||R.some(E=>p.includes(E)))return!1;try{const E=h.join(s,y),S=m.lstatSync(E);if(S.isSymbolicLink()||S.nlink>1)return!1}catch(E){return r(c,"WARN","Error occurred when detecting link file, skipping",{filePath:y,error:E.message}),!1}return i}),e.on("warning",i=>{if(i.code==="ENOENT")r(c,"WARN","Encountered file problem when creating zip",{message:i.message,code:i.code});else throw r(c,"ERROR","Encountered warning when creating zip",{message:i.message,code:i.code}),i}),e.on("error",i=>{r(c,"ERROR","Failed to create zip",{message:i.message,elapsedMs:Date.now()-a})}),e.on("end",()=>{r(c,"INFO","Workspace directory zip created successfully",{targetDir:s,zipFileName:d,elapsedMs:Date.now()-a})}),{archive:e,zipFileName:d}}export{$ as getFileList,_ as updateFiles,z as uploadFile,T as uploadFiles,v as downloadAllFiles};
1
+ import m from"fs";import h from"path";import z from"archiver";import I from"../../appConfig/index.js";import{log as s}from"../log/logUtils.js";import{ValidationError as g,SystemError as P}from"../error/errorHandler.js";const _=100*1024*1024,b=I.DOWNLOAD_MAX_FILE_SIZE_BYTES||_;async function N(d,u,a,c){const i=[],w=await m.promises.readdir(d,{withFileTypes:!0});w.sort((n,o)=>n.isDirectory()&&!o.isDirectory()?-1:!n.isDirectory()&&o.isDirectory()?1:n.name.toLowerCase().localeCompare(o.name.toLowerCase()));for(const n of w){const o=h.join(d,n.name);if(!(n.name.startsWith(".")&&n.name!==".gitignore"||(I.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(n.name))&&!(n.isDirectory()&&I.TRAVERSE_EXCLUDE_DIRS.includes(n.name)))if(n.isDirectory()){const e=await N(o,u,a,c);if(e.length===0){const f=u||d,p=h.relative(f,o).replace(/\\/g,"/");i.push({name:p,isDir:!0})}else i.push(...e)}else try{const e=u||d,f=h.relative(e,o).replace(/\\/g,"/"),p=n.isSymbolicLink();let t=null;if(c){const R=f.split("/").map(E=>encodeURIComponent(E)).join("/");t=`${c}/${R}`}const r={name:f,isDir:!1,fileProxyUrl:t,isLink:p};i.push(r)}catch(e){s(a,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${o}`,{error:e.message})}}return i}async function O(d,u,a,c,i=""){const w=await m.promises.readdir(h.join(d,i),{withFileTypes:!0});let n=0;for(const o of w){const l=i?h.join(i,o.name):o.name,e=l.split(h.sep).filter(Boolean);if(e.some(r=>r.startsWith(".")))continue;const f=e[e.length-1];if(u.includes(f)||e.some(r=>a.includes(r)))continue;const p=h.join(d,l);let t;try{t=await m.promises.lstat(p)}catch(r){s(c,"WARN","Error occurred when getting file stats, skipping",{filePath:l.replace(/\\/g,"/"),error:r.message});continue}t.isSymbolicLink()||t.nlink>1||(t.isDirectory()?n+=await O(d,u,a,c,l):t.isFile()&&(n+=t.size))}return n}async function $(d,u,a){const c=Date.now(),i=`computer:${d}:${u}`,w=I.COMPUTER_WORKSPACE_DIR;if(!d)throw new g("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!u)throw new g("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const n=String(d),o=String(u),l=h.join(w,n,o);if(!m.existsSync(l))return s(i,"INFO","Directory does not exist, returning empty list",{targetDir:l,userId:n,cId:o}),{files:[]};s(i,"DEBUG","Start getting user file list",{targetDir:l,userId:n,cId:o});try{const e=await N(l,l,i,a);return s(i,"INFO","User file list obtained successfully",{fileCount:e.length,targetDir:l,userId:n,cId:o,elapsedMs:Date.now()-c}),{files:e}}catch(e){throw s(i,"ERROR","Failed to get user file list",{targetDir:l,userId:n,cId:o,error:e.message,elapsedMs:Date.now()-c}),new P(`Failed to get file list: ${e.message}`,{targetDir:l,originalError:e.message})}}async function A(d,u,a){const c=Date.now(),i=`computer:${d}:${u}`,w=I.COMPUTER_WORKSPACE_DIR;if(!d)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!Array.isArray(a))throw new g("files must be an array",{field:"files"});const n=String(d),o=String(u),l=h.join(w,n,o);m.existsSync(l)||m.mkdirSync(l,{recursive:!0});for(let e=0;e<a.length;e++){const f=a[e];if(!f||typeof f.operation!="string")throw new g(`files[${e}].operation cannot be empty`,{field:`files[${e}].operation`});if(!f.name||typeof f.name!="string")throw new g(`files[${e}].name cannot be empty`,{field:`files[${e}].name`});const p=f.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(p))throw new g(`files[${e}].operation must be one of create, delete, rename or modify`,{field:`files[${e}].operation`});if(p==="rename"&&!f.renameFrom)throw new g(`files[${e}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${e}].renameFrom`});if(p==="modify"&&f.isDir!==!0&&typeof f.contents!="string")throw new g(`files[${e}].contents must be a string (modify operation requires)`,{field:`files[${e}].contents`})}s(i,"DEBUG","Start updating user files",{userId:n,cId:o,filesCount:a.length});try{for(const e of a){const f=e.operation.toLowerCase(),p=e.name,t=h.normalize(p).replace(/^[\/\\]+/,""),r=h.join(l,t),R=h.resolve(r),E=h.resolve(l);if(!R.startsWith(E+h.sep)&&R!==E){s(i,"WARN","File path is not secure, skipping",{filePath:t,resolvedPath:R});continue}switch(f){case"create":{if(e.isDir===!0){if(m.existsSync(r)){if((await m.promises.stat(r)).isFile())throw new g("Cannot create directory, file with the same name already exists",{filePath:t});s(i,"INFO","Directory already exists, skipping creation",{filePath:t});break}await m.promises.mkdir(r,{recursive:!0}),s(i,"INFO","Directory created successfully",{filePath:t});break}if(m.existsSync(r)){if((await m.promises.stat(r)).isDirectory())throw new g("Cannot create file, directory with the same name already exists",{filePath:t});s(i,"INFO","File already exists, skipping creation",{filePath:t});break}await m.promises.mkdir(h.dirname(r),{recursive:!0});const S=e.contents||"";await m.promises.writeFile(r,S,"utf8"),s(i,"INFO","File created successfully",{filePath:t});break}case"delete":{m.existsSync(r)?(await m.promises.stat(r)).isDirectory()?(await m.promises.rm(r,{recursive:!0,force:!0}),s(i,"INFO","Directory deleted successfully",{filePath:t})):(await m.promises.unlink(r),s(i,"INFO","File deleted successfully",{filePath:t})):s(i,"WARN","The file or directory to be deleted does not exist",{filePath:t});break}case"rename":{const S=e.renameFrom;if(!S||typeof S!="string"){s(i,"WARN","Rename operation missing renameFrom",{filePath:t});break}const y=h.normalize(S).replace(/^[\/\\]+/,""),D=h.join(l,y),F=h.resolve(D);if(!F.startsWith(E+h.sep)&&F!==E){s(i,"WARN","Source path is not secure, skipping rename",{sourcePath:y,targetPath:t});break}if(m.existsSync(D)){const C=(await m.promises.stat(D)).isDirectory();await m.promises.mkdir(h.dirname(r),{recursive:!0}),await m.promises.rename(D,r),s(i,"INFO",C?"Directory renamed successfully":"File renamed successfully",{sourcePath:y,targetPath:t})}else s(i,"WARN","The file or directory to be renamed does not exist",{sourcePath:y});break}case"modify":{if(!m.existsSync(r)){s(i,"WARN","The file to be modified does not exist",{filePath:t});break}if((await m.promises.stat(r)).isDirectory()){s(i,"INFO","The target is a directory, skipping modification",{filePath:t});break}const y=typeof e.contents=="string"?e.contents:"";if(await m.promises.readFile(r,"utf8")===y){s(i,"INFO","File content has no changes, skipping write",{filePath:t});break}await m.promises.writeFile(r,y,"utf8"),s(i,"INFO","File modified successfully",{filePath:t});break}default:{s(i,"WARN","Unsupported operation type",{operation:f,filePath:t});break}}}return s(i,"INFO","User files updated successfully",{userId:n,cId:o,filesCount:a.length,elapsedMs:Date.now()-c}),{success:!0,message:"User files updated successfully",userId:n,cId:o,filesCount:a.length}}catch(e){throw s(i,"ERROR","User files updated failed",{userId:n,cId:o,error:e.message,elapsedMs:Date.now()-c}),new P(`User files updated failed: ${e.message}`,{userId:n,cId:o,originalError:e.message})}}async function k(d,u,a,c){const i=Date.now(),w=`computer:${d}:${u}`,n=I.COMPUTER_WORKSPACE_DIR;if(!d)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!a)throw new g("file cannot be empty",{field:"file"});if(!c||typeof c!="string")throw new g("filePath cannot be empty",{field:"filePath"});const o=String(d),l=String(u),e=h.join(n,o,l);m.existsSync(e)||m.mkdirSync(e,{recursive:!0});const f=h.normalize(c).replace(/^[\/\\]+/,""),p=h.join(e,f),t=h.resolve(p),r=h.resolve(e);if(!t.startsWith(r+h.sep)&&t!==r)throw new g("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:c,resolvedPath:t});try{if(await m.promises.mkdir(h.dirname(p),{recursive:!0}),a.buffer)await m.promises.writeFile(p,a.buffer);else if(typeof a.contents=="string")await m.promises.writeFile(p,a.contents,"utf8");else throw new g("File content format is incorrect",{field:"file",hasBuffer:!!a.buffer,hasContents:typeof a.contents});return s(w,"INFO","File uploaded successfully",{userId:o,cId:l,filePath:f,targetPath:t,fileSize:a.buffer?a.buffer.length:a.contents?a.contents.length:0,elapsedMs:Date.now()-i}),{success:!0,message:"File uploaded successfully",fileSize:a.buffer?a.buffer.length:a.contents?a.contents.length:0}}catch(R){throw s(w,"ERROR","File upload failed",{userId:o,cId:l,filePath:f,error:R.message,elapsedMs:Date.now()-i}),new P(`File upload failed: ${R.message}`,{userId:o,cId:l,filePath:f,originalError:R.message})}}async function T(d,u,a,c){const i=Date.now(),w=`computer:${d}:${u}`;if(!d)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!Array.isArray(a))throw new g("files must be an array",{field:"files"});if(!Array.isArray(c))throw new g("filePaths must be an array",{field:"filePaths"});if(a.length!==c.length)throw new g(`File count (${a.length}) does not match path count (${c.length})`,{field:"filePaths"});s(w,"DEBUG","Start batch uploading files",{userId:d,cId:u,filesCount:a.length});const n=[];try{for(let e=0;e<a.length;e++){const f=a[e],p=c[e];if(!f){s(w,"WARN","Empty file object encountered in batch upload, skipping",{index:e,filePath:p}),n.push({success:!1,filePath:p,error:"Empty file object"});continue}if(!p||typeof p!="string"){s(w,"WARN","Invalid file path in batch upload, skipping",{index:e,originalname:f.originalname}),n.push({success:!1,filePath:p||"",originalname:f.originalname,error:"Invalid file path"});continue}try{const t=await k(d,u,f,p);n.push({success:!0,filePath:p,originalname:f.originalname,...t})}catch(t){s(w,"ERROR","Single file upload failed in batch upload",{filePath:p,originalname:f.originalname,error:t.message}),n.push({success:!1,filePath:p,originalname:f.originalname,error:t.message})}}const o=n.filter(e=>e.success).length,l=n.filter(e=>!e.success).length;return s(w,"INFO","Batch upload files completed",{userId:d,cId:u,totalCount:a.length,successCount:o,failCount:l,elapsedMs:Date.now()-i}),{success:!0,message:"Batch upload completed",totalCount:a.length,successCount:o,failCount:l,results:n}}catch(o){throw s(w,"ERROR","Batch upload files failed",{userId:d,cId:u,error:o.message,elapsedMs:Date.now()-i}),new P(`Batch upload files failed: ${o.message}`,{userId:d,cId:u,originalError:o.message})}}async function x(d,u){const a=Date.now(),c=`computer:${d}:${u}`,i=I.COMPUTER_WORKSPACE_DIR;if(!d)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});if(!i)throw new P("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const w=String(d),n=String(u),o=h.join(i,w,n);if(!m.existsSync(o)){const r=`${w}_${n}.zip`;s(c,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:o,userId:w,cId:n,zipFileName:r});const R=z("zip",{zlib:{level:9}});return R.append(null,{name:`${w}_${n}/`,type:"directory"}),R.on("warning",E=>{if(E.code==="ENOENT")s(c,"WARN","Encountered file problem when creating empty zip",{message:E.message,code:E.code});else throw s(c,"ERROR","Encountered warning when creating empty zip",{message:E.message,code:E.code}),E}),R.on("error",E=>{s(c,"ERROR","Failed to create empty zip",{message:E.message})}),{archive:R,zipFileName:r}}const l=`${w}_${n}.zip`;s(c,"DEBUG","Start creating workspace directory zip",{targetDir:o,zipFileName:l});const e=z("zip",{zlib:{level:9}}),f=I.CONTENT_TRAVERSE_EXCLUDE_FILES||[],p=I.TRAVERSE_EXCLUDE_DIRS||[],t=await O(o,f,p,c);if(t>b){const r=b/1024/1024,R=(t/1024/1024).toFixed(2);throw s(c,"WARN","Download rejected due to oversized workspace",{targetDir:o,downloadableSize:t,maxSizeBytes:b}),new g(`Download failed: total file size ${R}MB exceeds limit ${r}MB`,{field:"downloadSize",downloadableSize:t,maxSizeBytes:b})}return e.directory(o,`${w}_${n}`,r=>{const R=r.name||"",E=R.split(/[\/\\]/).filter(Boolean);if(E.some(y=>y.startsWith(".")))return!1;const S=E[E.length-1];if(f.includes(S)||E.some(y=>p.includes(y)))return!1;try{const y=h.join(o,R),D=m.lstatSync(y);if(D.isSymbolicLink()||D.nlink>1)return!1}catch(y){return s(c,"WARN","Error occurred when detecting link file, skipping",{filePath:R,error:y.message}),!1}return r}),e.on("warning",r=>{if(r.code==="ENOENT")s(c,"WARN","Encountered file problem when creating zip",{message:r.message,code:r.code});else throw s(c,"ERROR","Encountered warning when creating zip",{message:r.message,code:r.code}),r}),e.on("error",r=>{s(c,"ERROR","Failed to create zip",{message:r.message,elapsedMs:Date.now()-a})}),e.on("end",()=>{s(c,"INFO","Workspace directory zip created successfully",{targetDir:o,zipFileName:l,elapsedMs:Date.now()-a})}),{archive:e,zipFileName:l}}async function W(d,u,a=200){const c=Date.now(),i=`computer:${d}:${u}`;if(!d)throw new g("userId cannot be empty",{field:"userId"});if(!u)throw new g("cId cannot be empty",{field:"cId"});const w=String(d),n=String(u),o=I.COMPUTER_LOG_DIR;if(!o)return s(i,"WARN","COMPUTER_LOG_DIR is not configured"),{fileName:null,fileSize:0,lines:[]};const l=h.join(o,w,n);if(!m.existsSync(l))return s(i,"DEBUG","Log directory does not exist",{logDir:l}),{fileName:null,fileSize:0,lines:[]};const f=(await m.promises.readdir(l)).filter(y=>y.endsWith(".log"));if(f.length===0)return s(i,"DEBUG","No log file found",{logDir:l}),{fileName:null,fileSize:0,lines:[]};const p=[];for(const y of f){const D=h.join(l,y),F=await m.promises.stat(D);p.push({name:y,fullPath:D,mtime:F.mtimeMs,size:F.size})}p.sort((y,D)=>D.mtime-y.mtime);const t=p[0],R=(await m.promises.readFile(t.fullPath,"utf8")).split(`
2
+ `).filter(y=>y.length>0),E=Math.max(1,a),S=R.slice(-E);return s(i,"DEBUG","Get latest logs",{fileName:t.name,fileSize:t.size,totalLines:R.length,returnedLines:S.length,elapsedMs:Date.now()-c}),{fileName:t.name,fileSize:t.size,lines:S}}export{$ as getFileList,A as updateFiles,k as uploadFile,T as uploadFiles,x as downloadAllFiles,W as getLatestLogs};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuwax-file-server",
3
3
  "displayName": "nuwax-file-server",
4
- "version": "1.3.0-beta.12",
4
+ "version": "1.3.0-beta.13",
5
5
  "description": "Cross-platform file service deployment tool with start/stop/restart CLI commands",
6
6
  "type": "module",
7
7
  "main": "index.js",