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

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.
@@ -1 +1 @@
1
- import E from"path";import n from"fs";import o from"os";import{fileURLToPath as T}from"url";import I from"dotenv";const L=E.dirname(T(import.meta.url));I.config();function O(){const e=process.env.LOG_BASE_DIR,_=E.join(o.tmpdir(),"nuwax-file-server","project_logs");if(!e)return _;try{return n.mkdirSync(e,{recursive:!0}),e}catch{try{n.mkdirSync(_,{recursive:!0})}catch{}return _}}const r=process.env.NODE_ENV||"development";function p(e){const _=E.join(L,"..",`env.${e}`);if(n.existsSync(_))I.config({path:_}),console.log(`Environment configuration file env.${e} loaded`);else{const s=`Environment configuration file env.${e} does not exist, please create the corresponding environment configuration file and try again`;throw console.error(s),new Error(s)}}p(r);const R={NODE_ENV:r,PORT:parseInt(process.env.PORT),DEPLOYMENT_MODE:process.env.DEPLOYMENT_MODE||"docker-compose",INIT_PROJECT_NAME_REACT:process.env.INIT_PROJECT_NAME_REACT||"react-vite-template",INIT_PROJECT_NAME_VUE3:process.env.INIT_PROJECT_NAME_VUE3||"vue3-vite-template",INIT_PROJECT_DIR:process.env.INIT_PROJECT_DIR,PROJECT_SOURCE_DIR:process.env.PROJECT_SOURCE_DIR,DIST_TARGET_DIR:process.env.DIST_TARGET_DIR,UPLOAD_PROJECT_DIR:process.env.UPLOAD_PROJECT_DIR,MAX_BUILD_CONCURRENCY:process.env.MAX_BUILD_CONCURRENCY?parseInt(process.env.MAX_BUILD_CONCURRENCY,10):void 0,MAX_INLINE_FILE_SIZE_BYTES:process.env.MAX_INLINE_FILE_SIZE_BYTES?parseInt(process.env.MAX_INLINE_FILE_SIZE_BYTES,10):void 0,UPLOAD_MAX_FILE_SIZE_BYTES:process.env.UPLOAD_MAX_FILE_SIZE_BYTES?parseInt(process.env.UPLOAD_MAX_FILE_SIZE_BYTES,10):void 0,UPLOAD_ALLOWED_EXTENSIONS:process.env.UPLOAD_ALLOWED_EXTENSIONS?process.env.UPLOAD_ALLOWED_EXTENSIONS.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean):[],UPLOAD_SINGLE_FILE_SIZE_BYTES:process.env.UPLOAD_SINGLE_FILE_SIZE_BYTES?parseInt(process.env.UPLOAD_SINGLE_FILE_SIZE_BYTES,10):void 0,DOWNLOAD_MAX_FILE_SIZE_BYTES:process.env.DOWNLOAD_MAX_FILE_SIZE_BYTES?parseInt(process.env.DOWNLOAD_MAX_FILE_SIZE_BYTES,10):void 0,REQUEST_BODY_LIMIT:process.env.REQUEST_BODY_LIMIT,TRAVERSE_EXCLUDE_DIRS:process.env.TRAVERSE_EXCLUDE_DIRS?process.env.TRAVERSE_EXCLUDE_DIRS.split(",").map(e=>e.trim()).filter(Boolean):[],BACKUP_TRAVERSE_EXCLUDE_FILES:process.env.BACKUP_TRAVERSE_EXCLUDE_FILES?process.env.BACKUP_TRAVERSE_EXCLUDE_FILES.split(",").map(e=>e.trim()).filter(Boolean):[],CONTENT_TRAVERSE_EXCLUDE_FILES:process.env.CONTENT_TRAVERSE_EXCLUDE_FILES?process.env.CONTENT_TRAVERSE_EXCLUDE_FILES.split(",").map(e=>e.trim()).filter(Boolean):[],INLINE_IMAGE_EXTENSIONS:process.env.INLINE_IMAGE_EXTENSIONS?process.env.INLINE_IMAGE_EXTENSIONS.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean):[],TOP_LEVEL_NOISE_PATTERNS:process.env.TOP_LEVEL_NOISE_PATTERNS?process.env.TOP_LEVEL_NOISE_PATTERNS.split(",").map(e=>e.trim()).filter(Boolean):[],LOG_BASE_DIR:O(),LOG_LEVEL:process.env.LOG_LEVEL?process.env.LOG_LEVEL.toLowerCase():void 0,LOG_PREFIX_API:process.env.LOG_PREFIX_API,LOG_PREFIX_BUILD:process.env.LOG_PREFIX_BUILD,LOG_CONSOLE_ENABLED:typeof process.env.LOG_CONSOLE_ENABLED=="string"?process.env.LOG_CONSOLE_ENABLED.toLowerCase()==="true":void 0,LOG_CACHE_ENABLED:typeof process.env.LOG_CACHE_ENABLED=="string"?process.env.LOG_CACHE_ENABLED.toLowerCase()==="true":void 0,LOG_CACHE_DURATION:process.env.LOG_CACHE_DURATION?parseInt(process.env.LOG_CACHE_DURATION,10):void 0,LOG_CACHE_MAX_ENTRIES:process.env.LOG_CACHE_MAX_ENTRIES?parseInt(process.env.LOG_CACHE_MAX_ENTRIES,10):void 0,LOG_CACHE_MAX_FILE_SIZE:process.env.LOG_CACHE_MAX_FILE_SIZE?parseInt(process.env.LOG_CACHE_MAX_FILE_SIZE,10):void 0,DEV_SERVER_PORT_TIMEOUT:process.env.DEV_SERVER_PORT_TIMEOUT?parseInt(process.env.DEV_SERVER_PORT_TIMEOUT,10):void 0,DEV_SERVER_STOP_TIMEOUT:process.env.DEV_SERVER_STOP_TIMEOUT?parseInt(process.env.DEV_SERVER_STOP_TIMEOUT,10):void 0,DEV_SERVER_STOP_CHECK_INTERVAL:process.env.DEV_SERVER_STOP_CHECK_INTERVAL?parseInt(process.env.DEV_SERVER_STOP_CHECK_INTERVAL,10):void 0,DEV_SERVER_STOP_MAX_ATTEMPTS:process.env.DEV_SERVER_STOP_MAX_ATTEMPTS?parseInt(process.env.DEV_SERVER_STOP_MAX_ATTEMPTS,10):void 0,COMPUTER_WORKSPACE_DIR:process.env.COMPUTER_WORKSPACE_DIR,COMPUTER_LOG_DIR:process.env.COMPUTER_LOG_DIR,CLI_SERVICE_NAME:"nuwax-file-server",CLI_PID_DIR:process.env.CLI_PID_DIR||(process.platform==="win32"?E.join(process.env.TEMP||"","nuwax-file-server"):E.join("/tmp","nuwax-file-server")),CLI_PID_FILE:"server.pid",CLI_STOP_TIMEOUT:process.env.CLI_STOP_TIMEOUT?parseInt(process.env.CLI_STOP_TIMEOUT,10):3e4,CLI_CHECK_INTERVAL:process.env.CLI_CHECK_INTERVAL?parseInt(process.env.CLI_CHECK_INTERVAL,10):500,CLI_LOG_DIR:process.env.CLI_LOG_DIR||(process.platform==="win32"?E.join(process.env.TEMP||"","nuwax-file-server","logs"):E.join("/tmp","nuwax-file-server","logs")),CLI_IS_WINDOWS:process.platform==="win32",GIT_DEFAULT_AUTHOR_NAME:process.env.GIT_DEFAULT_AUTHOR_NAME||"Nuwax File Server",GIT_DEFAULT_AUTHOR_EMAIL:process.env.GIT_DEFAULT_AUTHOR_EMAIL||"git@nuwax.local",GIT_AUTO_GITIGNORE:process.env.GIT_AUTO_GITIGNORE?.toLowerCase()!=="false",GIT_GITIGNORE_ENTRIES:process.env.GIT_GITIGNORE_ENTRIES?process.env.GIT_GITIGNORE_ENTRIES.split("|").map(e=>e.trim()).filter(Boolean):["node_modules/",".pnpm-store/","dist/","build/",".idea/",".vscode/",".DS_Store",".agents/",".claude/",".opencode/",".codex/"],GIT_ENABLED:process.env.GIT_ENABLED?.toLowerCase()==="true"};export default R;
1
+ import E from"path";import n from"fs";import o from"os";import{fileURLToPath as T}from"url";import I from"dotenv";const L=E.dirname(T(import.meta.url));I.config();function O(){const e=process.env.LOG_BASE_DIR,_=E.join(o.tmpdir(),"nuwax-file-server","project_logs");if(!e)return _;try{return n.mkdirSync(e,{recursive:!0}),e}catch{try{n.mkdirSync(_,{recursive:!0})}catch{}return _}}const r=process.env.NODE_ENV||"development";function p(e){const _=E.join(L,"..",`env.${e}`);if(n.existsSync(_))I.config({path:_}),console.log(`Environment configuration file env.${e} loaded`);else{const s=`Environment configuration file env.${e} does not exist, please create the corresponding environment configuration file and try again`;throw console.error(s),new Error(s)}}p(r);const R={NODE_ENV:r,PORT:parseInt(process.env.PORT),DEPLOYMENT_MODE:process.env.DEPLOYMENT_MODE||"docker-compose",INIT_PROJECT_NAME_REACT:process.env.INIT_PROJECT_NAME_REACT||"react-vite-template",INIT_PROJECT_NAME_VUE3:process.env.INIT_PROJECT_NAME_VUE3||"vue3-vite-template",INIT_PROJECT_DIR:process.env.INIT_PROJECT_DIR,PROJECT_SOURCE_DIR:process.env.PROJECT_SOURCE_DIR,DIST_TARGET_DIR:process.env.DIST_TARGET_DIR,UPLOAD_PROJECT_DIR:process.env.UPLOAD_PROJECT_DIR,MAX_BUILD_CONCURRENCY:process.env.MAX_BUILD_CONCURRENCY?parseInt(process.env.MAX_BUILD_CONCURRENCY,10):void 0,MAX_INLINE_FILE_SIZE_BYTES:process.env.MAX_INLINE_FILE_SIZE_BYTES?parseInt(process.env.MAX_INLINE_FILE_SIZE_BYTES,10):void 0,UPLOAD_MAX_FILE_SIZE_BYTES:process.env.UPLOAD_MAX_FILE_SIZE_BYTES?parseInt(process.env.UPLOAD_MAX_FILE_SIZE_BYTES,10):void 0,UPLOAD_ALLOWED_EXTENSIONS:process.env.UPLOAD_ALLOWED_EXTENSIONS?process.env.UPLOAD_ALLOWED_EXTENSIONS.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean):[],UPLOAD_SINGLE_FILE_SIZE_BYTES:process.env.UPLOAD_SINGLE_FILE_SIZE_BYTES?parseInt(process.env.UPLOAD_SINGLE_FILE_SIZE_BYTES,10):void 0,DOWNLOAD_MAX_FILE_SIZE_BYTES:process.env.DOWNLOAD_MAX_FILE_SIZE_BYTES?parseInt(process.env.DOWNLOAD_MAX_FILE_SIZE_BYTES,10):void 0,REQUEST_BODY_LIMIT:process.env.REQUEST_BODY_LIMIT,TRAVERSE_EXCLUDE_DIRS:process.env.TRAVERSE_EXCLUDE_DIRS?process.env.TRAVERSE_EXCLUDE_DIRS.split(",").map(e=>e.trim()).filter(Boolean):[],BACKUP_TRAVERSE_EXCLUDE_FILES:process.env.BACKUP_TRAVERSE_EXCLUDE_FILES?process.env.BACKUP_TRAVERSE_EXCLUDE_FILES.split(",").map(e=>e.trim()).filter(Boolean):[],CONTENT_TRAVERSE_EXCLUDE_FILES:process.env.CONTENT_TRAVERSE_EXCLUDE_FILES?process.env.CONTENT_TRAVERSE_EXCLUDE_FILES.split(",").map(e=>e.trim()).filter(Boolean):[],INLINE_IMAGE_EXTENSIONS:process.env.INLINE_IMAGE_EXTENSIONS?process.env.INLINE_IMAGE_EXTENSIONS.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean):[],TOP_LEVEL_NOISE_PATTERNS:process.env.TOP_LEVEL_NOISE_PATTERNS?process.env.TOP_LEVEL_NOISE_PATTERNS.split(",").map(e=>e.trim()).filter(Boolean):[],LOG_BASE_DIR:O(),LOG_LEVEL:process.env.LOG_LEVEL?process.env.LOG_LEVEL.toLowerCase():void 0,LOG_PREFIX_API:process.env.LOG_PREFIX_API,LOG_PREFIX_BUILD:process.env.LOG_PREFIX_BUILD,LOG_CONSOLE_ENABLED:typeof process.env.LOG_CONSOLE_ENABLED=="string"?process.env.LOG_CONSOLE_ENABLED.toLowerCase()==="true":void 0,LOG_CACHE_ENABLED:typeof process.env.LOG_CACHE_ENABLED=="string"?process.env.LOG_CACHE_ENABLED.toLowerCase()==="true":void 0,LOG_CACHE_DURATION:process.env.LOG_CACHE_DURATION?parseInt(process.env.LOG_CACHE_DURATION,10):void 0,LOG_CACHE_MAX_ENTRIES:process.env.LOG_CACHE_MAX_ENTRIES?parseInt(process.env.LOG_CACHE_MAX_ENTRIES,10):void 0,LOG_CACHE_MAX_FILE_SIZE:process.env.LOG_CACHE_MAX_FILE_SIZE?parseInt(process.env.LOG_CACHE_MAX_FILE_SIZE,10):void 0,DEV_SERVER_PORT_TIMEOUT:process.env.DEV_SERVER_PORT_TIMEOUT?parseInt(process.env.DEV_SERVER_PORT_TIMEOUT,10):void 0,DEV_SERVER_STOP_TIMEOUT:process.env.DEV_SERVER_STOP_TIMEOUT?parseInt(process.env.DEV_SERVER_STOP_TIMEOUT,10):void 0,DEV_SERVER_STOP_CHECK_INTERVAL:process.env.DEV_SERVER_STOP_CHECK_INTERVAL?parseInt(process.env.DEV_SERVER_STOP_CHECK_INTERVAL,10):void 0,DEV_SERVER_STOP_MAX_ATTEMPTS:process.env.DEV_SERVER_STOP_MAX_ATTEMPTS?parseInt(process.env.DEV_SERVER_STOP_MAX_ATTEMPTS,10):void 0,COMPUTER_WORKSPACE_DIR:process.env.COMPUTER_WORKSPACE_DIR,COMPUTER_LOG_DIR:process.env.COMPUTER_LOG_DIR,CLI_SERVICE_NAME:"nuwax-file-server",CLI_PID_DIR:process.env.CLI_PID_DIR||(process.platform==="win32"?E.join(process.env.TEMP||"","nuwax-file-server"):E.join("/tmp","nuwax-file-server")),CLI_PID_FILE:"server.pid",CLI_STOP_TIMEOUT:process.env.CLI_STOP_TIMEOUT?parseInt(process.env.CLI_STOP_TIMEOUT,10):3e4,CLI_CHECK_INTERVAL:process.env.CLI_CHECK_INTERVAL?parseInt(process.env.CLI_CHECK_INTERVAL,10):500,CLI_LOG_DIR:process.env.CLI_LOG_DIR||(process.platform==="win32"?E.join(process.env.TEMP||"","nuwax-file-server","logs"):E.join("/tmp","nuwax-file-server","logs")),CLI_IS_WINDOWS:process.platform==="win32",GIT_DEFAULT_AUTHOR_NAME:process.env.GIT_DEFAULT_AUTHOR_NAME||"Nuwax File Server",GIT_DEFAULT_AUTHOR_EMAIL:process.env.GIT_DEFAULT_AUTHOR_EMAIL||"git@nuwax.local",GIT_AUTO_GITIGNORE:process.env.GIT_AUTO_GITIGNORE?.toLowerCase()!=="false",GIT_GITIGNORE_ENTRIES:process.env.GIT_GITIGNORE_ENTRIES?process.env.GIT_GITIGNORE_ENTRIES.split("|").map(e=>e.trim()).filter(Boolean):["node_modules/",".pnpm-store/","dist/","build/",".idea/",".vscode/",".DS_Store",".agents/",".claude/",".opencode/",".codex/"],GIT_ENABLED:process.env.GIT_ENABLED?.toLowerCase()==="true",GIT_PATH:process.env.GIT_PATH||"",BASH_PATH:process.env.BASH_PATH||"",ZIP_WORKSPACE_EXCLUDE_DIRS:process.env.ZIP_WORKSPACE_EXCLUDE_DIRS?process.env.ZIP_WORKSPACE_EXCLUDE_DIRS.split(",").map(e=>e.trim()).filter(Boolean):[".git",".tmp",".claude",".agents",".codex",".opencode",".logs","__pycache__","node_modules","dist"]};export default R;
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.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();
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.15",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();
@@ -48,7 +48,7 @@ DOWNLOAD_MAX_FILE_SIZE_BYTES=104857600
48
48
  REQUEST_BODY_LIMIT=2000mb
49
49
 
50
50
  # 目录遍历排除(返回内容、归档等)
51
- TRAVERSE_EXCLUDE_DIRS=dist,node_modules,.pnpm-store,__MACOSX,.attachments,.git
51
+ TRAVERSE_EXCLUDE_DIRS=dist,node_modules,.pnpm-store,__MACOSX,.attachments,.git,.agents,.codex,.opencode,.logs
52
52
 
53
53
  # 归档遍历排除文件
54
54
  BACKUP_TRAVERSE_EXCLUDE_FILES=pnpm-lock.yaml,yarn.lock,package-lock.json
@@ -95,3 +95,10 @@ GIT_DEFAULT_AUTHOR_EMAIL=git@nuwax.com
95
95
  GIT_AUTO_GITIGNORE=true
96
96
  GIT_GITIGNORE_ENTRIES=node_modules/|.pnpm-store/|dist/|build/|.idea/|.vscode/|.DS_Store|.agents/|.claude/|.opencode/|.codex/
97
97
  GIT_ENABLED=true
98
+
99
+ # Windows 专用路径(Linux/macOS 留空)
100
+ GIT_PATH=
101
+ BASH_PATH=
102
+
103
+ # zip-workspace 打包时排除的目录(逗号分隔)
104
+ ZIP_WORKSPACE_EXCLUDE_DIRS=.git,.tmp,.claude,.agents,.codex,.opencode,.logs,__pycache__,node_modules,dist
@@ -48,7 +48,7 @@ DOWNLOAD_MAX_FILE_SIZE_BYTES=104857600
48
48
  REQUEST_BODY_LIMIT=2000mb
49
49
 
50
50
  # 目录遍历排除(返回内容、归档等)
51
- TRAVERSE_EXCLUDE_DIRS=dist,node_modules,.pnpm-store,__MACOSX,.attachments,.git
51
+ TRAVERSE_EXCLUDE_DIRS=dist,node_modules,.pnpm-store,__MACOSX,.attachments,.git,.agents,.codex,.opencode,.logs
52
52
 
53
53
  # 归档遍历排除文件
54
54
  BACKUP_TRAVERSE_EXCLUDE_FILES=pnpm-lock.yaml,yarn.lock,package-lock.json
@@ -95,3 +95,10 @@ GIT_DEFAULT_AUTHOR_EMAIL=git@nuwax.com
95
95
  GIT_AUTO_GITIGNORE=true
96
96
  GIT_GITIGNORE_ENTRIES=node_modules/|.pnpm-store/|dist/|build/|.idea/|.vscode/|.DS_Store|.agents/|.claude/|.opencode/|.codex/
97
97
  GIT_ENABLED=true
98
+
99
+ # Windows 专用路径(Linux/macOS 留空)
100
+ GIT_PATH=
101
+ BASH_PATH=
102
+
103
+ # zip-workspace 打包时排除的目录(逗号分隔)
104
+ ZIP_WORKSPACE_EXCLUDE_DIRS=.git,.tmp,.claude,.agents,.codex,.opencode,.logs,__pycache__,node_modules,dist
@@ -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 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
+ import z from"express";import k from"multer";import m from"fs";import I from"path";import{ValidationError as C,asyncHandler as c}from"../utils/error/errorHandler.js";import{log as d}from"../utils/log/logUtils.js";import $ from"../appConfig/index.js";import{createWorkspace as F,pushSkillsToWorkspace as N,initProjectTemplate as b,executeCommand as A,deleteWorkspace as j,zipWorkspace as O,buildAgentPackage as E,cleanupBuildArtifacts as U}from"../utils/computer/computerUtils.js";import{getFileList as P,updateFiles as D,uploadFile as R,uploadFiles as x,downloadAllFiles as v,getLatestLogs as H}from"../utils/computer/computerFileUtils.js";const g=z.Router(),y=k({storage:k.diskStorage({destination:(t,n,s)=>{try{const e=$.COMPUTER_WORKSPACE_DIR;if(!e)return s(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const a=t.body?.userId||"unknown",o=t.body?.cId||"unknown",i=I.join(e,String(a),String(o),".tmp");m.existsSync(i)||m.mkdirSync(i,{recursive:!0}),s(null,i)}catch(e){s(e)}},filename:(t,n,s)=>{const e=I.extname(n.originalname)||".zip",a=I.basename(n.originalname,e),o=`${Date.now()}_${Math.round(Math.random()*1e6)}`;s(null,`${a}_${o}${e}`)}}),limits:{fileSize:$.UPLOAD_MAX_FILE_SIZE_BYTES}});function T(t,n,s,e){if(t&&t.name==="MulterError"||t&&(t.name==="ValidationError"||t instanceof C))return e(t);e(t)}const _=[{path:"/create-workspace",method:"post",middleware:y.single("file"),handler:c(async(t,n)=>{const{userId:s,cId:e}=t.body||{},a=t.file||null,o=`computer:${s}:${e}`;d(o,"INFO","Create workspace request",{userId:s,cId:e,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await F(s,e,a);n.status(200).json({success:!0,...i})})},{path:"/create-workspace-v2",method:"post",middleware:y.single("file"),handler:c(async(t,n)=>{const{userId:s,cId:e,skillUrls:a,mcpServersConfig:o,hooksConfig:i,permissionsConfig:r,hookScripts:l}=t.body||{},p=t.file||null,f=`computer:${s}:${e}`;let u=a;if(typeof a=="string")try{const w=JSON.parse(a);u=Array.isArray(w)?w:[a]}catch{u=[a]}let h=l;if(typeof l=="string")try{h=JSON.parse(l)}catch{h=null}d(f,"INFO","Create workspace v2 request",{userId:s,cId:e,hasFile:!!p,fileName:p?.originalname,fileSize:p?.size,skillUrlsCount:Array.isArray(u)?u.length:0,hasMcpServersConfig:!!o,hasHooksConfig:!!i,hasPermissionsConfig:!!r,hookScriptsCount:Array.isArray(h)?h.length:0});const S=await F(s,e,p,u,o,r,i,h);n.status(200).json({success:!0,...S})})},{path:"/push-skills-to-workspace",method:"post",middleware:y.single("file"),handler:c(async(t,n)=>{const{userId:s,cId:e}=t.body||{},a=t.file||null,o=`computer:${s}:${e}`;d(o,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:s,cId:e,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await N(s,e,a);n.status(200).json({success:!0,...i})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:y.single("file"),handler:c(async(t,n)=>{const{userId:s,cId:e,skillUrls:a}=t.body||{},o=t.file||null,i=`computer:${s}:${e}`;let r=a;if(typeof a=="string")try{const p=JSON.parse(a);r=Array.isArray(p)?p:[a]}catch{r=[a]}d(i,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:s,cId:e,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size,skillUrlsCount:Array.isArray(r)?r.length:0});const l=await N(s,e,o,r);n.status(200).json({success:!0,...l})})},{path:"/get-file-list",method:"get",handler:c(async(t,n)=>{const{userId:s,cId:e,proxyPath:a}=t.query,o=await P(s,e,a);n.status(200).json({success:!0,...o})})},{path:"/files-update",method:"post",handler:c(async(t,n)=>{const{userId:s,cId:e,files:a}=t.body||{},o=`computer:${s}:${e}`;d(o,"INFO","Files update",{userId:s,cId:e,filesCount:a?a.length:0}),a&&Array.isArray(a)&&a.forEach(r=>{if(r&&typeof r.contents=="string"&&r.contents)try{r.contents=decodeURIComponent(r.contents)}catch(l){d(o,"WARN","Decode file content failed",{fileName:r.name,error:l.message})}});const i=await D(s,e,a);n.status(200).json(i)})},{path:"/upload-file",method:"post",middleware:y.single("file"),handler:c(async(t,n)=>{const{userId:s,cId:e,filePath:a}=t.body||{},o=t.file,i=`computer:${s}:${e}`;d(i,"INFO","Upload single file",{userId:s,cId:e,filePath:a});const l={buffer:await m.promises.readFile(o.path),originalname:o.originalname,mimetype:o.mimetype,size:o.size};try{const p=await R(s,e,l,a);n.status(200).json(p)}finally{m.existsSync(o.path)&&await m.promises.unlink(o.path)}})},{path:"/upload-files",method:"post",middleware:y.array("files"),handler:c(async(t,n)=>{const{userId:s,cId:e,filePaths:a}=t.body||{},o=t.files||[],i=`computer:${s}:${e}`,r=Array.isArray(a)?a:typeof a=="string"?[a]:a;d(i,"INFO","Batch upload files request",{userId:s,cId:e,filesCount:o.length,filePathsCount:Array.isArray(r)?r.length:0});const l=[],p=[];try{for(const u of o){p.push(u.path);const h=await m.promises.readFile(u.path);l.push({buffer:h,originalname:u.originalname,mimetype:u.mimetype,size:u.size})}const f=await x(s,e,l,r);n.status(200).json(f)}finally{for(const f of p)if(m.existsSync(f))try{await m.promises.unlink(f)}catch(u){d(i,"WARN","Clean temporary file failed",{tempPath:f,error:u.message})}}})},{path:"/init-project-template",method:"post",middleware:y.single("file"),handler:c(async(t,n)=>{const{userId:s,cId:e,enableGit:a}=t.body||{},o=t.file||null,i=`computer:${s}:${e}`;d(i,"INFO","Init project template request",{userId:s,cId:e,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size,enableGit:a});const r=await b(s,e,o,a);n.status(200).json({success:!0,...r})})},{path:"/download-all-files",method:"get",handler:c(async(t,n)=>{const{userId:s,cId:e}=t.query||{},a=`computer:${s}:${e}`;d(a,"INFO","Download all files request",{userId:s,cId:e});const{archive:o,zipFileName:i}=await v(s,e);n.setHeader("Content-Type","application/zip");const r=encodeURIComponent(i);n.setHeader("Content-Disposition",`attachment; filename="${r}"; filename*=UTF-8''${r}`),o.on("error",l=>{n.destroy(l)}),o.pipe(n),o.finalize()})},{path:"/execute-command",method:"post",handler:c(async(t,n)=>{const{userId:s,cId:e,command:a}=t.body||{},o=`computer:${s}:${e}`;d(o,"INFO","Execute command request",{userId:s,cId:e,command:a});const i=await A(s,e,a);n.status(200).json({success:!0,...i})})},{path:"/delete-workspace",method:"post",handler:c(async(t,n)=>{const{userId:s,cId:e}=t.body||{},a=`computer:${s}:${e}`;d(a,"INFO","Delete workspace request",{userId:s,cId:e});const o=await j(s,e);n.status(200).json({success:!0,...o})})},{path:"/get-logs",method:"get",handler:c(async(t,n)=>{const{userId:s,cId:e,tailLines:a}=t.query,o=a?parseInt(a,10):200,i=Number.isFinite(o)&&o>0?o:200,r=await H(s,e,i);n.status(200).json({success:!0,...r})})},{path:"/zip-workspace",method:"post",handler:c(async(t,n)=>{const{userId:s,cId:e,excludeDirs:a}=t.body||{},o=`computer:${s}:${e}`;d(o,"INFO","Zip workspace request",{userId:s,cId:e,hasExcludeDirs:!!a});const{archive:i,zipFileName:r}=await O(s,e,a||null);n.setHeader("Content-Type","application/zip");const l=encodeURIComponent(r);n.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),i.on("error",p=>{n.destroy(p)}),i.pipe(n),i.finalize()})},{path:"/build-agent-package",method:"post",handler:c(async(t,n)=>{const{userId:s,cId:e,agentId:a,version:o}=t.body||{},i=`computer:${s}:${e}`;d(i,"INFO","Build agent package request",{userId:s,cId:e,agentId:a,version:o});const r=await E(s,e,a,o);n.status(200).json({success:!0,...r})})},{path:"/cleanup-build-artifacts",method:"post",handler:c(async(t,n)=>{const{userId:s,cId:e}=t.body||{},a=`computer:${s}:${e}`;d(a,"INFO","Cleanup build artifacts request",{userId:s,cId:e});const o=await U(s,e);n.status(200).json({success:!0,...o})})}];_.forEach(t=>{if(t.middleware)g[t.method](t.path,t.middleware,t.handler);else if(t.customHandler){const n=[];t.handler&&n.push(t.handler),t.decodeMiddleware&&n.push(t.decodeMiddleware),n.push(T),n.push(t.customHandler),g[t.method](t.path,...n)}else g[t.method](t.path,t.handler)});export default g;
@@ -1,2 +1,2 @@
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};
1
+ import m from"fs";import h from"path";import z from"archiver";import S from"../../appConfig/index.js";import{log as s}from"../log/logUtils.js";import{ValidationError as w,SystemError as P}from"../error/errorHandler.js";const _=100*1024*1024,b=S.DOWNLOAD_MAX_FILE_SIZE_BYTES||_;async function N(d,u,a,c){const i=[],y=await m.promises.readdir(d,{withFileTypes:!0});y.sort((n,r)=>n.isDirectory()&&!r.isDirectory()?-1:!n.isDirectory()&&r.isDirectory()?1:n.name.toLowerCase().localeCompare(r.name.toLowerCase()));for(const n of y){const r=h.join(d,n.name);if(!(n.name.startsWith(".")&&n.name!==".gitignore"||(S.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(n.name))&&!(n.isDirectory()&&S.TRAVERSE_EXCLUDE_DIRS.includes(n.name)))if(n.isDirectory()){const e=await N(r,u,a,c);if(e.length===0){const f=u||d,p=h.relative(f,r).replace(/\\/g,"/");i.push({name:p,isDir:!0})}else i.push(...e)}else try{const e=u||d,f=h.relative(e,r).replace(/\\/g,"/"),p=n.isSymbolicLink();let t=null;if(c){const R=f.split("/").map(E=>encodeURIComponent(E)).join("/");t=`${c}/${R}`}const o={name:f,isDir:!1,fileProxyUrl:t,isLink:p};i.push(o)}catch(e){s(a,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${r}`,{error:e.message})}}return i}async function O(d,u,a,c,i=""){const y=await m.promises.readdir(h.join(d,i),{withFileTypes:!0});let n=0;for(const r of y){const l=i?h.join(i,r.name):r.name,e=l.split(h.sep).filter(Boolean);if(e.some(o=>o.startsWith(".")))continue;const f=e[e.length-1];if(u.includes(f)||e.some(o=>a.includes(o)))continue;const p=h.join(d,l);let t;try{t=await m.promises.lstat(p)}catch(o){s(c,"WARN","Error occurred when getting file stats, skipping",{filePath:l.replace(/\\/g,"/"),error:o.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}`,y=S.COMPUTER_WORKSPACE_DIR;if(!d)throw new w("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!u)throw new w("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const n=String(d),r=String(u),l=h.join(y,n,r);if(!m.existsSync(l))return s(i,"INFO","Directory does not exist, returning empty list",{targetDir:l,userId:n,cId:r}),{files:[]};s(i,"DEBUG","Start getting user file list",{targetDir:l,userId:n,cId:r});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:r,elapsedMs:Date.now()-c}),{files:e}}catch(e){throw s(i,"ERROR","Failed to get user file list",{targetDir:l,userId:n,cId:r,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}`,y=S.COMPUTER_WORKSPACE_DIR;if(!d)throw new w("userId cannot be empty",{field:"userId"});if(!u)throw new w("cId cannot be empty",{field:"cId"});if(!Array.isArray(a))throw new w("files must be an array",{field:"files"});const n=String(d),r=String(u),l=h.join(y,n,r);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 w(`files[${e}].operation cannot be empty`,{field:`files[${e}].operation`});if(!f.name||typeof f.name!="string")throw new w(`files[${e}].name cannot be empty`,{field:`files[${e}].name`});const p=f.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(p))throw new w(`files[${e}].operation must be one of create, delete, rename or modify`,{field:`files[${e}].operation`});if(p==="rename"&&!f.renameFrom)throw new w(`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 w(`files[${e}].contents must be a string (modify operation requires)`,{field:`files[${e}].contents`})}s(i,"DEBUG","Start updating user files",{userId:n,cId:r,filesCount:a.length});try{for(const e of a){const f=e.operation.toLowerCase(),p=e.name,t=h.normalize(p).replace(/^[\/\\]+/,""),o=h.join(l,t),R=h.resolve(o),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(o)){if((await m.promises.stat(o)).isFile())throw new w("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(o,{recursive:!0}),s(i,"INFO","Directory created successfully",{filePath:t});break}if(m.existsSync(o)){if((await m.promises.stat(o)).isDirectory())throw new w("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(o),{recursive:!0});const F=e.contents||"";await m.promises.writeFile(o,F,"utf8"),s(i,"INFO","File created successfully",{filePath:t});break}case"delete":{m.existsSync(o)?(await m.promises.stat(o)).isDirectory()?(await m.promises.rm(o,{recursive:!0,force:!0}),s(i,"INFO","Directory deleted successfully",{filePath:t})):(await m.promises.unlink(o),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 F=e.renameFrom;if(!F||typeof F!="string"){s(i,"WARN","Rename operation missing renameFrom",{filePath:t});break}const g=h.normalize(F).replace(/^[\/\\]+/,""),D=h.join(l,g),I=h.resolve(D);if(!I.startsWith(E+h.sep)&&I!==E){s(i,"WARN","Source path is not secure, skipping rename",{sourcePath:g,targetPath:t});break}if(m.existsSync(D)){const C=(await m.promises.stat(D)).isDirectory();await m.promises.mkdir(h.dirname(o),{recursive:!0}),await m.promises.rename(D,o),s(i,"INFO",C?"Directory renamed successfully":"File renamed successfully",{sourcePath:g,targetPath:t})}else s(i,"WARN","The file or directory to be renamed does not exist",{sourcePath:g});break}case"modify":{if(!m.existsSync(o)){s(i,"WARN","The file to be modified does not exist",{filePath:t});break}if((await m.promises.stat(o)).isDirectory()){s(i,"INFO","The target is a directory, skipping modification",{filePath:t});break}const g=typeof e.contents=="string"?e.contents:"";if(await m.promises.readFile(o,"utf8")===g){s(i,"INFO","File content has no changes, skipping write",{filePath:t});break}await m.promises.writeFile(o,g,"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:r,filesCount:a.length,elapsedMs:Date.now()-c}),{success:!0,message:"User files updated successfully",userId:n,cId:r,filesCount:a.length}}catch(e){throw s(i,"ERROR","User files updated failed",{userId:n,cId:r,error:e.message,elapsedMs:Date.now()-c}),new P(`User files updated failed: ${e.message}`,{userId:n,cId:r,originalError:e.message})}}async function k(d,u,a,c){const i=Date.now(),y=`computer:${d}:${u}`,n=S.COMPUTER_WORKSPACE_DIR;if(!d)throw new w("userId cannot be empty",{field:"userId"});if(!u)throw new w("cId cannot be empty",{field:"cId"});if(!a)throw new w("file cannot be empty",{field:"file"});if(!c||typeof c!="string")throw new w("filePath cannot be empty",{field:"filePath"});const r=String(d),l=String(u),e=h.join(n,r,l);m.existsSync(e)||m.mkdirSync(e,{recursive:!0});const f=h.normalize(c).replace(/^[\/\\]+/,""),p=h.join(e,f),t=h.resolve(p),o=h.resolve(e);if(!t.startsWith(o+h.sep)&&t!==o)throw new w("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 w("File content format is incorrect",{field:"file",hasBuffer:!!a.buffer,hasContents:typeof a.contents});return s(y,"INFO","File uploaded successfully",{userId:r,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(y,"ERROR","File upload failed",{userId:r,cId:l,filePath:f,error:R.message,elapsedMs:Date.now()-i}),new P(`File upload failed: ${R.message}`,{userId:r,cId:l,filePath:f,originalError:R.message})}}async function T(d,u,a,c){const i=Date.now(),y=`computer:${d}:${u}`;if(!d)throw new w("userId cannot be empty",{field:"userId"});if(!u)throw new w("cId cannot be empty",{field:"cId"});if(!Array.isArray(a))throw new w("files must be an array",{field:"files"});if(!Array.isArray(c))throw new w("filePaths must be an array",{field:"filePaths"});if(a.length!==c.length)throw new w(`File count (${a.length}) does not match path count (${c.length})`,{field:"filePaths"});s(y,"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(y,"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(y,"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(y,"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 r=n.filter(e=>e.success).length,l=n.filter(e=>!e.success).length;return s(y,"INFO","Batch upload files completed",{userId:d,cId:u,totalCount:a.length,successCount:r,failCount:l,elapsedMs:Date.now()-i}),{success:!0,message:"Batch upload completed",totalCount:a.length,successCount:r,failCount:l,results:n}}catch(r){throw s(y,"ERROR","Batch upload files failed",{userId:d,cId:u,error:r.message,elapsedMs:Date.now()-i}),new P(`Batch upload files failed: ${r.message}`,{userId:d,cId:u,originalError:r.message})}}async function x(d,u){const a=Date.now(),c=`computer:${d}:${u}`,i=S.COMPUTER_WORKSPACE_DIR;if(!d)throw new w("userId cannot be empty",{field:"userId"});if(!u)throw new w("cId cannot be empty",{field:"cId"});if(!i)throw new P("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const y=String(d),n=String(u),r=h.join(i,y,n);if(!m.existsSync(r)){const o=`${y}_${n}.zip`;s(c,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:r,userId:y,cId:n,zipFileName:o});const R=z("zip",{zlib:{level:9}});return R.append(null,{name:`${y}_${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:o}}const l=`${y}_${n}.zip`;s(c,"DEBUG","Start creating workspace directory zip",{targetDir:r,zipFileName:l});const e=z("zip",{zlib:{level:9}}),f=S.CONTENT_TRAVERSE_EXCLUDE_FILES||[],p=S.TRAVERSE_EXCLUDE_DIRS||[],t=await O(r,f,p,c);if(t>b){const o=b/1024/1024,R=(t/1024/1024).toFixed(2);throw s(c,"WARN","Download rejected due to oversized workspace",{targetDir:r,downloadableSize:t,maxSizeBytes:b}),new w(`Download failed: total file size ${R}MB exceeds limit ${o}MB`,{field:"downloadSize",downloadableSize:t,maxSizeBytes:b})}return e.directory(r,`${y}_${n}`,o=>{const R=o.name||"",E=R.split(/[\/\\]/).filter(Boolean);if(E.some(g=>g.startsWith(".")))return!1;const F=E[E.length-1];if(f.includes(F)||E.some(g=>p.includes(g)))return!1;try{const g=h.join(r,R),D=m.lstatSync(g);if(D.isSymbolicLink()||D.nlink>1)return!1}catch(g){return s(c,"WARN","Error occurred when detecting link file, skipping",{filePath:R,error:g.message}),!1}return o}),e.on("warning",o=>{if(o.code==="ENOENT")s(c,"WARN","Encountered file problem when creating zip",{message:o.message,code:o.code});else throw s(c,"ERROR","Encountered warning when creating zip",{message:o.message,code:o.code}),o}),e.on("error",o=>{s(c,"ERROR","Failed to create zip",{message:o.message,elapsedMs:Date.now()-a})}),e.on("end",()=>{s(c,"INFO","Workspace directory zip created successfully",{targetDir:r,zipFileName:l,elapsedMs:Date.now()-a})}),{archive:e,zipFileName:l}}async function L(d,u,a=200){const c=Date.now(),i=`computer:${d}:${u}`;if(!d)throw new w("userId cannot be empty",{field:"userId"});if(!u)throw new w("cId cannot be empty",{field:"cId"});const y=String(d),n=String(u),r=S.COMPUTER_LOG_DIR;if(!r)return s(i,"WARN","COMPUTER_LOG_DIR is not configured"),{fileName:null,fileSize:0,lines:[]};const l=h.join(r,y,n,".logs");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,{withFileTypes:!0})).filter(g=>g.isFile()).map(g=>g.name);if(f.length===0)return s(i,"DEBUG","No log file found",{logDir:l}),{fileName:null,fileSize:0,lines:[]};const p=[];for(const g of f){const D=h.join(l,g),I=await m.promises.stat(D);p.push({name:g,fullPath:D,mtime:I.mtimeMs,size:I.size})}p.sort((g,D)=>D.mtime-g.mtime);const t=p[0],R=(await m.promises.readFile(t.fullPath,"utf8")).split(`
2
+ `).filter(g=>g.length>0),E=Math.max(1,a),F=R.slice(-E);return s(i,"DEBUG","Get latest logs",{fileName:t.name,fileSize:t.size,totalLines:R.length,returnedLines:F.length,elapsedMs:Date.now()-c}),{fileName:t.name,fileSize:t.size,lines:F}}export{$ as getFileList,A as updateFiles,k as uploadFile,T as uploadFiles,x as downloadAllFiles,L as getLatestLogs};
@@ -1,2 +1,5 @@
1
- import t from"fs";import a from"path";import{exec as tt}from"child_process";import X from"../../appConfig/index.js";import{extractZip as B}from"../common/zipUtils.js";import{ValidationError as h,SystemError as U,FileError as Z}from"../error/errorHandler.js";import{log as o}from"../log/logUtils.js";import{ensurePrimaryAgentDirs as Y,syncAgents as V}from"../common/AgentWorkspaceUtils.js";function Q(e){if(!e)return[];if(Array.isArray(e))return e.map(i=>typeof i=="string"?i.trim():"").filter(Boolean);if(typeof e=="string"){const i=e.trim();if(!i)return[];try{const s=JSON.parse(i);if(Array.isArray(s))return s.map(w=>typeof w=="string"?w.trim():"").filter(Boolean)}catch{}return[i]}return[]}async function I(e,i,s){let w;try{w=await fetch(e)}catch(N){throw new Z(`Failed to download skill zip from url: ${e}`,{url:e,reason:N.message})}if(!w.ok)throw new Z(`Failed to download skill zip from url: ${e}`,{url:e,status:w.status,statusText:w.statusText});const p=w.headers.get("content-type")||"";p&&!p.includes("zip")&&!p.includes("octet-stream")&&o(s,"WARN","Downloaded skill url content-type is not typical zip",{url:e,contentType:p});const n=await w.arrayBuffer(),g=Buffer.from(n);await t.promises.writeFile(i,g)}async function G(e="computer"){const i=X.COMPUTER_WORKSPACE_DIR;if(!i)throw new h("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});return t.existsSync(i)||(await t.promises.mkdir(i,{recursive:!0}),o(e,"INFO","Created user workspace root directory",{workspaceRoot:i})),i}async function H(e,i){const s=a.join(e,i);if(t.existsSync(s)&&(await t.promises.lstat(s)).isDirectory())return s;const w=await t.promises.readdir(e,{withFileTypes:!0});for(const p of w){if(!p.isDirectory())continue;const n=a.join(e,p.name),g=a.join(n,i);if(t.existsSync(g)&&(await t.promises.lstat(g)).isDirectory())return g}return null}async function kt(e){return H(e,"skills")}const et=".dynamic_add.lock";function it(e){const i=a.join(e,et);return t.existsSync(i)&&t.statSync(i).isFile()}async function W(e){t.existsSync(e)&&await t.promises.rm(e,{recursive:!0,force:!0})}async function $(e,i){try{await t.promises.rename(e,i)}catch(s){if(s.code==="EXDEV"){async function w(p,n){if((await t.promises.lstat(p)).isDirectory()){await t.promises.mkdir(n,{recursive:!0});const N=await t.promises.readdir(p);for(const k of N)await w(a.join(p,k),a.join(n,k))}else await t.promises.copyFile(p,n)}await w(e,i),await t.promises.rm(e,{recursive:!0,force:!0})}else throw s}}async function st(e,i,s,w,p,n){const g=i&&i.trim(),N=s&&s.trim(),k=w&&w.trim(),c=Array.isArray(p)&&p.length>0;if(!g&&!N&&!k&&!c)return;const f=a.join(e,".claude");try{if(t.existsSync(f)||await t.promises.mkdir(f,{recursive:!0}),g)try{const d={mcpServers:JSON.parse(i)},y=a.join(e,".mcp.json");await t.promises.writeFile(y,JSON.stringify(d,null,2),"utf-8"),o(n,"INFO","Written .mcp.json to workspace root")}catch(d){o(n,"WARN","Failed to parse/write mcpServersConfig, skipping",{error:d.message})}const m={};if(N)try{m.hooks=JSON.parse(s)}catch(d){o(n,"WARN","Failed to parse hooksConfig, skipping",{error:d.message})}if(k)try{m.permissions=JSON.parse(w)}catch(d){o(n,"WARN","Failed to parse permissionsConfig, skipping",{error:d.message})}if(Object.keys(m).length>0){const d=a.join(f,"settings.json");await t.promises.writeFile(d,JSON.stringify(m,null,2),"utf-8"),o(n,"INFO","Written .claude/settings.json",{keys:Object.keys(m)})}if(c){const d=a.join(f,"hooks");t.existsSync(d)||await t.promises.mkdir(d,{recursive:!0});for(const y of p){if(!y||!y.path||!y.content)continue;const l=a.normalize(y.path);if(l.startsWith("..")||a.isAbsolute(l)){o(n,"WARN","Hook script path contains traversal, skipping",{path:y.path});continue}const x=a.join(f,l),O=a.dirname(x);t.existsSync(O)||await t.promises.mkdir(O,{recursive:!0}),await t.promises.writeFile(x,y.content,"utf-8"),await t.promises.chmod(x,493),o(n,"INFO","Written hook script",{path:y.path})}}}catch(m){o(n,"WARN","Failed to write .claude/settings or .mcp.json or hook scripts, not blocking workspace creation",{error:m.message})}}async function at(e,i,s,w,p,n,g,N){const k=Date.now(),c=`computer:${e}:${i}`,f=Q(w),m=[],d=[],y=new Set;if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!i)throw new h("cId cannot be empty",{field:"cId"});const l=await G(c),x=a.join(l,String(e),String(i),".tmp"),O=a.join(l,String(e),String(i)),{skillsDir:u,agentsDir:j,agentTypes:A}=await Y(O);t.existsSync(O)||await t.promises.mkdir(O,{recursive:!0});const D=a.join(x,`preserved_skills_${Date.now()}_${Math.round(Math.random()*1e6)}`);if(t.existsSync(u)){const F=(await t.promises.readdir(u,{withFileTypes:!0})).filter(z=>z.isDirectory()&&it(a.join(u,z.name)));if(F.length>0){await t.promises.mkdir(D,{recursive:!0});for(const z of F){const S=a.join(u,z.name),v=a.join(D,z.name);await $(S,v)}o(c,"INFO","\u4FDD\u7559\u542B .dynamic_add.lock \u7684 skill",{preserved:F.map(z=>z.name)})}}if(await W(u),await W(j),await t.promises.mkdir(u,{recursive:!0}),await t.promises.mkdir(j,{recursive:!0}),t.existsSync(D)){const r=await t.promises.readdir(D,{withFileTypes:!0});for(const F of r)if(F.isDirectory()){const z=a.join(D,F.name),S=a.join(u,F.name);await $(z,S)}await W(D)}const P=t.existsSync(u),M=t.existsSync(j);o(c,"INFO","Deleted old skills and agents directories completed",{userId:e,cId:i,targetSkillsDir:u,targetAgentsDir:j,agentTypes:A,skillsExists:P,agentsExists:M});const E=a.join(O,".mcp.json");t.existsSync(E)&&await t.promises.unlink(E);const b=a.join(O,".claude","settings.json");if(t.existsSync(b)&&await t.promises.unlink(b),await st(O,p,g,n,N,c),!s&&f.length===0)return await V(O),o(c,"INFO","Created workspace (no uploaded file, no skills and agents)",{userId:e,cId:i,workspaceRoot:l,skillsDir:null,agentsDir:null,agentTypes:A,elapsedMs:Date.now()-k}),{message:"Workspace created (no uploaded file, no skills and agents)",workspaceRoot:l};if(s){if(!s.path)throw new h("Uploaded file has no valid path",{field:"file.path"});if(a.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new h("Only zip files are supported",{field:"file",originalName:s.originalname})}o(c,"DEBUG","Start processing workspace resources",{userId:e,cId:i,workspaceRoot:l,hasUploadedZip:!!s,skillUrlsCount:f.length});try{t.existsSync(x)||await t.promises.mkdir(x,{recursive:!0});const r=[];if(s){const S=a.join(x,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);d.push(S),await t.promises.mkdir(S,{recursive:!0}),o(c,"DEBUG","Start extracting uploaded zip file",{extractRoot:S}),await B(s.path,S),o(c,"DEBUG","Uploaded zip file extracted successfully",{extractRoot:S});const v=await H(S,"skills"),T=await H(S,"agents");if(v){await t.promises.mkdir(u,{recursive:!0});const _=await t.promises.readdir(v,{withFileTypes:!0});for(const C of _){if(!C.isDirectory())continue;const L=a.join(v,C.name),J=a.join(u,C.name);t.existsSync(J)&&await W(J),await $(L,J),y.add(C.name)}r.push("skills"),o(c,"INFO","skills updated to workspace",{userId:e,cId:i,workspaceRoot:l,targetSkillsDir:u,agentTypes:A})}else o(c,"INFO","skills directory not found in uploaded zip, skipping",{userId:e,cId:i,extractRoot:S});T?(await W(j),await $(T,j),r.push("agents"),o(c,"INFO","agents updated to workspace",{userId:e,cId:i,workspaceRoot:l,targetAgentsDir:j,agentTypes:A})):o(c,"INFO","agents directory not found in uploaded zip, skipping",{userId:e,cId:i,extractRoot:S})}for(let S=0;S<f.length;S+=1){const v=f[S],T=a.join(x,`skill_url_${Date.now()}_${S}_${Math.round(Math.random()*1e6)}.zip`);m.push(T);const _=a.join(x,`skill_url_extract_${Date.now()}_${S}_${Math.round(Math.random()*1e6)}`);d.push(_),await t.promises.mkdir(_,{recursive:!0}),o(c,"INFO","Start download skill zip from url",{userId:e,cId:i,skillUrl:v}),await I(v,T,c),o(c,"INFO","Skill zip downloaded, start extracting",{userId:e,cId:i,skillUrl:v,downloadedZipPath:T}),await B(T,_);const L=(await t.promises.readdir(_,{withFileTypes:!0})).filter(R=>R.isDirectory()&&!R.name.startsWith(".")),q=L.find(R=>R.name==="skills")?(await t.promises.readdir(a.join(_,"skills"),{withFileTypes:!0})).filter(R=>R.isDirectory()&&!R.name.startsWith(".")).map(R=>({name:R.name,sourcePath:a.join(_,"skills",R.name)})):L.map(R=>({name:R.name,sourcePath:a.join(_,R.name)}));if(q.length===0){o(c,"WARN","No skill directory found after extracting skill url zip",{userId:e,cId:i,skillUrl:v,extractRoot:_});continue}await t.promises.mkdir(u,{recursive:!0});for(const R of q){const K=a.join(u,R.name);t.existsSync(K)&&await W(K),await $(R.sourcePath,K),y.add(R.name),o(c,"INFO","Skill from url updated to workspace",{userId:e,cId:i,skillUrl:v,skillName:R.name,destSkillPath:K})}r.includes("skills")||r.push("skills")}r.length===0&&o(c,"WARN","No valid skills or agents directories found",{userId:e,cId:i,hasUploadedZip:!!s,skillUrlsCount:f.length});const F=Array.from(y),z=r.length>0?`Workspace created successfully, ${r.join(" and ")} updated`:"Workspace created successfully (skills and agents directories not found)";return o(c,"INFO",z,{userId:e,cId:i,updatedDirs:r,updatedSkills:F,agentTypes:A,elapsedMs:Date.now()-k}),await V(O),{message:z,workspaceRoot:l,updatedSkills:F}}catch(r){throw o(c,"ERROR","Failed to process workspace resources",{userId:e,cId:i,error:r.message,elapsedMs:Date.now()-k}),r instanceof h||r instanceof Z||r instanceof U?r:new U(`Failed to create workspace: ${r.message}`,{userId:e,cId:i})}finally{try{for(const r of d)t.existsSync(r)&&await t.promises.rm(r,{recursive:!0,force:!0})}catch(r){o(c,"WARN","Failed to clean up temporary extracted zip",{error:r.message})}for(const r of m)try{t.existsSync(r)&&await t.promises.unlink(r)}catch(F){o(c,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:r,error:F.message})}try{s&&s.path&&t.existsSync(s.path)&&await t.promises.unlink(s.path)}catch(r){o(c,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:r.message})}}}async function ot(e,i,s,w){const p=Date.now(),n=`computer:${e}:${i}`,g=Q(w),N=[],k=[];if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!i)throw new h("cId cannot be empty",{field:"cId"});if(!s&&g.length===0)throw new h("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(s){if(!s.path)throw new h("Uploaded file has no valid path",{field:"file.path"});if(a.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new h("Only zip files are supported",{field:"file",originalName:s?.originalname})}const c=await G(n),f=a.join(c,String(e),String(i),".tmp"),m=a.join(c,String(e),String(i)),{skillsDir:d,agentTypes:y}=await Y(m);try{t.existsSync(m)||await t.promises.mkdir(m,{recursive:!0}),t.existsSync(d)||await t.promises.mkdir(d,{recursive:!0}),t.existsSync(f)||await t.promises.mkdir(f,{recursive:!0});const l=[],x=new Set;if(s){const u=a.join(f,`skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);k.push(u),await t.promises.mkdir(u,{recursive:!0}),o(n,"DEBUG","Start extracting skill zip file",{extractRoot:u}),await B(s.path,u),o(n,"DEBUG","Skill zip file extracted successfully",{extractRoot:u});const j=await H(u,"skills");if(!j)o(n,"WARN","skills directory not found in uploaded zip",{userId:e,cId:i,extractRoot:u});else{const D=(await t.promises.readdir(j,{withFileTypes:!0})).filter(P=>P.isDirectory()&&!P.name.startsWith("."));if(D.length===0)o(n,"WARN","skills directory in uploaded zip has no skill subdirectories",{userId:e,cId:i,skillsDir:j});else for(const P of D){const M=a.join(j,P.name),E=a.join(d,P.name);t.existsSync(E)&&await W(E),await $(M,E),x.add(P.name),o(n,"INFO","skill pushed to workspace from uploaded zip",{userId:e,cId:i,skillName:P.name,destSkillPath:E})}}}for(let u=0;u<g.length;u+=1){const j=g[u],A=a.join(f,`skill_push_url_${Date.now()}_${u}_${Math.round(Math.random()*1e6)}.zip`);N.push(A);const D=a.join(f,`skill_push_url_extract_${Date.now()}_${u}_${Math.round(Math.random()*1e6)}`);k.push(D),await t.promises.mkdir(D,{recursive:!0}),o(n,"INFO","Start download skill zip for push from url",{userId:e,cId:i,skillUrl:j}),await I(j,A,n),await B(A,D);const M=(await t.promises.readdir(D,{withFileTypes:!0})).filter(r=>r.isDirectory()&&!r.name.startsWith(".")),b=M.find(r=>r.name==="skills")?(await t.promises.readdir(a.join(D,"skills"),{withFileTypes:!0})).filter(r=>r.isDirectory()&&!r.name.startsWith(".")).map(r=>({name:r.name,sourcePath:a.join(D,"skills",r.name)})):M.map(r=>({name:r.name,sourcePath:a.join(D,r.name)}));if(b.length===0){o(n,"WARN","No skill directory found after extracting push skill url zip",{userId:e,cId:i,skillUrl:j,extractRoot:D});continue}for(const r of b){const F=a.join(d,r.name);t.existsSync(F)&&await W(F),await $(r.sourcePath,F),x.add(r.name),o(n,"INFO","skill pushed to workspace from url zip",{userId:e,cId:i,skillUrl:j,skillName:r.name,destSkillPath:F})}}for(const u of x)l.push(u);const O=l.length>0?`Pushed ${l.length} skills: ${l.join(", ")}`:"No valid skill directories found in file or skillUrls";return o(n,"INFO",O,{userId:e,cId:i,updatedSkills:l,agentTypes:y,elapsedMs:Date.now()-p}),await V(m),{message:O,workspaceRoot:c,updatedSkills:l}}catch(l){throw o(n,"ERROR","Failed to push skill to workspace",{userId:e,cId:i,error:l.message,elapsedMs:Date.now()-p}),l instanceof h||l instanceof Z||l instanceof U?l:new U(`Failed to push skill to workspace: ${l.message}`,{userId:e,cId:i})}finally{try{for(const l of k)t.existsSync(l)&&await t.promises.rm(l,{recursive:!0,force:!0})}catch(l){o(n,"WARN","Failed to clean up temporary extracted zip",{error:l.message})}for(const l of N)try{t.existsSync(l)&&await t.promises.unlink(l)}catch(x){o(n,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:l,error:x.message})}try{s&&s.path&&t.existsSync(s.path)&&await t.promises.unlink(s.path)}catch(l){o(n,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:l.message})}}}async function rt(e,i,s,w){const p=Date.now(),n=`computer:${e}:${i}`;if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!i)throw new h("cId cannot be empty",{field:"cId"});if(!s||!s.path)throw new h("file is required",{field:"file"});if(a.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new h("Only zip files are supported",{field:"file",originalName:s.originalname});const N=await G(n),k=a.join(N,String(e),String(i)),c=a.join(k,".tmp"),f=a.join(c,`template_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{t.existsSync(k)||await t.promises.mkdir(k,{recursive:!0}),t.existsSync(c)||await t.promises.mkdir(c,{recursive:!0}),await t.promises.mkdir(f,{recursive:!0}),o(n,"DEBUG","Start extracting template zip file",{extractRoot:f}),await B(s.path,f),o(n,"DEBUG","Template zip file extracted successfully",{extractRoot:f});const m=await t.promises.readdir(f,{withFileTypes:!0});for(const d of m){const y=a.join(f,d.name),l=a.join(k,d.name);if(d.isDirectory())await $(y,l);else{const x=a.dirname(l);t.existsSync(x)||await t.promises.mkdir(x,{recursive:!0}),await t.promises.copyFile(y,l)}}if(o(n,"INFO","Template files extracted to workspace",{userId:e,cId:i,targetDir:k,fileCount:m.length}),X.GIT_ENABLED&&(w==="true"||w===!0)){const d=await import("../../service/gitService.js");await d.default.init({workspaceType:"taskAgent",userId:e,cId:i}),await d.default.commit({workspaceType:"taskAgent",userId:e,cId:i,message:"Initial commit"}),o(n,"INFO","Git init and initial commit done",{userId:e,cId:i})}return o(n,"INFO","Init project template completed",{userId:e,cId:i,targetDir:k,elapsedMs:Date.now()-p}),{message:"Project template initialized successfully",workspaceRoot:k}}catch(m){throw o(n,"ERROR","Failed to init project template",{userId:e,cId:i,error:m.message,elapsedMs:Date.now()-p}),m instanceof h||m instanceof Z||m instanceof U?m:new U(`Failed to init project template: ${m.message}`,{userId:e,cId:i})}finally{try{t.existsSync(f)&&await t.promises.rm(f,{recursive:!0,force:!0})}catch(m){o(n,"WARN","Failed to clean up temporary extracted zip",{error:m.message})}try{s&&s.path&&t.existsSync(s.path)&&await t.promises.unlink(s.path)}catch(m){o(n,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:m.message})}}}async function nt(e,i,s){if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!i)throw new h("cId cannot be empty",{field:"cId"});if(!s||typeof s!="string"||!s.trim())throw new h("command cannot be empty",{field:"command"});const w=await G("computer"),p=a.join(w,String(e),String(i));if(!t.existsSync(p))throw new h("workspace directory does not exist",{field:"workDir",workDir:p});const n=`computer:${e}:${i}`;o(n,"INFO","Execute command in workspace",{userId:e,cId:i,workDir:p,command:s});const g=10*60*1e3;return new Promise((N,k)=>{tt(s,{cwd:p,timeout:g,maxBuffer:50*1024*1024},(c,f,m)=>{const d=c?c.killed?-1:c.code||1:0,y=c&&c.killed?(m||"")+`
2
- Command timed out after ${g/1e3}s`:m||"";o(n,"INFO","Execute command completed",{userId:e,cId:i,exitCode:d,killed:c?c.killed:!1,stdoutLength:f?f.length:0,stderrLength:y.length}),N({stdout:f||"",stderr:y,exitCode:d})})})}async function ct(e,i){const s=`computer:${e}:${i}`;if(!e)throw new h("userId cannot be empty",{field:"userId"});if(!i)throw new h("cId cannot be empty",{field:"cId"});const w=await G(s),p=a.join(w,String(e),String(i));return t.existsSync(p)?(await t.promises.rm(p,{recursive:!0,force:!0}),o(s,"INFO","Workspace deleted",{userId:e,cId:i,targetDir:p})):o(s,"WARN","Workspace not found, skip delete",{userId:e,cId:i,targetDir:p}),{deleted:!0}}export{at as createWorkspace,ot as pushSkillsToWorkspace,rt as initProjectTemplate,nt as executeCommand,ct as deleteWorkspace};
1
+ import i from"fs";import r from"path";import{exec as it}from"child_process";import st from"cross-spawn";import ot from"archiver";import v from"../../appConfig/index.js";import{extractZip as H}from"../common/zipUtils.js";import{ValidationError as y,SystemError as W,FileError as Z}from"../error/errorHandler.js";import{log as o}from"../log/logUtils.js";import{ensurePrimaryAgentDirs as Q,syncAgents as X}from"../common/AgentWorkspaceUtils.js";function I(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean);if(typeof e=="string"){const t=e.trim();if(!t)return[];try{const s=JSON.parse(t);if(Array.isArray(s))return s.map(c=>typeof c=="string"?c.trim():"").filter(Boolean)}catch{}return[t]}return[]}async function tt(e,t,s){let c;try{c=await fetch(e)}catch(g){throw new Z(`Failed to download skill zip from url: ${e}`,{url:e,reason:g.message})}if(!c.ok)throw new Z(`Failed to download skill zip from url: ${e}`,{url:e,status:c.status,statusText:c.statusText});const n=c.headers.get("content-type")||"";n&&!n.includes("zip")&&!n.includes("octet-stream")&&o(s,"WARN","Downloaded skill url content-type is not typical zip",{url:e,contentType:n});const a=await c.arrayBuffer(),h=Buffer.from(a);await i.promises.writeFile(t,h)}async function b(e="computer"){const t=v.COMPUTER_WORKSPACE_DIR;if(!t)throw new y("COMPUTER_WORKSPACE_DIR configuration does not exist",{field:"COMPUTER_WORKSPACE_DIR"});return i.existsSync(t)||(await i.promises.mkdir(t,{recursive:!0}),o(e,"INFO","Created user workspace root directory",{workspaceRoot:t})),t}async function q(e,t){const s=r.join(e,t);if(i.existsSync(s)&&(await i.promises.lstat(s)).isDirectory())return s;const c=await i.promises.readdir(e,{withFileTypes:!0});for(const n of c){if(!n.isDirectory())continue;const a=r.join(e,n.name),h=r.join(a,t);if(i.existsSync(h)&&(await i.promises.lstat(h)).isDirectory())return h}return null}async function At(e){return q(e,"skills")}const rt=".dynamic_add.lock";function at(e){const t=r.join(e,rt);return i.existsSync(t)&&i.statSync(t).isFile()}async function C(e){i.existsSync(e)&&await i.promises.rm(e,{recursive:!0,force:!0})}async function M(e,t){try{await i.promises.rename(e,t)}catch(s){if(s.code==="EXDEV"){async function c(n,a){if((await i.promises.lstat(n)).isDirectory()){await i.promises.mkdir(a,{recursive:!0});const g=await i.promises.readdir(n);for(const u of g)await c(r.join(n,u),r.join(a,u))}else await i.promises.copyFile(n,a)}await c(e,t),await i.promises.rm(e,{recursive:!0,force:!0})}else throw s}}async function nt(e,t,s,c,n,a){const h=t&&t.trim(),g=s&&s.trim(),u=c&&c.trim(),d=Array.isArray(n)&&n.length>0;if(!h&&!g&&!u&&!d)return;const w=r.join(e,".claude");try{if(i.existsSync(w)||await i.promises.mkdir(w,{recursive:!0}),h)try{const p={mcpServers:JSON.parse(t)},S=r.join(e,".mcp.json");await i.promises.writeFile(S,JSON.stringify(p,null,2),"utf-8"),o(a,"INFO","Written .mcp.json to workspace root")}catch(p){o(a,"WARN","Failed to parse/write mcpServersConfig, skipping",{error:p.message})}const f={};if(g)try{f.hooks=JSON.parse(s)}catch(p){o(a,"WARN","Failed to parse hooksConfig, skipping",{error:p.message})}if(u)try{f.permissions=JSON.parse(c)}catch(p){o(a,"WARN","Failed to parse permissionsConfig, skipping",{error:p.message})}if(Object.keys(f).length>0){const p=r.join(w,"settings.json");await i.promises.writeFile(p,JSON.stringify(f,null,2),"utf-8"),o(a,"INFO","Written .claude/settings.json",{keys:Object.keys(f)})}if(d){const p=r.join(w,"hooks");i.existsSync(p)||await i.promises.mkdir(p,{recursive:!0});for(const S of n){if(!S||!S.path||!S.content)continue;const l=r.normalize(S.path);if(l.startsWith("..")||r.isAbsolute(l)){o(a,"WARN","Hook script path contains traversal, skipping",{path:S.path});continue}const x=r.join(w,l),P=r.dirname(x);i.existsSync(P)||await i.promises.mkdir(P,{recursive:!0}),await i.promises.writeFile(x,S.content,"utf-8"),await i.promises.chmod(x,493),o(a,"INFO","Written hook script",{path:S.path})}}}catch(f){o(a,"WARN","Failed to write .claude/settings or .mcp.json or hook scripts, not blocking workspace creation",{error:f.message})}}async function ct(e,t,s,c,n,a,h,g){const u=Date.now(),d=`computer:${e}:${t}`,w=I(c),f=[],p=[],S=new Set;if(!e)throw new y("userId cannot be empty",{field:"userId"});if(!t)throw new y("cId cannot be empty",{field:"cId"});const l=await b(d),x=r.join(l,String(e),String(t),".tmp"),P=r.join(l,String(e),String(t)),{skillsDir:k,agentsDir:R,agentTypes:z}=await Q(P);i.existsSync(P)||await i.promises.mkdir(P,{recursive:!0});const D=r.join(x,`preserved_skills_${Date.now()}_${Math.round(Math.random()*1e6)}`);if(i.existsSync(k)){const N=(await i.promises.readdir(k,{withFileTypes:!0})).filter(O=>O.isDirectory()&&at(r.join(k,O.name)));if(N.length>0){await i.promises.mkdir(D,{recursive:!0});for(const O of N){const j=r.join(k,O.name),E=r.join(D,O.name);await M(j,E)}o(d,"INFO","\u4FDD\u7559\u542B .dynamic_add.lock \u7684 skill",{preserved:N.map(O=>O.name)})}}if(await C(k),await C(R),await i.promises.mkdir(k,{recursive:!0}),await i.promises.mkdir(R,{recursive:!0}),i.existsSync(D)){const m=await i.promises.readdir(D,{withFileTypes:!0});for(const N of m)if(N.isDirectory()){const O=r.join(D,N.name),j=r.join(k,N.name);await M(O,j)}await C(D)}const A=i.existsSync(k),T=i.existsSync(R);o(d,"INFO","Deleted old skills and agents directories completed",{userId:e,cId:t,targetSkillsDir:k,targetAgentsDir:R,agentTypes:z,skillsExists:A,agentsExists:T});const $=r.join(P,".mcp.json");i.existsSync($)&&await i.promises.unlink($);const B=r.join(P,".claude","settings.json");if(i.existsSync(B)&&await i.promises.unlink(B),await nt(P,n,h,a,g,d),!s&&w.length===0)return await X(P),o(d,"INFO","Created workspace (no uploaded file, no skills and agents)",{userId:e,cId:t,workspaceRoot:l,skillsDir:null,agentsDir:null,agentTypes:z,elapsedMs:Date.now()-u}),{message:"Workspace created (no uploaded file, no skills and agents)",workspaceRoot:l};if(s){if(!s.path)throw new y("Uploaded file has no valid path",{field:"file.path"});if(r.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new y("Only zip files are supported",{field:"file",originalName:s.originalname})}o(d,"DEBUG","Start processing workspace resources",{userId:e,cId:t,workspaceRoot:l,hasUploadedZip:!!s,skillUrlsCount:w.length});try{i.existsSync(x)||await i.promises.mkdir(x,{recursive:!0});const m=[];if(s){const j=r.join(x,`skill_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);p.push(j),await i.promises.mkdir(j,{recursive:!0}),o(d,"DEBUG","Start extracting uploaded zip file",{extractRoot:j}),await H(s.path,j),o(d,"DEBUG","Uploaded zip file extracted successfully",{extractRoot:j});const E=await q(j,"skills"),U=await q(j,"agents");if(E){await i.promises.mkdir(k,{recursive:!0});const _=await i.promises.readdir(E,{withFileTypes:!0});for(const L of _){if(!L.isDirectory())continue;const G=r.join(E,L.name),K=r.join(k,L.name);i.existsSync(K)&&await C(K),await M(G,K),S.add(L.name)}m.push("skills"),o(d,"INFO","skills updated to workspace",{userId:e,cId:t,workspaceRoot:l,targetSkillsDir:k,agentTypes:z})}else o(d,"INFO","skills directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:j});U?(await C(R),await M(U,R),m.push("agents"),o(d,"INFO","agents updated to workspace",{userId:e,cId:t,workspaceRoot:l,targetAgentsDir:R,agentTypes:z})):o(d,"INFO","agents directory not found in uploaded zip, skipping",{userId:e,cId:t,extractRoot:j})}for(let j=0;j<w.length;j+=1){const E=w[j],U=r.join(x,`skill_url_${Date.now()}_${j}_${Math.round(Math.random()*1e6)}.zip`);f.push(U);const _=r.join(x,`skill_url_extract_${Date.now()}_${j}_${Math.round(Math.random()*1e6)}`);p.push(_),await i.promises.mkdir(_,{recursive:!0}),o(d,"INFO","Start download skill zip from url",{userId:e,cId:t,skillUrl:E}),await tt(E,U,d),o(d,"INFO","Skill zip downloaded, start extracting",{userId:e,cId:t,skillUrl:E,downloadedZipPath:U}),await H(U,_);const G=(await i.promises.readdir(_,{withFileTypes:!0})).filter(F=>F.isDirectory()&&!F.name.startsWith(".")),Y=G.find(F=>F.name==="skills")?(await i.promises.readdir(r.join(_,"skills"),{withFileTypes:!0})).filter(F=>F.isDirectory()&&!F.name.startsWith(".")).map(F=>({name:F.name,sourcePath:r.join(_,"skills",F.name)})):G.map(F=>({name:F.name,sourcePath:r.join(_,F.name)}));if(Y.length===0){o(d,"WARN","No skill directory found after extracting skill url zip",{userId:e,cId:t,skillUrl:E,extractRoot:_});continue}await i.promises.mkdir(k,{recursive:!0});for(const F of Y){const J=r.join(k,F.name);i.existsSync(J)&&await C(J),await M(F.sourcePath,J),S.add(F.name),o(d,"INFO","Skill from url updated to workspace",{userId:e,cId:t,skillUrl:E,skillName:F.name,destSkillPath:J})}m.includes("skills")||m.push("skills")}m.length===0&&o(d,"WARN","No valid skills or agents directories found",{userId:e,cId:t,hasUploadedZip:!!s,skillUrlsCount:w.length});const N=Array.from(S),O=m.length>0?`Workspace created successfully, ${m.join(" and ")} updated`:"Workspace created successfully (skills and agents directories not found)";return o(d,"INFO",O,{userId:e,cId:t,updatedDirs:m,updatedSkills:N,agentTypes:z,elapsedMs:Date.now()-u}),await X(P),{message:O,workspaceRoot:l,updatedSkills:N}}catch(m){throw o(d,"ERROR","Failed to process workspace resources",{userId:e,cId:t,error:m.message,elapsedMs:Date.now()-u}),m instanceof y||m instanceof Z||m instanceof W?m:new W(`Failed to create workspace: ${m.message}`,{userId:e,cId:t})}finally{try{for(const m of p)i.existsSync(m)&&await i.promises.rm(m,{recursive:!0,force:!0})}catch(m){o(d,"WARN","Failed to clean up temporary extracted zip",{error:m.message})}for(const m of f)try{i.existsSync(m)&&await i.promises.unlink(m)}catch(N){o(d,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:m,error:N.message})}try{s&&s.path&&i.existsSync(s.path)&&await i.promises.unlink(s.path)}catch(m){o(d,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:m.message})}}}async function lt(e,t,s,c){const n=Date.now(),a=`computer:${e}:${t}`,h=I(c),g=[],u=[];if(!e)throw new y("userId cannot be empty",{field:"userId"});if(!t)throw new y("cId cannot be empty",{field:"cId"});if(!s&&h.length===0)throw new y("file or skillUrls cannot both be empty",{field:"file|skillUrls"});if(s){if(!s.path)throw new y("Uploaded file has no valid path",{field:"file.path"});if(r.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new y("Only zip files are supported",{field:"file",originalName:s?.originalname})}const d=await b(a),w=r.join(d,String(e),String(t),".tmp"),f=r.join(d,String(e),String(t)),{skillsDir:p,agentTypes:S}=await Q(f);try{i.existsSync(f)||await i.promises.mkdir(f,{recursive:!0}),i.existsSync(p)||await i.promises.mkdir(p,{recursive:!0}),i.existsSync(w)||await i.promises.mkdir(w,{recursive:!0});const l=[],x=new Set;if(s){const k=r.join(w,`skill_push_${Date.now()}_${Math.round(Math.random()*1e6)}`);u.push(k),await i.promises.mkdir(k,{recursive:!0}),o(a,"DEBUG","Start extracting skill zip file",{extractRoot:k}),await H(s.path,k),o(a,"DEBUG","Skill zip file extracted successfully",{extractRoot:k});const R=await q(k,"skills");if(!R)o(a,"WARN","skills directory not found in uploaded zip",{userId:e,cId:t,extractRoot:k});else{const D=(await i.promises.readdir(R,{withFileTypes:!0})).filter(A=>A.isDirectory()&&!A.name.startsWith("."));if(D.length===0)o(a,"WARN","skills directory in uploaded zip has no skill subdirectories",{userId:e,cId:t,skillsDir:R});else for(const A of D){const T=r.join(R,A.name),$=r.join(p,A.name);i.existsSync($)&&await C($),await M(T,$),x.add(A.name),o(a,"INFO","skill pushed to workspace from uploaded zip",{userId:e,cId:t,skillName:A.name,destSkillPath:$})}}}for(let k=0;k<h.length;k+=1){const R=h[k],z=r.join(w,`skill_push_url_${Date.now()}_${k}_${Math.round(Math.random()*1e6)}.zip`);g.push(z);const D=r.join(w,`skill_push_url_extract_${Date.now()}_${k}_${Math.round(Math.random()*1e6)}`);u.push(D),await i.promises.mkdir(D,{recursive:!0}),o(a,"INFO","Start download skill zip for push from url",{userId:e,cId:t,skillUrl:R}),await tt(R,z,a),await H(z,D);const T=(await i.promises.readdir(D,{withFileTypes:!0})).filter(m=>m.isDirectory()&&!m.name.startsWith(".")),B=T.find(m=>m.name==="skills")?(await i.promises.readdir(r.join(D,"skills"),{withFileTypes:!0})).filter(m=>m.isDirectory()&&!m.name.startsWith(".")).map(m=>({name:m.name,sourcePath:r.join(D,"skills",m.name)})):T.map(m=>({name:m.name,sourcePath:r.join(D,m.name)}));if(B.length===0){o(a,"WARN","No skill directory found after extracting push skill url zip",{userId:e,cId:t,skillUrl:R,extractRoot:D});continue}for(const m of B){const N=r.join(p,m.name);i.existsSync(N)&&await C(N),await M(m.sourcePath,N),x.add(m.name),o(a,"INFO","skill pushed to workspace from url zip",{userId:e,cId:t,skillUrl:R,skillName:m.name,destSkillPath:N})}}for(const k of x)l.push(k);const P=l.length>0?`Pushed ${l.length} skills: ${l.join(", ")}`:"No valid skill directories found in file or skillUrls";return o(a,"INFO",P,{userId:e,cId:t,updatedSkills:l,agentTypes:S,elapsedMs:Date.now()-n}),await X(f),{message:P,workspaceRoot:d,updatedSkills:l}}catch(l){throw o(a,"ERROR","Failed to push skill to workspace",{userId:e,cId:t,error:l.message,elapsedMs:Date.now()-n}),l instanceof y||l instanceof Z||l instanceof W?l:new W(`Failed to push skill to workspace: ${l.message}`,{userId:e,cId:t})}finally{try{for(const l of u)i.existsSync(l)&&await i.promises.rm(l,{recursive:!0,force:!0})}catch(l){o(a,"WARN","Failed to clean up temporary extracted zip",{error:l.message})}for(const l of g)try{i.existsSync(l)&&await i.promises.unlink(l)}catch(x){o(a,"WARN","Failed to clean up downloaded skill zip file",{downloadedZipPath:l,error:x.message})}try{s&&s.path&&i.existsSync(s.path)&&await i.promises.unlink(s.path)}catch(l){o(a,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:l.message})}}}async function pt(e,t,s,c){const n=Date.now(),a=`computer:${e}:${t}`;if(!e)throw new y("userId cannot be empty",{field:"userId"});if(!t)throw new y("cId cannot be empty",{field:"cId"});if(!s||!s.path)throw new y("file is required",{field:"file"});if(r.extname(s.originalname||s.filename||"").toLowerCase()!==".zip")throw new y("Only zip files are supported",{field:"file",originalName:s.originalname});const g=await b(a),u=r.join(g,String(e),String(t)),d=r.join(u,".tmp"),w=r.join(d,`template_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{i.existsSync(u)||await i.promises.mkdir(u,{recursive:!0}),i.existsSync(d)||await i.promises.mkdir(d,{recursive:!0}),await i.promises.mkdir(w,{recursive:!0}),o(a,"DEBUG","Start extracting template zip file",{extractRoot:w}),await H(s.path,w),o(a,"DEBUG","Template zip file extracted successfully",{extractRoot:w});const f=await i.promises.readdir(w,{withFileTypes:!0});for(const p of f){const S=r.join(w,p.name),l=r.join(u,p.name);if(p.isDirectory())await M(S,l);else{const x=r.dirname(l);i.existsSync(x)||await i.promises.mkdir(x,{recursive:!0}),await i.promises.copyFile(S,l)}}if(o(a,"INFO","Template files extracted to workspace",{userId:e,cId:t,targetDir:u,fileCount:f.length}),v.GIT_ENABLED&&(c==="true"||c===!0)){const p=await import("../../service/gitService.js");await p.default.init({workspaceType:"taskAgent",userId:e,cId:t}),await p.default.commit({workspaceType:"taskAgent",userId:e,cId:t,message:"Initial commit"}),o(a,"INFO","Git init and initial commit done",{userId:e,cId:t})}return o(a,"INFO","Init project template completed",{userId:e,cId:t,targetDir:u,elapsedMs:Date.now()-n}),{message:"Project template initialized successfully",workspaceRoot:u}}catch(f){throw o(a,"ERROR","Failed to init project template",{userId:e,cId:t,error:f.message,elapsedMs:Date.now()-n}),f instanceof y||f instanceof Z||f instanceof W?f:new W(`Failed to init project template: ${f.message}`,{userId:e,cId:t})}finally{try{i.existsSync(w)&&await i.promises.rm(w,{recursive:!0,force:!0})}catch(f){o(a,"WARN","Failed to clean up temporary extracted zip",{error:f.message})}try{s&&s.path&&i.existsSync(s.path)&&await i.promises.unlink(s.path)}catch(f){o(a,"WARN","Failed to clean up uploaded zip file",{tempZipPath:s?.path,error:f.message})}}}async function mt(e,t,s){if(!e)throw new y("userId cannot be empty",{field:"userId"});if(!t)throw new y("cId cannot be empty",{field:"cId"});if(!s||typeof s!="string"||!s.trim())throw new y("command cannot be empty",{field:"command"});const c=await b("computer"),n=r.join(c,String(e),String(t));if(!i.existsSync(n))throw new y("workspace directory does not exist",{field:"workDir",workDir:n});const a=`computer:${e}:${t}`;o(a,"INFO","Execute command in workspace",{userId:e,cId:t,workDir:n,command:s});const h=10*60*1e3,g={cwd:n,timeout:h,maxBuffer:50*1024*1024};return v.BASH_PATH&&(g.shell=v.BASH_PATH),v.GIT_PATH&&(g.env={...process.env,PATH:`${v.GIT_PATH}${r.delimiter}${process.env.PATH}`}),new Promise((u,d)=>{it(s,g,(w,f,p)=>{const S=w?w.killed?-1:w.code||1:0,l=w&&w.killed?(p||"")+`
2
+ Command timed out after ${h/1e3}s`:p||"";o(a,"INFO","Execute command completed",{userId:e,cId:t,exitCode:S,killed:w?w.killed:!1,stdoutLength:f?f.length:0,stderrLength:l.length}),u({stdout:f||"",stderr:l,exitCode:S})})})}async function dt(e,t,s){const c=`computer:${e}:${t}`;if(!e)throw new y("userId cannot be empty",{field:"userId"});if(!t)throw new y("cId cannot be empty",{field:"cId"});const n=await b(c),a=r.join(n,String(e),String(t));if(!i.existsSync(a))throw new y("workspace directory does not exist",{field:"workDir",workDir:a});const h=v.ZIP_WORKSPACE_EXCLUDE_DIRS||[],g=Array.isArray(s)?s:[],u=new Set([...h,...g]),d=`${e}_${t}.zip`,w=Date.now();o(c,"INFO","Zip workspace request",{userId:e,cId:t,targetDir:a,excludeDirs:[...u]});const f=ot("zip",{zlib:{level:9}});return f.directory(a,!1,p=>{const S=p.name||"";if(S.split(/[\/\\]/).filter(Boolean).some(x=>u.has(x)))return!1;try{const x=r.join(a,S);if(i.lstatSync(x).isSymbolicLink())return!1}catch{return!1}return p}),f.on("warning",p=>{p.code==="ENOENT"?o(c,"WARN","Encountered file problem when creating zip",{message:p.message,code:p.code}):o(c,"ERROR","Encountered warning when creating zip",{message:p.message,code:p.code})}),f.on("error",p=>{o(c,"ERROR","Failed to create zip",{message:p.message,elapsedMs:Date.now()-w})}),f.on("end",()=>{o(c,"INFO","Workspace zip created successfully",{targetDir:a,zipFileName:d,elapsedMs:Date.now()-w})}),{archive:f,zipFileName:d}}const ft=new Set([...v.ZIP_WORKSPACE_EXCLUDE_DIRS||[],"dist-packages"]);function V(e){let t;try{t=i.readdirSync(e,{withFileTypes:!0})}catch{return null}const s=r.join(e,"scripts","package-platforms.mjs");if(i.existsSync(s))return e;for(const c of t)if(c.isDirectory()&&!ft.has(c.name)){const n=V(r.join(e,c.name));if(n)return n}return null}function et(e,t,s,c=10*60*1e3){return new Promise(n=>{const a=st(e,t,{...s,timeout:c});let h="",g="";a.stdout?.on("data",u=>{h+=u.toString()}),a.stderr?.on("data",u=>{g+=u.toString()}),a.on("error",u=>{n({stdout:h,stderr:g+`
3
+ Failed to spawn ${e}: ${u.message}`,exitCode:1})}),a.on("close",(u,d)=>{n(u===null&&d?{stdout:h,stderr:g+`
4
+ Process killed by signal ${d} (timeout after ${c/1e3}s)`,exitCode:-1}:{stdout:h,stderr:g,exitCode:u??1})})})}function ut(e){if(!e)return null;let t=e;t.endsWith(".tar.gz")?t=t.slice(0,-7):t.endsWith(".tar.bz2")?t=t.slice(0,-8):(t.endsWith(".tgz")||t.endsWith(".zip"))&&(t=t.slice(0,-4));const s=t.split("-");if(s.length<4)return null;let c=-1;for(let n=s.length-1;n>=2;n--)if(/^\d+\.\d+\.\d+$/.test(s[n])){c=n;break}return c<3?null:s.slice(2,c).join("-")}async function wt(e,t,s,c){const n=`computer:${e}:${t}`;if(!e)throw new y("userId cannot be empty",{field:"userId"});if(!t)throw new y("cId cannot be empty",{field:"cId"});if(!s)throw new y("agentId cannot be empty",{field:"agentId"});if(!c)throw new y("version cannot be empty",{field:"version"});const a=await b(n),h=r.join(a,String(e),String(t));if(!i.existsSync(h))throw new y("workspace directory does not exist",{field:"workDir",workDir:h});o(n,"INFO","Build agent package request",{userId:e,cId:t,agentId:s,version:c});const g=V(h);if(!g)throw new y("package-platforms.mjs not found in workspace",{field:"script"});o(n,"INFO","Found package script",{projectDir:g});const u={...process.env,CI:"true"};v.GIT_PATH&&(u.PATH=`${v.GIT_PATH}${r.delimiter}${process.env.PATH}`);const d=await et("pnpm",["install"],{cwd:g,env:u});if(o(n,"INFO","pnpm install completed",{exitCode:d.exitCode,stderrLength:d.stderr.length}),d.exitCode!==0)throw o(n,"ERROR","pnpm install failed",{stderr:d.stderr}),new W(`pnpm install failed: ${d.stderr}`);const w=r.join(g,"dist-packages"),f=["scripts/package-platforms.mjs",`agent-${s}`,c,w,"--print-artifacts"],p=await et("node",f,{cwd:g,env:u});if(o(n,"INFO","Build completed",{exitCode:p.exitCode,stdoutLength:p.stdout.length}),p.exitCode!==0)throw o(n,"ERROR","Build failed",{stderr:p.stderr}),new W(`Build failed: ${p.stderr}`);const S=[".tar.gz",".tar.bz2",".zip",".tgz"],l=[],x=p.stdout.split(`
5
+ `);for(const P of x){const k=P.trim();if(!k)continue;const R=k.toLowerCase();if(!S.some($=>R.endsWith($)))continue;const z=r.resolve(g,k);let D=r.relative(h,z);D=D.split(r.sep).join("/");const A=r.basename(k),T=ut(A);l.push({path:D,fileName:A,platform:T||""})}return o(n,"INFO","Build agent package completed",{artifactsCount:l.length,artifacts:l}),{artifacts:l}}async function ht(e,t){const s=`computer:${e}:${t}`;if(!e)throw new y("userId cannot be empty",{field:"userId"});if(!t)throw new y("cId cannot be empty",{field:"cId"});const c=await b(s),n=r.join(c,String(e),String(t));if(!i.existsSync(n))return o(s,"WARN","Workspace not found, skip cleanup",{userId:e,cId:t}),{cleaned:!1};const a=V(n);if(!a)return o(s,"WARN","package-platforms.mjs not found, skip cleanup",{userId:e,cId:t}),{cleaned:!1};const h=r.join(a,"dist-packages");return i.existsSync(h)?(i.rmSync(h,{recursive:!0,force:!0}),o(s,"INFO","Cleaned dist-packages",{distPackagesDir:h}),{cleaned:!0}):(o(s,"INFO","dist-packages not found, nothing to clean",{distPackagesDir:h}),{cleaned:!1})}async function kt(e,t){const s=`computer:${e}:${t}`;if(!e)throw new y("userId cannot be empty",{field:"userId"});if(!t)throw new y("cId cannot be empty",{field:"cId"});const c=await b(s),n=r.join(c,String(e),String(t));return i.existsSync(n)?(await i.promises.rm(n,{recursive:!0,force:!0}),o(s,"INFO","Workspace deleted",{userId:e,cId:t,targetDir:n})):o(s,"WARN","Workspace not found, skip delete",{userId:e,cId:t,targetDir:n}),{deleted:!0}}export{ct as createWorkspace,lt as pushSkillsToWorkspace,pt as initProjectTemplate,mt as executeCommand,kt as deleteWorkspace,dt as zipWorkspace,wt as buildAgentPackage,ht as cleanupBuildArtifacts};
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.13",
4
+ "version": "1.3.0-beta.15",
5
5
  "description": "Cross-platform file service deployment tool with start/stop/restart CLI commands",
6
6
  "type": "module",
7
7
  "main": "index.js",