nuwax-file-server 1.5.3 → 1.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.5.3",d=new ee,w={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"};function j(e){console.error(`${w.red}ERROR: ${e}${w.reset}`)}function b(e){console.log(`${w.green}${e}${w.reset}`)}function oe(e){console.log(`${w.blue}${e}${w.reset}`)}function y(e){return async(...t)=>{try{let o=await e(...t);o&&o.success===!1?(j(o.message||"Command failed"),process.exitCode=1):process.exitCode=0}catch(o){j(o?.message||"Command failed with unexpected error"),process.exitCode=1}}}async function se(e){let t=await N({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(`Service started (PID: ${t.pid})`),t}async function re(e){let t=await T({force:e.force,timeout:Number(e.timeout)});return t.success&&b(t.message||"Service stopped"),t}async function ne(e){let t=await O({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(t.message||"Service restarted"),t}function ie(){let e=_();return oe(`${n.name} service status:`),console.log(""),console.log(` Service name: ${n.name}`),console.log(` Running status: ${e.running?"Running":"Stopped"}`),console.log(` Message: ${e.message}`),console.log(` PID file: ${$()}`),e.pidInfo&&(console.log(` Process ID: ${e.pidInfo.pid}`),console.log(` Environment: ${e.pidInfo.env||"Unknown"}`),console.log(` Port: ${e.pidInfo.port||"Unknown"}`),console.log(` Version: ${e.pidInfo.version||A}`),console.log(` Platform: ${e.pidInfo.platform||process.platform}`),console.log(` Started at: ${e.pidInfo.startedAt||"Unknown"}`),console.log(` Uptime: ${L(e.pidInfo.startedAt)}`)),console.log(""),{success:e.running,message:e.message}}function ce(){d.name("nuwax-file-server").description("Cross-platform file service deployment tool, supporting start/stop/restart/status").version(A,"-v, --version","Display version number").helpOption("-h, --help","Display help information"),d.command("start").allowUnknownOption().description("Start service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(se)),d.command("stop").description("Stop service").option("--force","Force stop").option("--timeout <ms>","\u505C\u6B62\u670D\u52A1\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).action(y(re)),d.command("restart").allowUnknownOption().description("Restart service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(ne)),d.command("status").description("View service status").action(y(ie)),d.command("help").description("Display help information").action(()=>{d.outputHelp()}),d.parse(process.argv),process.argv.slice(2).length||(d.outputHelp(),process.exitCode=0)}ce();
2
+ import{Command as ee}from"commander";import{createRequire as te}from"module";import f from"path";import U from"os";import c from"fs-extra";import{spawn as E}from"cross-spawn";import V from"tree-kill";import{fileURLToPath as q}from"url";import{execFileSync as R}from"child_process";import M from"http";import{createRequire as G}from"module";var I=f.dirname(q(import.meta.url)),H=G(import.meta.url),n={name:"nuwax-file-server",pidDir:f.join(U.tmpdir(),"nuwax-file-server"),pidFileName:"server.pid",lockFileName:"start.lock",defaultStopTimeout:3e4,defaultStartTimeout:3e4,staleLockTimeout:12e4,checkInterval:500};function $(){return f.join(n.pidDir,n.pidFileName)}function F(){return f.join(n.pidDir,n.lockFileName)}function J(){let e=[f.join(I,"..","server.js"),f.join(I,"server.js")];for(let t of e)if(c.existsSync(t))return t;return e[0]}function W(){let e=["../../package.json","../package.json"];for(let t of e)try{let o=H(t);if(o?.version)return o.version}catch{}return"unknown"}function x(){try{let e=$();if(!c.existsSync(e))return null;let t=c.readFileSync(e,"utf8"),o=JSON.parse(t);return!o||typeof o.pid!="number"?null:o}catch(e){return e.code!=="ENOENT"&&console.error(`Read PID file failed: ${e.message}`),null}}function B(e){try{let t=$();c.ensureDirSync(n.pidDir),c.writeFileSync(t,JSON.stringify(e,null,2)),console.debug(`PID file written: ${t}`)}catch(t){throw console.error(`Write PID file failed: ${t.message}`),t}}function v(){try{let e=$();c.existsSync(e)&&(c.removeSync(e),console.debug(`PID file deleted: ${e}`))}catch(e){console.error(`Delete PID file failed: ${e.message}`)}}function g(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function K(e){try{return k()?R("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId = ${e}").CommandLine`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim():R("ps",["-p",String(e),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function X(e){if(!g(e))return!1;let t=K(e);if(!t)return!1;let o=t.toLowerCase(),s=f.basename(f.join(I,"..","server.js")).toLowerCase(),i=n.name.toLowerCase();return o.includes(s)||o.includes(i)}function z(){c.ensureDirSync(n.pidDir);let e=F(),t=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=JSON.stringify({pid:process.pid,token:t,createdAt:new Date().toISOString()},null,2);try{let s=c.openSync(e,"wx");return c.writeSync(s,o),{fd:s,token:t}}catch(s){if(s.code!=="EEXIST")throw s;try{let i=c.readFileSync(e,"utf8"),r=JSON.parse(i),a=Number(r?.pid),u=r?.createdAt?new Date(r.createdAt).getTime():0,l=Date.now()-u,C=Number.isFinite(a)&&a>0&&g(a),p=!u||Number.isNaN(l)||l>n.staleLockTimeout;if(!C||p){c.removeSync(e);let S=c.openSync(e,"wx");return c.writeSync(S,o),console.warn("Detected stale start lock, auto cleaned"),{fd:S,token:t}}}catch{c.removeSync(e);let r=c.openSync(e,"wx");return c.writeSync(r,o),console.warn("Detected invalid start lock, auto cleaned"),{fd:r,token:t}}throw s}}function Q(e){let t=e?.fd,o=e?.token;try{t!=null&&c.closeSync(t)}catch{}try{let s=F();if(c.existsSync(s)){let i=!1;if(!o)i=!0;else try{let r=c.readFileSync(s,"utf8");i=JSON.parse(r)?.token===o}catch{i=!0}i&&c.removeSync(s)}}catch{}}function k(){return process.platform==="win32"}async function Y(e=n.defaultStopTimeout){let t=x();return t?X(t.pid)?(console.log(`Existing service process detected (PID: ${t.pid}), stopping before start...`),await h(t.pid,!1)&&await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped gracefully`}):(console.warn(`Graceful stop timeout or failed for PID ${t.pid}, force stop...`),await h(t.pid,!0)?await D(t.pid,e)?(v(),{success:!0,message:`Existing process ${t.pid} stopped forcibly`}):{success:!1,message:`Existing process ${t.pid} did not exit after force stop`}:{success:!1,message:`Failed to stop existing process ${t.pid}`})):(console.log(`Found stale PID file (PID: ${t.pid}), clean it...`),v(),{success:!0,message:"Stale PID file cleaned"}):{success:!0,message:"No existing service process"}}async function h(e,t=!1){return new Promise(o=>{if(!g(e)){console.debug(`Process ${e} does not exist, already stopped`),o(!0);return}let s=t?"SIGKILL":"SIGTERM",i=k()?"taskkill":"tree-kill";if(console.debug(`Use ${i} to stop process ${e} (signal: ${s})`),k()){let r=t?["/F","/PID",String(e)]:["/PID",String(e)],a=E("taskkill",r,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),u="";a.stdout.on("data",l=>{u+=l.toString()}),a.stderr.on("data",l=>{u+=l.toString()}),a.on("error",l=>{console.error(`Stop process failed: ${l.message}`),o(!1)}),a.on("close",l=>{l===0?(console.debug(`Process ${e} stopped`),o(!0)):(console.warn(`taskkill exit code: ${l}, output: ${u}`),t?o(!1):h(e,!0).then(o))})}else V(e,s,r=>{r?r.code==="ESRCH"?(console.debug(`Process ${e} does not exist`),o(!0)):(console.error(`Stop process failed: ${r.message}`),o(!1)):(console.debug(`Process ${e} stopped`),o(!0))})})}async function D(e,t=n.defaultStopTimeout){let o=Date.now();for(;g(e);){if(Date.now()-o>t)return console.warn(`Wait for process ${e} to stop timeout (${t}ms)`),!1;await new Promise(i=>setTimeout(i,n.checkInterval))}let s=Date.now()-o;return console.debug(`Process ${e} stopped after ${s}ms`),!0}async function Z(e,t=n.defaultStartTimeout){let o=Number(e);if(!Number.isFinite(o)||o<=0)return!1;let s=Date.now();for(;Date.now()-s<=t;){if(await new Promise(r=>{let a=M.get({host:"127.0.0.1",port:o,path:"/health",timeout:Math.min(2e3,n.checkInterval*4)},u=>{r(u.statusCode>=200&&u.statusCode<300),u.resume()});a.on("timeout",()=>{a.destroy(),r(!1)}),a.on("error",()=>r(!1))}))return!0;await new Promise(r=>setTimeout(r,n.checkInterval))}return!1}async function N(e={}){let{env:t,port:o,config:s}=e,i=null;console.log(`Start service ${n.name}...`);try{i=z()}catch(r){return r.code==="EEXIST"?{success:!1,pid:null,message:"Another start operation is in progress, please retry later"}:{success:!1,pid:null,message:`Acquire start lock failed: ${r.message}`}}try{let r=Number(e.timeout)||n.defaultStopTimeout,a=await Y(r);if(!a.success)return{success:!1,pid:null,message:`Service start blocked: ${a.message}`};let u={...process.env};t&&(u.NODE_ENV=t,console.log(`Environment: ${t}`)),o&&(u.PORT=o,console.log(`Port: ${o}`)),s&&(u.CONFIG_FILE=s,console.log(`Configuration file: ${s}`));let l=J(),p=E("node",[l,...[]],{env:u,stdio:["pipe","pipe","pipe"],detached:!0,cwd:process.cwd()});if(p.stdout.on("data",m=>{process.stdout.write(m)}),p.stderr.on("data",m=>{process.stderr.write(m)}),p.on("error",m=>{console.error(`Start service failed: ${m.message}`)}),await new Promise(m=>setTimeout(m,2e3)),!g(p.pid))return{success:!1,pid:null,message:"Service start failed"};let S={pid:p.pid,startedAt:new Date().toISOString(),env:t||process.env.NODE_ENV||"production",port:o||process.env.PORT||"60000",version:W(),platform:process.platform};B(S);let P=Number(e.startTimeout)||n.defaultStartTimeout;return await Z(S.port,P)?(p.unref(),console.log(`Service started (PID: ${p.pid})`),console.log(`Service address: http://localhost:${S.port}`),{success:!0,pid:p.pid,message:"Service started successfully"}):(console.error(`Service health check timeout (${P}ms), stop failed instance...`),await h(p.pid,!0),v(),{success:!1,pid:null,message:`Service health check timeout (${P}ms)`})}finally{Q(i)}}async function T(e={}){let{force:t=!1,timeout:o=n.defaultStopTimeout}=e;console.log(`Stop service ${n.name}...`);let s=x();if(!s)return{success:!1,message:"Service not found"};if(!g(s.pid))return console.log("Service process has stopped, clean PID file..."),v(),{success:!0,message:"Service has stopped (process has exited)"};if(!await h(s.pid,t))return{success:!1,message:"Stop service failed"};let r=await D(s.pid,o);return v(),r?{success:!0,message:"Service has stopped"}:{success:!1,message:"Service stop timeout"}}async function O(e={}){console.log(`Restart service ${n.name}...`);let t=await T(e);!t.success&&t.message!=="Service not found"&&console.warn(`Stop service failed: ${t.message}`),await new Promise(s=>setTimeout(s,2e3));let o=await N(e);return o.success?{success:!0,pid:o.pid,message:"Service has restarted"}:{success:!1,pid:null,message:`Restart failed: ${o.message}`}}function _(){let e=x();return e?g(e.pid)?{running:!0,pidInfo:e,message:"Service running"}:{running:!1,pidInfo:e,message:"Service process does not exist"}:{running:!1,pidInfo:null,message:"Service not running"}}function L(e){try{let t=new Date(e),o=new Date;if(isNaN(t.getTime()))return"unknown";let s=Math.floor((o-t)/1e3),i=Math.floor(s/3600),r=Math.floor(s%3600/60),a=s%60;return i>0?`${i} hours ${r} minutes ${a} seconds`:r>0?`${r} minutes ${a} seconds`:`${a} seconds`}catch{return"unknown"}}var Pe=te(import.meta.url),A="1.5.5",d=new ee,w={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m"};function j(e){console.error(`${w.red}ERROR: ${e}${w.reset}`)}function b(e){console.log(`${w.green}${e}${w.reset}`)}function oe(e){console.log(`${w.blue}${e}${w.reset}`)}function y(e){return async(...t)=>{try{let o=await e(...t);o&&o.success===!1?(j(o.message||"Command failed"),process.exitCode=1):process.exitCode=0}catch(o){j(o?.message||"Command failed with unexpected error"),process.exitCode=1}}}async function se(e){let t=await N({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(`Service started (PID: ${t.pid})`),t}async function re(e){let t=await T({force:e.force,timeout:Number(e.timeout)});return t.success&&b(t.message||"Service stopped"),t}async function ne(e){let t=await O({env:e.env,port:e.port,config:e.config,timeout:Number(e.timeout),startTimeout:Number(e.startTimeout)});return t.success&&b(t.message||"Service restarted"),t}function ie(){let e=_();return oe(`${n.name} service status:`),console.log(""),console.log(` Service name: ${n.name}`),console.log(` Running status: ${e.running?"Running":"Stopped"}`),console.log(` Message: ${e.message}`),console.log(` PID file: ${$()}`),e.pidInfo&&(console.log(` Process ID: ${e.pidInfo.pid}`),console.log(` Environment: ${e.pidInfo.env||"Unknown"}`),console.log(` Port: ${e.pidInfo.port||"Unknown"}`),console.log(` Version: ${e.pidInfo.version||A}`),console.log(` Platform: ${e.pidInfo.platform||process.platform}`),console.log(` Started at: ${e.pidInfo.startedAt||"Unknown"}`),console.log(` Uptime: ${L(e.pidInfo.startedAt)}`)),console.log(""),{success:e.running,message:e.message}}function ce(){d.name("nuwax-file-server").description("Cross-platform file service deployment tool, supporting start/stop/restart/status").version(A,"-v, --version","Display version number").helpOption("-h, --help","Display help information"),d.command("start").allowUnknownOption().description("Start service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(se)),d.command("stop").description("Stop service").option("--force","Force stop").option("--timeout <ms>","\u505C\u6B62\u670D\u52A1\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).action(y(re)),d.command("restart").allowUnknownOption().description("Restart service").option("--env <environment>","\u73AF\u5883: development|production|test","production").option("--port <port>","Service port").option("--config <path>","Custom configuration file path").option("--timeout <ms>","\u505C\u6B62\u65E7\u8FDB\u7A0B\u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStopTimeout}`).option("--start-timeout <ms>","\u542F\u52A8\u5065\u5EB7\u68C0\u67E5\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09",`${n.defaultStartTimeout}`).action(y(ne)),d.command("status").description("View service status").action(y(ie)),d.command("help").description("Display help information").action(()=>{d.outputHelp()}),d.parse(process.argv),process.argv.slice(2).length||(d.outputHelp(),process.exitCode=0)}ce();
@@ -1 +1 @@
1
- import v from"express";import z from"multer";import g from"fs";import j from"path";import{ValidationError as P,asyncHandler as c}from"../utils/error/errorHandler.js";import{log as u}from"../utils/log/logUtils.js";import b from"../appConfig/index.js";import{createWorkspace as D,pushSkillsToWorkspace as T,initProjectTemplate as R,installProjectDependencies as M,executeCommand as _,deleteWorkspace as B,zipWorkspace as H,buildAgentPackage as L,cleanupBuildArtifacts as W}from"../utils/computer/computerUtils.js";import{getFileList as J,getFileMeta as K,resolveExistingFile as V,searchFiles as G,updateFiles as Z,uploadFile as X,uploadFiles as Y,generateFile as Q,downloadAllFiles as q,getLatestLogs as ee,importProject as te}from"../utils/computer/computerFileUtils.js";import{resolveServiceContext as p}from"../utils/computer/workspaceContext.js";import{listFsRoots as se,listFsChildren as ae,createFsDirectory as oe,renameFsDirectory as ne}from"../utils/computer/fsBrowserUtils.js";const A=v.Router(),I=z({storage:z.diskStorage({destination:(e,n,s)=>{try{const t=typeof e.headers["x-workspace-type"]=="string"?e.headers["x-workspace-type"].trim().toLowerCase():"",a=typeof e.headers["x-app-id"]=="string"?e.headers["x-app-id"].trim():"";let o;if(t==="userapp"&&a){const r=b.USERAPP_WORKSPACE_DIR;if(!r)return s(new Error("USERAPP_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));o=j.join(r,String(a),".tmp")}else{const r=b.COMPUTER_WORKSPACE_DIR;if(!r)return s(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const i=e.body?.userId||"unknown",l=e.body?.cId||"unknown";o=j.join(r,String(i),String(l),".tmp")}g.existsSync(o)||g.mkdirSync(o,{recursive:!0}),s(null,o)}catch(t){s(t)}},filename:(e,n,s)=>{const t=j.extname(n.originalname)||".zip",a=j.basename(n.originalname,t),o=`${Date.now()}_${Math.round(Math.random()*1e6)}`;s(null,`${a}_${o}${t}`)}}),limits:{fileSize:b.UPLOAD_MAX_FILE_SIZE_BYTES}});function re(e,n,s,t){if(e&&e.name==="MulterError"||e&&(e.name==="ValidationError"||e instanceof P))return t(e);t(e)}const ie=[{path:"/create-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=e.file||null,o=p(e),r=`computer:${s}:${t}`;u(r,"INFO","Create workspace request",{userId:s,cId:t,workspaceType:o.workspaceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await D(s,t,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,o);n.status(200).json({success:!0,...i})})},{path:"/create-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,agentId:a,skillUrls:o,skillUrlMap:r,skillNames:i,updateSkillNames:l,mcpServersConfig:d,hooksConfig:m,permissionsConfig:f,hookScripts:h}=e.body||{},k=e.file||null,C=p(e),O=`computer:${s}:${t}`;let N=o;if(typeof o=="string")try{N=JSON.parse(o)}catch{N=[o]}let w=r;if(typeof r=="string")try{w=JSON.parse(r)}catch{w=null}let F=i;if(typeof i=="string")try{const y=JSON.parse(i);F=Array.isArray(y)?y:[i]}catch{F=i.split(",").map(y=>y.trim()).filter(Boolean)}let S=l;if(typeof l=="string")try{const y=JSON.parse(l);S=Array.isArray(y)?y:[l]}catch{S=l.split(",").map(y=>y.trim()).filter(Boolean)}let $=h;if(typeof h=="string")try{$=JSON.parse(h)}catch{$=null}const x=Array.isArray(N)?N.length:0,E=w&&typeof w=="object"&&!Array.isArray(w)?Object.keys(w).length:0;u(O,"INFO","Create workspace v2 request",{userId:s,cId:t,agentId:a,workspaceType:C.workspaceType,appId:C.appId,hasFile:!!k,fileName:k?.originalname,fileSize:k?.size,skillUrlsCount:x,skillUrlMapCount:E,skillNamesCount:Array.isArray(F)?F.length:0,updateSkillNamesCount:Array.isArray(S)?S.length:0,hasMcpServersConfig:!!d,hasHooksConfig:!!m,hasPermissionsConfig:!!f,hookScriptsCount:Array.isArray($)?$.length:0});const U=await D(s,t,k,N,d,f,m,$,a,F,S,w,C);n.status(200).json({success:!0,...U})})},{path:"/push-skills-to-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=e.file||null,o=p(e),r=`computer:${s}:${t}`;u(r,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:s,cId:t,workspaceType:o.workspaceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await T(s,t,a,void 0,void 0,o);n.status(200).json({success:!0,...i})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,agentId:a,skillUrls:o}=e.body||{},r=e.file||null,i=p(e),l=`computer:${s}:${t}`;let d=o;if(typeof o=="string")try{const f=JSON.parse(o);d=Array.isArray(f)?f:[o]}catch{d=[o]}u(l,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:s,cId:t,agentId:a,workspaceType:i.workspaceType,appId:i.appId,hasFile:!!r,fileName:r?.originalname,fileSize:r?.size,skillUrlsCount:Array.isArray(d)?d.length:0});const m=await T(s,t,r,d,a,i);n.status(200).json({success:!0,...m})})},{path:"/fs/roots",method:"get",handler:c(async(e,n)=>{const s=await se();n.status(200).json({success:!0,...s})})},{path:"/fs/children",method:"get",handler:c(async(e,n)=>{const{path:s}=e.query,t=await ae(s);n.status(200).json({success:!0,...t})})},{path:"/fs/mkdir",method:"post",handler:c(async(e,n)=>{const{parentPath:s,dirName:t}=e.body||{},a=await oe(s,t);n.status(200).json({success:!0,...a})})},{path:"/fs/rename",method:"post",handler:c(async(e,n)=>{const{path:s,newName:t}=e.body||{},a=await ne(s,t);n.status(200).json({success:!0,...a})})},{path:"/get-file-list",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:r,recursive:i,type:l,limit:d}=e.query,m=await J(s,t,a,o,r,i,l,d,p(e));n.status(200).json({success:!0,...m})})},{path:"/resolve-file",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,filePath:r}=e.query,i=await V(s,t,r,a,o,p(e));n.status(200).json({success:!0,...i})})},{path:"/get-file-meta",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,customTargetDir:a,filePaths:o,fileMetaMaxBatch:r}=e.body||{},i=await K(s,t,o,a,p(e),r);n.status(200).json({success:!0,...i})})},{path:"/search-files",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:r,kw:i,limit:l,maxVisit:d,timeoutMs:m}=e.query,f=await G(s,t,a,i,o,r,l,d,m,p(e));n.status(200).json({success:!0,...f})})},{path:"/files-update",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,files:a,customTargetDir:o}=e.body||{},r=`computer:${s}:${t}`;u(r,"INFO","Files update",{userId:s,cId:t,filesCount:a?a.length:0}),a&&Array.isArray(a)&&a.forEach(l=>{if(l&&typeof l.contents=="string"&&l.contents)try{l.contents=decodeURIComponent(l.contents)}catch(d){u(r,"WARN","Decode file content failed",{fileName:l.name,error:d.message})}});const i=await Z(s,t,a,o,p(e));n.status(200).json(i)})},{path:"/upload-file",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,filePath:a,customTargetDir:o}=e.body||{},r=e.file,i=`computer:${s}:${t}`;u(i,"INFO","Upload single file",{userId:s,cId:t,filePath:a});const d={buffer:await g.promises.readFile(r.path),originalname:r.originalname,mimetype:r.mimetype,size:r.size};try{const m=await X(s,t,d,a,o,p(e));n.status(200).json(m)}finally{g.existsSync(r.path)&&await g.promises.unlink(r.path)}})},{path:"/generate-file",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,fileName:a,content:o,customTargetDir:r}=e.body||{},i=`computer:${s}:${t}`;u(i,"INFO","Generate file request",{userId:s,cId:t,fileName:a,contentLength:typeof o=="string"?o.length:0});const l=await Q(s,t,a,o,r,p(e));n.status(200).json(l)})},{path:"/import-project",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,customTargetDir:a}=e.body||{},o=e.file,r=`computer:${s}:${t}`;if(u(r,"INFO","Import project request",{userId:s,cId:t,fileName:o?.originalname,fileSize:o?.size}),!o)throw new P("file is required",{field:"file"});const i=await te(s,t,o,a,p(e));n.status(200).json(i)})},{path:"/upload-files",method:"post",middleware:I.array("files"),handler:c(async(e,n)=>{const{userId:s,cId:t,filePaths:a,customTargetDir:o}=e.body||{},r=e.files||[],i=`computer:${s}:${t}`,l=Array.isArray(a)?a:typeof a=="string"?[a]:a;u(i,"INFO","Batch upload files request",{userId:s,cId:t,filesCount:r.length,filePathsCount:Array.isArray(l)?l.length:0});const d=[],m=[];try{for(const h of r){m.push(h.path);const k=await g.promises.readFile(h.path);d.push({buffer:k,originalname:h.originalname,mimetype:h.mimetype,size:h.size})}const f=await Y(s,t,d,l,o,p(e));n.status(200).json(f)}finally{for(const f of m)if(g.existsSync(f))try{await g.promises.unlink(f)}catch(h){u(i,"WARN","Clean temporary file failed",{tempPath:f,error:h.message})}}})},{path:"/install-project",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,programmingLanguage:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Install project request",{userId:s,cId:t,programmingLanguage:a});const r=await M(s,t,a,p(e));n.status(200).json({success:!0,...r})})},{path:"/init-project-template",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,enableGit:a}=e.body||{},o=e.file||null,r=`computer:${s}:${t}`;u(r,"INFO","Init project template request",{userId:s,cId:t,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size,enableGit:a});const i=await R(s,t,o,a,p(e));n.status(200).json({success:!0,...i})})},{path:"/download-all-files",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,customTargetDir:a}=e.query||{},o=`computer:${s}:${t}`;u(o,"INFO","Download all files request",{userId:s,cId:t});const{archive:r,zipFileName:i}=await q(s,t,a,p(e));n.setHeader("Content-Type","application/zip");const l=encodeURIComponent(i);n.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),r.on("error",d=>{n.destroy(d)}),r.pipe(n),r.finalize()})},{path:"/execute-command",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,command:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Execute command request",{userId:s,cId:t,command:a});const r=await _(s,t,a,p(e));n.status(200).json({success:!0,...r})})},{path:"/delete-workspace",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=`computer:${s}:${t}`;u(a,"INFO","Delete workspace request",{userId:s,cId:t});const o=await B(s,t,p(e));n.status(200).json({success:!0,...o})})},{path:"/get-logs",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,tailLines:a}=e.query,o=a?parseInt(a,10):200,r=Number.isFinite(o)&&o>0?o:200,i=await ee(s,t,r,p(e));n.status(200).json(i)})},{path:"/zip-workspace",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,excludeDirs:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Zip workspace request",{userId:s,cId:t,hasExcludeDirs:!!a});const{archive:r,zipFileName:i}=await H(s,t,a||null,p(e));n.setHeader("Content-Type","application/zip");const l=encodeURIComponent(i);n.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),r.on("error",d=>{n.destroy(d)}),r.pipe(n),r.finalize()})},{path:"/build-agent-package",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,agentId:a,version:o}=e.body||{},r=`computer:${s}:${t}`;u(r,"INFO","Build agent package request",{userId:s,cId:t,agentId:a,version:o});const i=await L(s,t,a,o,p(e));n.status(200).json({success:!0,...i})})},{path:"/cleanup-build-artifacts",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=`computer:${s}:${t}`;u(a,"INFO","Cleanup build artifacts request",{userId:s,cId:t});const o=await W(s,t,p(e));n.status(200).json({success:!0,...o})})}];ie.forEach(e=>{if(e.middleware)A[e.method](e.path,e.middleware,e.handler);else if(e.customHandler){const n=[];e.handler&&n.push(e.handler),e.decodeMiddleware&&n.push(e.decodeMiddleware),n.push(re),n.push(e.customHandler),A[e.method](e.path,...n)}else A[e.method](e.path,e.handler)});export default A;
1
+ import v from"express";import z from"multer";import g from"fs";import j from"path";import{ValidationError as P,asyncHandler as c}from"../utils/error/errorHandler.js";import{log as u}from"../utils/log/logUtils.js";import b from"../appConfig/index.js";import{createWorkspace as D,pushSkillsToWorkspace as T,initProjectTemplate as R,installProjectDependencies as M,executeCommand as _,deleteWorkspace as B,zipWorkspace as H,buildAgentPackage as L,cleanupBuildArtifacts as W}from"../utils/computer/computerUtils.js";import{getFileList as J,getFileMeta as K,resolveExistingFile as V,searchFiles as G,updateFiles as Z,uploadFile as X,uploadFiles as Y,generateFile as Q,downloadAllFiles as q,getLatestLogs as ee,importProject as te}from"../utils/computer/computerFileUtils.js";import{resolveServiceContext as p}from"../utils/computer/workspaceContext.js";import{listFsRoots as se,listFsChildren as ae,createFsDirectory as oe,renameFsDirectory as ne}from"../utils/computer/fsBrowserUtils.js";const A=v.Router(),I=z({storage:z.diskStorage({destination:(e,n,s)=>{try{const t=typeof e.headers["x-workspace-type"]=="string"?e.headers["x-workspace-type"].trim().toLowerCase():"",a=typeof e.headers["x-app-id"]=="string"?e.headers["x-app-id"].trim():"";let o;if(t==="userapp"&&a){const r=b.USERAPP_WORKSPACE_DIR;if(!r)return s(new Error("USERAPP_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));o=j.join(r,String(a),".tmp")}else{const r=b.COMPUTER_WORKSPACE_DIR;if(!r)return s(new Error("COMPUTER_WORKSPACE_DIR is not configured, cannot determine upload temporary directory"));const i=e.body?.userId||"unknown",l=e.body?.cId||"unknown";o=j.join(r,String(i),String(l),".tmp")}g.existsSync(o)||g.mkdirSync(o,{recursive:!0}),s(null,o)}catch(t){s(t)}},filename:(e,n,s)=>{const t=j.extname(n.originalname)||".zip",a=j.basename(n.originalname,t),o=`${Date.now()}_${Math.round(Math.random()*1e6)}`;s(null,`${a}_${o}${t}`)}}),limits:{fileSize:b.UPLOAD_MAX_FILE_SIZE_BYTES}});function re(e,n,s,t){if(e&&e.name==="MulterError"||e&&(e.name==="ValidationError"||e instanceof P))return t(e);t(e)}const ie=[{path:"/create-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=e.file||null,o=p(e),r=`computer:${s}:${t}`;u(r,"INFO","Create workspace request",{userId:s,cId:t,workspaceType:o.workspaceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await D(s,t,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,o);n.status(200).json({success:!0,...i})})},{path:"/create-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,agentId:a,skillUrls:o,skillUrlMap:r,skillNames:i,updateSkillNames:l,mcpServersConfig:d,hooksConfig:f,permissionsConfig:m,hookScripts:h}=e.body||{},k=e.file||null,C=p(e),O=`computer:${s}:${t}`;let N=o;if(typeof o=="string")try{N=JSON.parse(o)}catch{N=[o]}let w=r;if(typeof r=="string")try{w=JSON.parse(r)}catch{w=null}let F=i;if(typeof i=="string")try{const y=JSON.parse(i);F=Array.isArray(y)?y:[i]}catch{F=i.split(",").map(y=>y.trim()).filter(Boolean)}let S=l;if(typeof l=="string")try{const y=JSON.parse(l);S=Array.isArray(y)?y:[l]}catch{S=l.split(",").map(y=>y.trim()).filter(Boolean)}let $=h;if(typeof h=="string")try{$=JSON.parse(h)}catch{$=null}const x=Array.isArray(N)?N.length:0,E=w&&typeof w=="object"&&!Array.isArray(w)?Object.keys(w).length:0;u(O,"INFO","Create workspace v2 request",{userId:s,cId:t,agentId:a,workspaceType:C.workspaceType,appId:C.appId,hasFile:!!k,fileName:k?.originalname,fileSize:k?.size,skillUrlsCount:x,skillUrlMapCount:E,skillNamesCount:Array.isArray(F)?F.length:0,updateSkillNamesCount:Array.isArray(S)?S.length:0,hasMcpServersConfig:!!d,hasHooksConfig:!!f,hasPermissionsConfig:!!m,hookScriptsCount:Array.isArray($)?$.length:0});const U=await D(s,t,k,N,d,m,f,$,a,F,S,w,C);n.status(200).json({success:!0,...U})})},{path:"/push-skills-to-workspace",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=e.file||null,o=p(e),r=`computer:${s}:${t}`;u(r,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42",{userId:s,cId:t,workspaceType:o.workspaceType,appId:o.appId,hasFile:!!a,fileName:a?.originalname,fileSize:a?.size});const i=await T(s,t,a,void 0,void 0,o);n.status(200).json({success:!0,...i})})},{path:"/push-skills-to-workspace-v2",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,agentId:a,skillUrls:o}=e.body||{},r=e.file||null,i=p(e),l=`computer:${s}:${t}`;let d=o;if(typeof o=="string")try{const m=JSON.parse(o);d=Array.isArray(m)?m:[o]}catch{d=[o]}u(l,"INFO","\u63A8\u9001\u6280\u80FD\u5230\u5DE5\u4F5C\u7A7A\u95F4\u8BF7\u6C42(v2)",{userId:s,cId:t,agentId:a,workspaceType:i.workspaceType,appId:i.appId,hasFile:!!r,fileName:r?.originalname,fileSize:r?.size,skillUrlsCount:Array.isArray(d)?d.length:0});const f=await T(s,t,r,d,a,i);n.status(200).json({success:!0,...f})})},{path:"/fs/roots",method:"get",handler:c(async(e,n)=>{const s=await se();n.status(200).json({success:!0,...s})})},{path:"/fs/children",method:"get",handler:c(async(e,n)=>{const{path:s}=e.query,t=await ae(s);n.status(200).json({success:!0,...t})})},{path:"/fs/mkdir",method:"post",handler:c(async(e,n)=>{const{parentPath:s,dirName:t}=e.body||{},a=await oe(s,t);n.status(200).json({success:!0,...a})})},{path:"/fs/rename",method:"post",handler:c(async(e,n)=>{const{path:s,newName:t}=e.body||{},a=await ne(s,t);n.status(200).json({success:!0,...a})})},{path:"/get-file-list",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:r,recursive:i,depth:l,type:d,limit:f}=e.query,m=await J(s,t,a,o,r,i,l,d,f,p(e));n.status(200).json({success:!0,...m})})},{path:"/resolve-file",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,filePath:r}=e.query,i=await V(s,t,r,a,o,p(e));n.status(200).json({success:!0,...i})})},{path:"/get-file-meta",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,customTargetDir:a,filePaths:o,fileMetaMaxBatch:r}=e.body||{},i=await K(s,t,o,a,p(e),r);n.status(200).json({success:!0,...i})})},{path:"/search-files",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,proxyPath:a,customTargetDir:o,relativePath:r,type:i,kw:l,limit:d,maxVisit:f,timeoutMs:m}=e.query,h=await G(s,t,a,l,o,r,i,d,f,m,p(e));n.status(200).json({success:!0,...h})})},{path:"/files-update",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,files:a,customTargetDir:o}=e.body||{},r=`computer:${s}:${t}`;u(r,"INFO","Files update",{userId:s,cId:t,filesCount:a?a.length:0}),a&&Array.isArray(a)&&a.forEach(l=>{if(l&&typeof l.contents=="string"&&l.contents)try{l.contents=decodeURIComponent(l.contents)}catch(d){u(r,"WARN","Decode file content failed",{fileName:l.name,error:d.message})}});const i=await Z(s,t,a,o,p(e));n.status(200).json(i)})},{path:"/upload-file",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,filePath:a,customTargetDir:o}=e.body||{},r=e.file,i=`computer:${s}:${t}`;u(i,"INFO","Upload single file",{userId:s,cId:t,filePath:a});const d={buffer:await g.promises.readFile(r.path),originalname:r.originalname,mimetype:r.mimetype,size:r.size};try{const f=await X(s,t,d,a,o,p(e));n.status(200).json(f)}finally{g.existsSync(r.path)&&await g.promises.unlink(r.path)}})},{path:"/generate-file",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,fileName:a,content:o,customTargetDir:r}=e.body||{},i=`computer:${s}:${t}`;u(i,"INFO","Generate file request",{userId:s,cId:t,fileName:a,contentLength:typeof o=="string"?o.length:0});const l=await Q(s,t,a,o,r,p(e));n.status(200).json(l)})},{path:"/import-project",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,customTargetDir:a}=e.body||{},o=e.file,r=`computer:${s}:${t}`;if(u(r,"INFO","Import project request",{userId:s,cId:t,fileName:o?.originalname,fileSize:o?.size}),!o)throw new P("file is required",{field:"file"});const i=await te(s,t,o,a,p(e));n.status(200).json(i)})},{path:"/upload-files",method:"post",middleware:I.array("files"),handler:c(async(e,n)=>{const{userId:s,cId:t,filePaths:a,customTargetDir:o}=e.body||{},r=e.files||[],i=`computer:${s}:${t}`,l=Array.isArray(a)?a:typeof a=="string"?[a]:a;u(i,"INFO","Batch upload files request",{userId:s,cId:t,filesCount:r.length,filePathsCount:Array.isArray(l)?l.length:0});const d=[],f=[];try{for(const h of r){f.push(h.path);const k=await g.promises.readFile(h.path);d.push({buffer:k,originalname:h.originalname,mimetype:h.mimetype,size:h.size})}const m=await Y(s,t,d,l,o,p(e));n.status(200).json(m)}finally{for(const m of f)if(g.existsSync(m))try{await g.promises.unlink(m)}catch(h){u(i,"WARN","Clean temporary file failed",{tempPath:m,error:h.message})}}})},{path:"/install-project",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,programmingLanguage:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Install project request",{userId:s,cId:t,programmingLanguage:a});const r=await M(s,t,a,p(e));n.status(200).json({success:!0,...r})})},{path:"/init-project-template",method:"post",middleware:I.single("file"),handler:c(async(e,n)=>{const{userId:s,cId:t,enableGit:a}=e.body||{},o=e.file||null,r=`computer:${s}:${t}`;u(r,"INFO","Init project template request",{userId:s,cId:t,hasFile:!!o,fileName:o?.originalname,fileSize:o?.size,enableGit:a});const i=await R(s,t,o,a,p(e));n.status(200).json({success:!0,...i})})},{path:"/download-all-files",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,customTargetDir:a}=e.query||{},o=`computer:${s}:${t}`;u(o,"INFO","Download all files request",{userId:s,cId:t});const{archive:r,zipFileName:i}=await q(s,t,a,p(e));n.setHeader("Content-Type","application/zip");const l=encodeURIComponent(i);n.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),r.on("error",d=>{n.destroy(d)}),r.pipe(n),r.finalize()})},{path:"/execute-command",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,command:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Execute command request",{userId:s,cId:t,command:a});const r=await _(s,t,a,p(e));n.status(200).json({success:!0,...r})})},{path:"/delete-workspace",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=`computer:${s}:${t}`;u(a,"INFO","Delete workspace request",{userId:s,cId:t});const o=await B(s,t,p(e));n.status(200).json({success:!0,...o})})},{path:"/get-logs",method:"get",handler:c(async(e,n)=>{const{userId:s,cId:t,tailLines:a}=e.query,o=a?parseInt(a,10):200,r=Number.isFinite(o)&&o>0?o:200,i=await ee(s,t,r,p(e));n.status(200).json(i)})},{path:"/zip-workspace",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,excludeDirs:a}=e.body||{},o=`computer:${s}:${t}`;u(o,"INFO","Zip workspace request",{userId:s,cId:t,hasExcludeDirs:!!a});const{archive:r,zipFileName:i}=await H(s,t,a||null,p(e));n.setHeader("Content-Type","application/zip");const l=encodeURIComponent(i);n.setHeader("Content-Disposition",`attachment; filename="${l}"; filename*=UTF-8''${l}`),r.on("error",d=>{n.destroy(d)}),r.pipe(n),r.finalize()})},{path:"/build-agent-package",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t,agentId:a,version:o}=e.body||{},r=`computer:${s}:${t}`;u(r,"INFO","Build agent package request",{userId:s,cId:t,agentId:a,version:o});const i=await L(s,t,a,o,p(e));n.status(200).json({success:!0,...i})})},{path:"/cleanup-build-artifacts",method:"post",handler:c(async(e,n)=>{const{userId:s,cId:t}=e.body||{},a=`computer:${s}:${t}`;u(a,"INFO","Cleanup build artifacts request",{userId:s,cId:t});const o=await W(s,t,p(e));n.status(200).json({success:!0,...o})})}];ie.forEach(e=>{if(e.middleware)A[e.method](e.path,e.middleware,e.handler);else if(e.customHandler){const n=[];e.handler&&n.push(e.handler),e.decodeMiddleware&&n.push(e.decodeMiddleware),n.push(re),n.push(e.customHandler),A[e.method](e.path,...n)}else A[e.method](e.path,e.handler)});export default A;
package/dist/server.js CHANGED
@@ -1 +1 @@
1
- import A from"express";import"json-bigint";import C from"swagger-ui-express";import R from"./config/swagger.js";import a from"./appConfig/index.js";import{log as c,logger as S}from"./utils/log/logUtils.js";import w from"./utils/log/logCacheManager.js";import{errorHandler as P,notFoundHandler as y}from"./utils/error/errorHandler.js";import N from"./routes/router.js";import{cleanupInitProjectOnStartup as D}from"./utils/project/initProjectCleanupUtils.js";import{resolveServiceContext as H,resolveWorkspaceDir as F}from"./utils/computer/workspaceContext.js";import{startScheduler as v,stopScheduler as x}from"./scheduler/pnpmPruneScheduler.js";import f from"path";const o=A();o.use(A.json({limit:a.REQUEST_BODY_LIMIT,reviver:(t,e)=>typeof e=="number"&&!Number.isSafeInteger(e)?e.toString():e})),o.use(A.urlencoded({extended:!0,limit:a.REQUEST_BODY_LIMIT})),o.use(S);const T=t=>{let e=t;try{for(;;){const n=decodeURIComponent(e);if(n===e)break;e=n}}catch{}return e};o.use("/api/page/static/:projectId",(t,e,n)=>{const{projectId:d}=t.params;let s=t.path||"/";if(!d||s==="/")return e.status(404).send("Not Found");const r=t.headers.origin,l=r||"*";if(e.header("Access-Control-Allow-Origin",l),e.header("Access-Control-Allow-Methods","HEAD,GET,POST,PUT,DELETE,OPTIONS"),e.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Fragment"),e.header("Access-Control-Expose-Headers","Content-Type"),r&&(e.header("Access-Control-Allow-Credentials","true"),e.header("Vary","Origin")),t.method==="OPTIONS")return e.sendStatus(200);s=s.replace(/^\/+/,"");const p=T(s),g=f.join(a.PROJECT_SOURCE_DIR,d,p),i={"Access-Control-Allow-Origin":l,"Access-Control-Allow-Methods":"HEAD,GET,POST,PUT,DELETE,OPTIONS","Access-Control-Allow-Headers":"Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Fragment"};return r&&(i["Access-Control-Allow-Credentials"]="true",i.Vary="Origin"),e.sendFile(g,{dotfiles:"allow",headers:i},h=>{if(h)return n()})}),o.use("/api/computer/static/:userId/:cId",(t,e,n)=>{const{userId:d,cId:s}=t.params;let r=t.path||"/";if(!d||!s||r==="/")return e.status(404).send("Not Found");const l=t.headers.origin,p=l||"*";if(e.header("Access-Control-Allow-Origin",p),e.header("Access-Control-Allow-Methods","HEAD,GET,POST,PUT,DELETE,OPTIONS"),e.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Range, If-Range"),e.header("Access-Control-Expose-Headers","Content-Type, Content-Length, Content-Range, Accept-Ranges, ETag, Last-Modified"),l&&(e.header("Access-Control-Allow-Credentials","true"),e.header("Vary","Origin")),t.method==="OPTIONS")return e.sendStatus(200);r=r.replace(/^\/+/,"");const g=T(r),{customTargetDir:i}=t.query,h=H(t),E=i&&i.trim()?f.join(i,g):f.join(F(h,d,s),g),m={"Access-Control-Allow-Origin":p,"Access-Control-Allow-Methods":"HEAD,GET,POST,PUT,DELETE,OPTIONS","Access-Control-Allow-Headers":"Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Range, If-Range","Access-Control-Expose-Headers":"Content-Type, Content-Length, Content-Range, Accept-Ranges, ETag, Last-Modified"};return l&&(m["Access-Control-Allow-Credentials"]="true",m.Vary="Origin"),e.sendFile(E,{dotfiles:"allow",headers:m},I=>{if(I)return n()})}),o.use("/api-docs",C.serve,C.setup(R,{customCss:".swagger-ui .topbar { display: none }",customSiteTitle:"nuwax-file-server API Documentation"})),o.use(N),o.use(y),o.use(P);const u=o.listen(a.PORT,async()=>{c("default","INFO",`Server is running on port ${a.PORT} (${a.NODE_ENV} mode)`),await D(a);try{v()}catch(t){c("default","ERROR",`pnpm prune scheduled task failed to start: ${t.message}`)}});u.timeout=6e5,u.keepAliveTimeout=61e4,u.headersTimeout=62e4,u.requestTimeout=63e4;const O=t=>{c("default","INFO",`Received ${t} signal, preparing graceful exit...`),x();try{w.destroy(),c("default","INFO","Log cache manager cleared")}catch(e){c("default","ERROR",`Failed to clear log cache manager: ${e.message}`)}u.close(()=>{c("default","INFO","Server closed"),process.exit(0)}),setTimeout(()=>{c("default","ERROR","Force exit (timeout)"),process.exit(1)},3e4)};process.on("SIGTERM",()=>O("SIGTERM")),process.on("SIGINT",()=>O("SIGINT"));
1
+ import f from"express";import"json-bigint";import T from"swagger-ui-express";import R from"./config/swagger.js";import a from"./appConfig/index.js";import{log as c,logger as w}from"./utils/log/logUtils.js";import P from"./utils/log/logCacheManager.js";import{errorHandler as y,notFoundHandler as F}from"./utils/error/errorHandler.js";import N from"./routes/router.js";import{cleanupInitProjectOnStartup as H}from"./utils/project/initProjectCleanupUtils.js";import{resolveServiceContext as D,resolveWorkspaceDir as v}from"./utils/computer/workspaceContext.js";import{startScheduler as x,stopScheduler as L}from"./scheduler/pnpmPruneScheduler.js";import A from"path";import M from"fs/promises";const r=f();r.use(f.json({limit:a.REQUEST_BODY_LIMIT,reviver:(t,e)=>typeof e=="number"&&!Number.isSafeInteger(e)?e.toString():e})),r.use(f.urlencoded({extended:!0,limit:a.REQUEST_BODY_LIMIT})),r.use(w);const O=t=>{let e=t;try{for(;;){const o=decodeURIComponent(e);if(o===e)break;e=o}}catch{}return e},E=async(t,e)=>{try{const o=await M.stat(e);o.isFile()&&t.setHeader("X-File-Size",o.size)}catch{}};r.use("/api/page/static/:projectId",async(t,e,o)=>{const{projectId:d}=t.params;let s=t.path||"/";if(!d||s==="/")return e.status(404).send("Not Found");const n=t.headers.origin,l=n||"*";if(e.header("Access-Control-Allow-Origin",l),e.header("Access-Control-Allow-Methods","HEAD,GET,POST,PUT,DELETE,OPTIONS"),e.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Fragment"),e.header("Access-Control-Expose-Headers","Content-Type, X-File-Size"),n&&(e.header("Access-Control-Allow-Credentials","true"),e.header("Vary","Origin")),t.method==="OPTIONS")return e.sendStatus(200);s=s.replace(/^\/+/,"");const g=O(s),u=A.join(a.PROJECT_SOURCE_DIR,d,g);await E(e,u);const i={"Access-Control-Allow-Origin":l,"Access-Control-Allow-Methods":"HEAD,GET,POST,PUT,DELETE,OPTIONS","Access-Control-Allow-Headers":"Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Fragment"};return n&&(i["Access-Control-Allow-Credentials"]="true",i.Vary="Origin"),e.sendFile(u,{dotfiles:"allow",headers:i},h=>{if(h)return o()})}),r.use("/api/computer/static/:userId/:cId",async(t,e,o)=>{const{userId:d,cId:s}=t.params;let n=t.path||"/";if(!d||!s||n==="/")return e.status(404).send("Not Found");const l=t.headers.origin,g=l||"*";if(e.header("Access-Control-Allow-Origin",g),e.header("Access-Control-Allow-Methods","HEAD,GET,POST,PUT,DELETE,OPTIONS"),e.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Range, If-Range"),e.header("Access-Control-Expose-Headers","Content-Type, Content-Length, Content-Range, Accept-Ranges, ETag, Last-Modified, X-File-Size"),l&&(e.header("Access-Control-Allow-Credentials","true"),e.header("Vary","Origin")),t.method==="OPTIONS")return e.sendStatus(200);n=n.replace(/^\/+/,"");const u=O(n),{customTargetDir:i}=t.query,h=D(t),C=i&&i.trim()?A.join(i,u):A.join(v(h,d,s),u);await E(e,C);const m={"Access-Control-Allow-Origin":g,"Access-Control-Allow-Methods":"HEAD,GET,POST,PUT,DELETE,OPTIONS","Access-Control-Allow-Headers":"Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Range, If-Range","Access-Control-Expose-Headers":"Content-Type, Content-Length, Content-Range, Accept-Ranges, ETag, Last-Modified, X-File-Size"};return l&&(m["Access-Control-Allow-Credentials"]="true",m.Vary="Origin"),e.sendFile(C,{dotfiles:"allow",headers:m},I=>{if(I)return o()})}),r.use("/api-docs",T.serve,T.setup(R,{customCss:".swagger-ui .topbar { display: none }",customSiteTitle:"nuwax-file-server API Documentation"})),r.use(N),r.use(F),r.use(y);const p=r.listen(a.PORT,async()=>{c("default","INFO",`Server is running on port ${a.PORT} (${a.NODE_ENV} mode)`),await H(a);try{x()}catch(t){c("default","ERROR",`pnpm prune scheduled task failed to start: ${t.message}`)}});p.timeout=6e5,p.keepAliveTimeout=61e4,p.headersTimeout=62e4,p.requestTimeout=63e4;const S=t=>{c("default","INFO",`Received ${t} signal, preparing graceful exit...`),L();try{P.destroy(),c("default","INFO","Log cache manager cleared")}catch(e){c("default","ERROR",`Failed to clear log cache manager: ${e.message}`)}p.close(()=>{c("default","INFO","Server closed"),process.exit(0)}),setTimeout(()=>{c("default","ERROR","Force exit (timeout)"),process.exit(1)},3e4)};process.on("SIGTERM",()=>S("SIGTERM")),process.on("SIGINT",()=>S("SIGINT"));
@@ -1,2 +1,2 @@
1
- import l from"fs";import w from"path";import oe from"archiver";import{lookup as Fe}from"mime-types";import v from"../../appConfig/index.js";import{log as u}from"../log/logUtils.js";import{ValidationError as E,SystemError as z,FileError as Ie}from"../error/errorHandler.js";import{extractZip as Se}from"../common/zipUtils.js";import{moveDirectory as De,movePath as te}from"../common/fileSystemUtils.js";import{resolveLogDir as ke,resolveWorkspaceDir as A,resolveWorkspaceRoot as ae}from"./workspaceContext.js";const j=new Set([".git",".agents",".claude",".codex",".opencode",".tmp",".logs"]),xe=100*1024*1024,V=v.DOWNLOAD_MAX_FILE_SIZE_BYTES||xe;function G(e){return w.sep==="\\"?e.replace(/\\/g,"/"):e}function le(e,i){return G(w.relative(e,i))}function ce(e,i){return e?`${e}/${i}`:i}function re(e){return e!=null&&e.limit!=null&&e.pushed>=e.limit}function q(e){e!=null&&(e.pushed+=1)}async function be(e,i,t,n,a,s={}){const{typeFilter:o=null,limitState:m=null}=s,c=[],y=await l.promises.readdir(e,{withFileTypes:!0});y.sort((r,f)=>r.isDirectory()&&!f.isDirectory()?-1:!r.isDirectory()&&f.isDirectory()?1:r.name.toLowerCase().localeCompare(f.name.toLowerCase()));const h=le(i,e);for(const r of y){if(re(m))break;if(r.name.startsWith(".")&&r.name!==".gitignore"||(v.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(r.name)||r.isDirectory()&&v.TRAVERSE_EXCLUDE_DIRS.includes(r.name))continue;const g=ce(h,r.name);if(r.isDirectory()){if(o==="file")continue;c.push({name:g,isDir:!0}),q(m);continue}if(o!=="dir")try{c.push({name:g,isDir:!1,fileProxyUrl:Z(n,g,a),isLink:r.isSymbolicLink()}),q(m)}catch(d){u(t,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${e}/${r.name}`,{error:d.message})}}return c}async function ue(e,i,t,n,a="",s={}){const{typeFilter:o=null,limitState:m=null}=s,c=[];let y=0;const h=await l.promises.readdir(e,{withFileTypes:!0});h.sort((r,f)=>r.isDirectory()&&!f.isDirectory()?-1:!r.isDirectory()&&f.isDirectory()?1:r.name.toLowerCase().localeCompare(f.name.toLowerCase()));for(const r of h){if(re(m))break;const f=w.join(e,r.name);if(r.name.startsWith(".")&&r.name!==".gitignore"||(v.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(r.name)||r.isDirectory()&&v.TRAVERSE_EXCLUDE_DIRS.includes(r.name))continue;const d=ce(a,r.name);if(y+=1,r.isDirectory()){const p=await ue(f,i,t,n,d,s);p.naturalCount===0?o!=="file"&&!re(m)&&(c.push({name:d,isDir:!0}),q(m)):c.push(...p.entries)}else{if(o==="dir")continue;try{c.push({name:d,isDir:!1,fileProxyUrl:Z(t,d,n),isLink:r.isSymbolicLink()}),q(m)}catch(p){u(i,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${f}`,{error:p.message})}}}return{entries:c,naturalCount:y}}function me(e,i){const t=(i==null?"":String(i)).trim();if(!t||t==="."||t==="/")return w.resolve(e);const n=w.normalize(t).replace(/^[\/\\]+/,"");if(!n||n===".")return w.resolve(e);if(w.isAbsolute(t)||n.split(w.sep).includes(".."))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:i});const a=w.resolve(e),s=w.resolve(e,n);if(s!==a&&!s.startsWith(a+w.sep))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:i});return s}function H(e,i){const t=(i==null?"":String(i)).trim();if(!t)return null;const n=w.resolve(e);let a;if(w.isAbsolute(t))a=w.resolve(t);else{const o=w.normalize(t).replace(/^[\/\\]+/,"");if(!o||o==="."||o.split(w.sep).includes(".."))return null;a=w.resolve(e,o)}if(a!==n&&!a.startsWith(n+w.sep))return null;const s=G(w.relative(n,a));return!s||s.startsWith("..")?null:{absPath:a,name:s}}function Z(e,i,t){if(!e||!i)return null;const n=i.split("/").map(s=>encodeURIComponent(s)).join("/");let a=`${e}/${n}`;return t&&(a+=`?customTargetDir=${encodeURIComponent(t)}`),a}async function ve(e,i,t,n,a,s=null){if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!i)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});if(!t||!String(t).trim())throw new E("filePath \u4E0D\u80FD\u4E3A\u7A7A",{field:"filePath"});const o=String(e),m=String(i),c=a&&a.trim()?a.trim():null,y=c||A(s,o,m);if(!l.existsSync(y))return{exists:!1};let h=H(y,t);if(!h){const r=String(t).trim().replace(/^[\/\\]+/,"");r&&r!==String(t).trim()&&(h=H(y,r))}if(!h)return{exists:!1};try{if(!(await l.promises.stat(h.absPath)).isFile())return{exists:!1}}catch{return{exists:!1}}return{exists:!0,name:h.name,fileProxyUrl:Z(n,h.name,c)}}const Ne=100,Ce=1e3,Pe=8,fe=1e3;function Le(e){return w.extname(e).replace(/^\./,"").toLowerCase()||""}async function _e(e,i,t){const n=new Array(e.length),a=Math.max(1,Math.min(i,e.length));let s=0;return await Promise.all(Array.from({length:a},async()=>{for(;;){const o=s++;if(o>=e.length)return;n[o]=await t(e[o],o)}})),n}function ze(e){return!(e.startsWith(".")&&e!==".gitignore"||(v.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(e)||v.TRAVERSE_EXCLUDE_DIRS.includes(e))}async function Ae(e){const i=await l.promises.opendir(e);let t=0;for await(const n of i)if(ze(n.name)&&(t+=1,t>=fe))return fe;return t}function de(e,i){return{path:e,isDir:null,isLink:null,size:null,mtimeMs:null,extension:null,mimeType:null,linkTarget:null,childCount:null,...i?{error:i}:{}}}async function Te(e,i,t){const n=(i==null?"":String(i)).trim();let a=n?H(e,n):null;if(!a&&n.startsWith("/")){const s=n.replace(/^[\/\\]+/,"");s&&s!==n&&(a=H(e,s))}if(!a)return de(n,"illegal path");try{const s=await l.promises.lstat(a.absPath),o=s.isDirectory(),m=s.isSymbolicLink(),c={path:n,isDir:o,isLink:m,size:o?null:s.size,mtimeMs:s.mtimeMs,extension:o?null:Le(n),mimeType:o?null:Fe(n)||"application/octet-stream",linkTarget:null,childCount:null};if(m)try{c.linkTarget=await l.promises.readlink(a.absPath)}catch(y){u(t,"WARN","Readlink failed, linkTarget set to null",{filePath:n,error:y.message})}if(o)try{c.childCount=await Ae(a.absPath)}catch(y){u(t,"WARN","Count directory entries failed, childCount set to null",{filePath:n,error:y.message})}return c}catch(s){return de(n,s.code||s.message)}}async function Oe(e,i,t,n,a=null,s=null){const o=Date.now(),m=`computer:${e}:${i}`;if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!i)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});if(!Array.isArray(t)||t.length===0)throw new E("filePaths \u5FC5\u987B\u4E3A\u975E\u7A7A\u6570\u7EC4",{field:"filePaths"});const c=Number.parseInt(s,10),y=Number.isFinite(c)&&c>0?Math.min(c,Ce):Ne;if(t.length>y)throw new E(`filePaths \u5355\u6B21\u6700\u591A ${y} \u6761`,{field:"filePaths",count:t.length});const h=String(e),r=String(i),g=(n==null?"":String(n).trim())||null,d=g||A(a,h,r);if(!l.existsSync(d))return u(m,"INFO","Target directory does not exist, returning empty metas",{targetDir:d,userId:h,cId:r}),{metas:[]};const p=await _e(t,Pe,R=>Te(d,R,m));return u(m,"INFO","File metadata queried",{targetDir:d,count:p.length,failed:p.filter(R=>R.error).length,customTargetDir:g,userId:h,cId:r,elapsedMs:Date.now()-o}),{metas:p}}async function pe(e,i,t,n,a=""){const s=await l.promises.readdir(w.join(e,a),{withFileTypes:!0});let o=0;for(const m of s){const c=a?w.join(a,m.name):m.name,y=c.split(w.sep).filter(Boolean);if(y.some(g=>g.startsWith(".")))continue;const h=y[y.length-1];if(i.includes(h)||y.some(g=>t.includes(g)))continue;const r=w.join(e,c);let f;try{f=await l.promises.lstat(r)}catch(g){u(n,"WARN","Error occurred when getting file stats, skipping",{filePath:c.replace(/\\/g,"/"),error:g.message});continue}f.isSymbolicLink()||f.nlink>1||(f.isDirectory()?o+=await pe(e,i,t,n,c):f.isFile()&&(o+=f.size))}return o}async function $e(e,i,t,n,a,s,o,m,c=null){const y=Date.now(),h=`computer:${e}:${i}`,r=!(s===!1||s==="false");if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!i)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const f=o==null?"":String(o).trim().toLowerCase();let g=null;if(f&&f!=="all")if(f==="file")g="file";else if(f==="dir"||f==="directory")g="dir";else throw new E("type \u4EC5\u652F\u6301 file/dir/all",{field:"type",value:o});let d=null;if(m!=null&&m!==""){const I=Number(m);if(!Number.isInteger(I)||I<0)throw new E("limit \u5FC5\u987B\u4E3A\u975E\u8D1F\u6574\u6570",{field:"limit",value:m});d=I}const p=String(e),R=String(i),D=n&&n.trim()?n.trim():null,F=D||A(c,p,R);if(!l.existsSync(F))return u(h,"INFO","Directory does not exist, returning empty list",{targetDir:F,userId:p,cId:R}),{files:[],recursive:r,type:g||"all",limit:d};const S=me(F,a);if(!l.existsSync(S))return u(h,"INFO","List path does not exist, returning empty list",{targetDir:F,listDir:S,relativePath:a||"",userId:p,cId:R}),{files:[],recursive:r,type:g||"all",limit:d};if(!(await l.promises.stat(S)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:a});u(h,"DEBUG","Start getting user file list",{targetDir:F,listDir:S,relativePath:a||"",recursive:r,userId:p,cId:R});try{const I={typeFilter:g,limitState:{limit:d,pushed:0}},b=r?(await ue(S,h,t,D,le(F,S),I)).entries:await be(S,F,h,t,D,I);return u(h,"INFO","User file list obtained successfully",{fileCount:b.length,targetDir:F,listDir:S,relativePath:a||"",recursive:r,type:g||"all",limit:d,userId:p,cId:R,elapsedMs:Date.now()-y}),{files:b,recursive:r,type:g||"all",limit:d}}catch(I){throw I instanceof E?I:(u(h,"ERROR","Failed to get user file list",{targetDir:F,listDir:S,relativePath:a||"",recursive:r,userId:p,cId:R,error:I.message,elapsedMs:Date.now()-y}),new z(`Failed to get file list: ${I.message}`,{targetDir:F,originalError:I.message}))}}const Me=5e3;function ie(e,i){const t=Number.parseInt(e,10);if(!Number.isFinite(t)||t<=0)throw new E(`${i} \u5FC5\u987B\u4E3A\u6B63\u6574\u6570`,{field:i,value:e});return t}function he(e,i,t){return t?i.toLowerCase().includes(t)?!0:e.toLowerCase().includes(t):!1}function we(e,i,t){return!!(e.name.startsWith(".")&&e.name!==".gitignore"||i.includes(e.name)||e.isDirectory()&&t.includes(e.name))}function ge(e,i,t,n){for(let a=i;a<e.length;a++)if(!we(e[a],t,n))return!0;return!1}function ye(e,i){return Date.now()-e>=i}async function We(e,i,t,n,a,s,o,m,c,y=null){const h=Date.now(),r=`computer:${e}:${i}`;if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!i)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const f=(n==null?"":String(n)).trim();if(!f)throw new E("kw \u4E0D\u80FD\u4E3A\u7A7A",{field:"kw"});const g=ie(o,"limit"),d=ie(m,"maxVisit"),p=ie(c,"timeoutMs"),R=f.toLowerCase(),D=String(e),F=String(i),S=a&&a.trim()?a.trim():null,k=S||A(y,D,F);if(!l.existsSync(k))return{files:[],truncated:!1,visited:0};const I=me(k,s);if(!l.existsSync(I))return{files:[],truncated:!1,visited:0};if(!(await l.promises.stat(I)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:s});const T=G(w.relative(k,I)),K=v.CONTENT_TRAVERSE_EXCLUDE_FILES||[],Y=v.TRAVERSE_EXCLUDE_DIRS||[],N=[],J=new Set;let O=0,Q=!1,L=!1;const _=[T],W=()=>O>=d||ye(h,p);for(;_.length>0;){if(W()){L=!0;break}if(N.length>=g){_.length>0&&(L=!0);break}const P=_.shift();if(J.has(P))continue;J.add(P);const U=P?w.join(k,P):k;let $;try{$=await l.promises.readdir(U,{withFileTypes:!0})}catch(x){u(r,"WARN","search readdir failed",{dirRel:P,error:x.message});continue}$.sort((x,C)=>x.isDirectory()&&!C.isDirectory()?-1:!x.isDirectory()&&C.isDirectory()?1:x.name.toLowerCase().localeCompare(C.name.toLowerCase()));const ee=[];let B=!1,X=!1;for(let x=0;x<$.length;x++){const C=$[x];if(we(C,K,Y))continue;if(W()){L=!0,B=!0,X=!0;break}O+=1;const se=w.join(U,C.name),M=G(w.relative(k,se));if(C.isDirectory()){if(ee.push(M),N.length<g&&he(M,C.name,R)&&(N.push({name:M,isDir:!0}),N.length>=g)){B=!0,X=ge($,x+1,K,Y);break}continue}try{if(N.length<g&&he(M,C.name,R)&&(N.push({name:M,isDir:!1,fileProxyUrl:Z(t,M,S),isLink:C.isSymbolicLink()}),N.length>=g)){B=!0,X=ge($,x+1,K,Y);break}}catch(Re){u(r,"WARN",`search \u5904\u7406\u6587\u4EF6\u5931\u8D25: ${se}`,{error:Re.message})}}if(B||W()){(W()||X||ee.length>0||_.length>0)&&(L=!0);continue}for(const x of ee){if(W()){L=!0;break}if(_.length>=Me){L=!0;break}if(O+_.length>=d){L=!0;break}J.has(x)||_.push(x)}}return N.sort((P,U)=>P.isDir!==U.isDir?P.isDir?-1:1:String(P.name).localeCompare(String(U.name))),Q=L||_.length>0||O>=d||ye(h,p),u(r,"INFO","File search completed",{kw:f,matchCount:N.length,visited:O,truncated:Q,relativePath:s||"",elapsedMs:Date.now()-h}),{files:N,truncated:Q,visited:O}}async function Ue(e,i,t,n,a=null){const s=Date.now(),o=`computer:${e}:${i}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(t))throw new E("files must be an array",{field:"files"});const m=String(e),c=String(i),y=n&&n.trim()?n.trim():null,h=y||A(a,m,c);l.existsSync(h)||l.mkdirSync(h,{recursive:!0});for(let r=0;r<t.length;r++){const f=t[r];if(!f||typeof f.operation!="string")throw new E(`files[${r}].operation cannot be empty`,{field:`files[${r}].operation`});if(!f.name||typeof f.name!="string")throw new E(`files[${r}].name cannot be empty`,{field:`files[${r}].name`});const g=f.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(g))throw new E(`files[${r}].operation must be one of create, delete, rename or modify`,{field:`files[${r}].operation`});if(g==="rename"&&!f.renameFrom)throw new E(`files[${r}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${r}].renameFrom`});if(g==="modify"&&f.isDir!==!0&&typeof f.contents!="string")throw new E(`files[${r}].contents must be a string (modify operation requires)`,{field:`files[${r}].contents`})}u(o,"DEBUG","Start updating user files",{userId:m,cId:c,filesCount:t.length});try{for(const r of t){const f=r.operation.toLowerCase(),g=r.name,d=w.normalize(g).replace(/^[\/\\]+/,""),p=w.join(h,d),R=w.resolve(p),D=w.resolve(h);if(!R.startsWith(D+w.sep)&&R!==D){u(o,"WARN","File path is not secure, skipping",{filePath:d,resolvedPath:R});continue}switch(f){case"create":{if(r.isDir===!0){if(l.existsSync(p)){if((await l.promises.stat(p)).isFile())throw new E("Cannot create directory, file with the same name already exists",{filePath:d});u(o,"INFO","Directory already exists, skipping creation",{filePath:d});break}await l.promises.mkdir(p,{recursive:!0}),u(o,"INFO","Directory created successfully",{filePath:d});break}if(l.existsSync(p)){if((await l.promises.stat(p)).isDirectory())throw new E("Cannot create file, directory with the same name already exists",{filePath:d});u(o,"INFO","File already exists, skipping creation",{filePath:d});break}await l.promises.mkdir(w.dirname(p),{recursive:!0});const F=r.contents||"";await l.promises.writeFile(p,F,"utf8"),u(o,"INFO","File created successfully",{filePath:d});break}case"delete":{l.existsSync(p)?(await l.promises.stat(p)).isDirectory()?(await l.promises.rm(p,{recursive:!0,force:!0}),u(o,"INFO","Directory deleted successfully",{filePath:d})):(await l.promises.unlink(p),u(o,"INFO","File deleted successfully",{filePath:d})):u(o,"WARN","The file or directory to be deleted does not exist",{filePath:d});break}case"rename":{const F=r.renameFrom;if(!F||typeof F!="string"){u(o,"WARN","Rename operation missing renameFrom",{filePath:d});break}const S=w.normalize(F).replace(/^[\/\\]+/,""),k=w.join(h,S),I=w.resolve(k);if(!I.startsWith(D+w.sep)&&I!==D){u(o,"WARN","Source path is not secure, skipping rename",{sourcePath:S,targetPath:d});break}if(l.existsSync(k)){const T=(await l.promises.stat(k)).isDirectory();await l.promises.mkdir(w.dirname(p),{recursive:!0}),await l.promises.rename(k,p),u(o,"INFO",T?"Directory renamed successfully":"File renamed successfully",{sourcePath:S,targetPath:d})}else u(o,"WARN","The file or directory to be renamed does not exist",{sourcePath:S});break}case"modify":{if(!l.existsSync(p)){u(o,"WARN","The file to be modified does not exist",{filePath:d});break}if((await l.promises.stat(p)).isDirectory()){u(o,"INFO","The target is a directory, skipping modification",{filePath:d});break}const S=typeof r.contents=="string"?r.contents:"";if(await l.promises.readFile(p,"utf8")===S){u(o,"INFO","File content has no changes, skipping write",{filePath:d});break}await l.promises.writeFile(p,S,"utf8"),u(o,"INFO","File modified successfully",{filePath:d});break}default:{u(o,"WARN","Unsupported operation type",{operation:f,filePath:d});break}}}return u(o,"INFO","User files updated successfully",{userId:m,cId:c,filesCount:t.length,elapsedMs:Date.now()-s}),{success:!0,message:"User files updated successfully",userId:m,cId:c,filesCount:t.length}}catch(r){throw u(o,"ERROR","User files updated failed",{userId:m,cId:c,error:r.message,elapsedMs:Date.now()-s}),new z(`User files updated failed: ${r.message}`,{userId:m,cId:c,originalError:r.message})}}async function ne(e,i,t,n,a,s=null){const o=Date.now(),m=`computer:${e}:${i}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!t)throw new E("file cannot be empty",{field:"file"});if(!n||typeof n!="string")throw new E("filePath cannot be empty",{field:"filePath"});const c=String(e),y=String(i),h=a&&a.trim()?a.trim():null,r=h||A(s,c,y);l.existsSync(r)||l.mkdirSync(r,{recursive:!0});const f=w.normalize(n).replace(/^[\/\\]+/,""),g=w.join(r,f),d=w.resolve(g),p=w.resolve(r);if(!d.startsWith(p+w.sep)&&d!==p)throw new E("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:n,resolvedPath:d});try{if(await l.promises.mkdir(w.dirname(g),{recursive:!0}),t.buffer)await l.promises.writeFile(g,t.buffer);else if(typeof t.contents=="string")await l.promises.writeFile(g,t.contents,"utf8");else throw new E("File content format is incorrect",{field:"file",hasBuffer:!!t.buffer,hasContents:typeof t.contents});return u(m,"INFO","File uploaded successfully",{userId:c,cId:y,filePath:f,targetPath:d,fileSize:t.buffer?t.buffer.length:t.contents?t.contents.length:0,elapsedMs:Date.now()-o}),{success:!0,message:"File uploaded successfully",fileSize:t.buffer?t.buffer.length:t.contents?t.contents.length:0}}catch(R){throw u(m,"ERROR","File upload failed",{userId:c,cId:y,filePath:f,error:R.message,elapsedMs:Date.now()-o}),new z(`File upload failed: ${R.message}`,{userId:c,cId:y,filePath:f,originalError:R.message})}}async function je(e,i,t,n,a,s=null){const o=Date.now(),m=`computer:${e}:${i}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(t))throw new E("files must be an array",{field:"files"});if(!Array.isArray(n))throw new E("filePaths must be an array",{field:"filePaths"});if(t.length!==n.length)throw new E(`File count (${t.length}) does not match path count (${n.length})`,{field:"filePaths"});u(m,"DEBUG","Start batch uploading files",{userId:e,cId:i,filesCount:t.length});const c=[];try{for(let r=0;r<t.length;r++){const f=t[r],g=n[r];if(!f){u(m,"WARN","Empty file object encountered in batch upload, skipping",{index:r,filePath:g}),c.push({success:!1,filePath:g,error:"Empty file object"});continue}if(!g||typeof g!="string"){u(m,"WARN","Invalid file path in batch upload, skipping",{index:r,originalname:f.originalname}),c.push({success:!1,filePath:g||"",originalname:f.originalname,error:"Invalid file path"});continue}try{const d=await ne(e,i,f,g,a,s);c.push({success:!0,filePath:g,originalname:f.originalname,...d})}catch(d){u(m,"ERROR","Single file upload failed in batch upload",{filePath:g,originalname:f.originalname,error:d.message}),c.push({success:!1,filePath:g,originalname:f.originalname,error:d.message})}}const y=c.filter(r=>r.success).length,h=c.filter(r=>!r.success).length;return u(m,"INFO","Batch upload files completed",{userId:e,cId:i,totalCount:t.length,successCount:y,failCount:h,elapsedMs:Date.now()-o}),{success:!0,message:"Batch upload completed",totalCount:t.length,successCount:y,failCount:h,results:c}}catch(y){throw u(m,"ERROR","Batch upload files failed",{userId:e,cId:i,error:y.message,elapsedMs:Date.now()-o}),new z(`Batch upload files failed: ${y.message}`,{userId:e,cId:i,originalError:y.message})}}async function Be(e,i,t,n=null){const a=Date.now(),s=`computer:${e}:${i}`,o=ae(n);if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!o&&!n?.workspacePath)throw new z("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const m=String(e),c=String(i),y=t&&t.trim()?t.trim():null,h=y||A(n,m,c);if(!l.existsSync(h)){const R=`${m}_${c}.zip`;u(s,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:h,userId:m,cId:c,zipFileName:R});const D=oe("zip",{zlib:{level:9}});return D.append(null,{name:`${m}_${c}/`,type:"directory"}),D.on("warning",F=>{if(F.code==="ENOENT")u(s,"WARN","Encountered file problem when creating empty zip",{message:F.message,code:F.code});else throw u(s,"ERROR","Encountered warning when creating empty zip",{message:F.message,code:F.code}),F}),D.on("error",F=>{u(s,"ERROR","Failed to create empty zip",{message:F.message})}),{archive:D,zipFileName:R}}const r=`${m}_${c}.zip`;u(s,"DEBUG","Start creating workspace directory zip",{targetDir:h,zipFileName:r});const f=oe("zip",{zlib:{level:9}}),g=v.CONTENT_TRAVERSE_EXCLUDE_FILES||[],d=v.TRAVERSE_EXCLUDE_DIRS||[],p=await pe(h,g,d,s);if(p>V){const R=V/1024/1024,D=(p/1024/1024).toFixed(2);throw u(s,"WARN","Download rejected due to oversized workspace",{targetDir:h,downloadableSize:p,maxSizeBytes:V}),new E(`Download failed: total file size ${D}MB exceeds limit ${R}MB`,{field:"downloadSize",downloadableSize:p,maxSizeBytes:V})}return f.directory(h,`${m}_${c}`,R=>{const D=R.name||"",F=D.split(/[\/\\]/).filter(Boolean);if(F.some(k=>k.startsWith(".")))return!1;const S=F[F.length-1];if(g.includes(S)||F.some(k=>d.includes(k)))return!1;try{const k=w.join(h,D),I=l.lstatSync(k);if(I.isSymbolicLink()||I.nlink>1)return!1}catch(k){return u(s,"WARN","Error occurred when detecting link file, skipping",{filePath:D,error:k.message}),!1}return R}),f.on("warning",R=>{if(R.code==="ENOENT")u(s,"WARN","Encountered file problem when creating zip",{message:R.message,code:R.code});else throw u(s,"ERROR","Encountered warning when creating zip",{message:R.message,code:R.code}),R}),f.on("error",R=>{u(s,"ERROR","Failed to create zip",{message:R.message,elapsedMs:Date.now()-a})}),f.on("end",()=>{u(s,"INFO","Workspace directory zip created successfully",{targetDir:h,zipFileName:r,elapsedMs:Date.now()-a})}),{archive:f,zipFileName:r}}async function Xe(e,i,t=200,n=null){const a=Date.now(),s=`computer:${e}:${i}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});const o=String(e),m=String(i),c=ke(n,o,m);if(!c)return u(s,"WARN","COMPUTER_WORKSPACE_DIR is not configured"),{success:!0,message:"Log workspace is not configured",logs:[],totalLines:0,startIndex:1,logFileName:null};if(!l.existsSync(c))return u(s,"DEBUG","Log directory does not exist",{logDir:c}),{success:!0,message:"Log directory does not exist",logs:[],totalLines:0,startIndex:1,logFileName:null};const h=(await l.promises.readdir(c,{withFileTypes:!0})).filter(I=>I.isFile()).map(I=>I.name);if(h.length===0)return u(s,"DEBUG","No log file found",{logDir:c}),{success:!0,message:"No log file found",logs:[],totalLines:0,startIndex:1,logFileName:null};const r=[];for(const I of h){const b=w.join(c,I),T=await l.promises.stat(b);r.push({name:I,fullPath:b,mtime:T.mtimeMs,size:T.size})}r.sort((I,b)=>b.mtime-I.mtime);const f=r[0],d=(await l.promises.readFile(f.fullPath,"utf8")).split(`
2
- `).filter(I=>I.length>0),p=d.length,R=Math.max(1,t),D=Math.max(0,p-R),F=D+1,k=d.slice(D).map((I,b)=>({line:F+b,content:I}));return u(s,"DEBUG","Get latest logs",{fileName:f.name,fileSize:f.size,totalLines:p,returnedLines:k.length,elapsedMs:Date.now()-a}),{success:!0,message:"Get log successfully",logs:k,totalLines:p,startIndex:F,logFileName:f.name}}async function Ee(e,i){try{const n=(await l.promises.readdir(e,{withFileTypes:!0})).filter(m=>!m.name.startsWith(".")&&m.name!=="node_modules");if(n.length!==1||!n[0].isDirectory())return;const a=w.join(e,n[0].name),s=w.join(e,`..tmp_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{await l.promises.rename(a,s)}catch(m){if(m.code==="EXDEV")await l.promises.cp(a,s,{recursive:!0}),await l.promises.rm(a,{recursive:!0,force:!0});else throw m}const o=await l.promises.readdir(s);for(const m of o){const c=w.join(s,m),y=w.join(e,m);try{await l.promises.rename(c,y)}catch(h){if(h.code==="EXDEV")(await l.promises.lstat(c)).isDirectory()?await De(c,y):(await l.promises.copyFile(c,y),await l.promises.unlink(c));else throw h}}await l.promises.rm(s,{recursive:!0,force:!0}),u(i,"INFO","Removed single top-level directory from imported zip",{removedDir:n[0].name})}catch(t){u(i,"WARN","Failed to remove top-level directory from imported zip, continuing",{error:t.message})}}async function Ve(e,i){if(!l.existsSync(e)){await l.promises.mkdir(e,{recursive:!0});return}const t=await l.promises.readdir(e,{withFileTypes:!0});for(const n of t){if(j.has(n.name))continue;const a=w.join(e,n.name);await l.promises.rm(a,{recursive:!0,force:!0}),u(i,"DEBUG","Removed workspace entry during import",{name:n.name})}}async function Ge(e,i,t){if(await l.promises.mkdir(i,{recursive:!0}),!l.existsSync(e)){await l.promises.mkdir(e,{recursive:!0});return}const n=await l.promises.readdir(e,{withFileTypes:!0});for(const a of n){if(j.has(a.name))continue;const s=w.join(e,a.name),o=w.join(i,a.name);await te(s,o),u(t,"DEBUG","Backed up workspace entry before import",{name:a.name})}}async function qe(e,i,t){if(!l.existsSync(e))return;const n=await l.promises.readdir(e,{withFileTypes:!0});for(const a of n){if(j.has(a.name))continue;const s=w.join(e,a.name),o=w.join(i,a.name);await te(s,o)}u(t,"INFO","Workspace restored from backup after import failure")}async function He(e,i,t){const n=await l.promises.readdir(e,{withFileTypes:!0}),a=[];try{for(const s of n){if(j.has(s.name)){u(t,"INFO","Skipping preserved entry from imported zip",{name:s.name});continue}const o=w.join(e,s.name),m=w.join(i,s.name);await te(o,m),a.push(s.name)}}catch(s){throw s.mergedEntries=a,s}}async function Ze(e,i,t,n,a=null){const s=Date.now(),o=`computer:${e}:${i}`,m=ae(a);if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!i)throw new E("cId cannot be empty",{field:"cId"});if(!t||!t.path)throw new E("file is required",{field:"file"});if(!m&&!a?.workspacePath)throw new z("COMPUTER_WORKSPACE_DIR is not configured");if(w.extname(t.originalname||t.filename||"").toLowerCase()!==".zip")throw new E("Only zip files are supported",{field:"file",originalName:t.originalname});const y=String(e),h=String(i),r=n&&n.trim()?n.trim():A(a,y,h),f=w.join(r,".tmp"),g=w.join(f,`import_project_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);let d=null;u(o,"INFO","Start importing project from zip",{userId:y,cId:h,targetDir:r,fileName:t.originalname});try{await l.promises.mkdir(r,{recursive:!0}),await l.promises.mkdir(f,{recursive:!0}),await l.promises.mkdir(g,{recursive:!0}),await Se(t.path,g),await Ee(g,o),d=w.join(f,`import_backup_${Date.now()}_${Math.round(Math.random()*1e6)}`),await Ge(r,d,o);try{await He(g,r,o)}catch(p){throw u(o,"ERROR","Merge imported project failed, restoring workspace",{error:p.message,mergedEntries:p.mergedEntries||[]}),await Ve(r,o),await qe(d,r,o),p}return l.existsSync(d)&&(await l.promises.rm(d,{recursive:!0,force:!0}),d=null),u(o,"INFO","Project imported successfully",{userId:y,cId:h,targetDir:r,elapsedMs:Date.now()-s}),{success:!0,message:"Project imported successfully",userId:y,cId:h,targetDir:r}}catch(p){throw u(o,"ERROR","Failed to import project",{userId:y,cId:h,targetDir:r,error:p.message,elapsedMs:Date.now()-s}),p instanceof E||p instanceof z||p instanceof Ie?p:new z(`Failed to import project: ${p.message}`,{userId:y,cId:h,originalError:p.message})}finally{if(l.existsSync(g))try{await l.promises.rm(g,{recursive:!0,force:!0})}catch(p){u(o,"WARN","Failed to clean import extract directory",{extractRoot:g,error:p.message})}if(d&&l.existsSync(d))try{await l.promises.rm(d,{recursive:!0,force:!0})}catch(p){u(o,"WARN","Failed to clean import backup directory",{backupDir:d,error:p.message})}if(t?.path&&l.existsSync(t.path))try{await l.promises.unlink(t.path)}catch(p){u(o,"WARN","Failed to clean uploaded zip file",{tempZipPath:t.path,error:p.message})}}}async function Ke(e,i,t,n,a,s=null){const o=`computer:${e}:${i}`;if(!t||typeof t!="string"||!t.trim())throw new E("fileName cannot be empty",{field:"fileName"});if(n!=null&&typeof n!="string")throw new E("content must be a string",{field:"content"});const m=t.trim(),c=n??"";return u(o,"INFO","Generate file from text content",{userId:e,cId:i,fileName:m,contentLength:c.length}),{...await ne(e,i,{contents:c,originalname:w.basename(m),size:Buffer.byteLength(c,"utf8")},m,a,s),message:"File generated successfully",fileName:m}}export{$e as getFileList,Oe as getFileMeta,ve as resolveExistingFile,We as searchFiles,Ue as updateFiles,ne as uploadFile,je as uploadFiles,Ke as generateFile,Be as downloadAllFiles,Xe as getLatestLogs,Ze as importProject,j as IMPORT_PROJECT_PRESERVED_ENTRIES,Ee as removeTopLevelDir};
1
+ import c from"fs";import h from"path";import ae from"archiver";import{lookup as De}from"mime-types";import C from"../../appConfig/index.js";import{log as d}from"../log/logUtils.js";import{ValidationError as E,SystemError as z,FileError as ve}from"../error/errorHandler.js";import{extractZip as be}from"../common/zipUtils.js";import{moveDirectory as Ne,movePath as ie}from"../common/fileSystemUtils.js";import{resolveLogDir as ke,resolveWorkspaceDir as T,resolveWorkspaceRoot as le}from"./workspaceContext.js";const B=new Set([".git",".agents",".claude",".codex",".opencode",".tmp",".logs"]),xe=100*1024*1024,G=C.DOWNLOAD_MAX_FILE_SIZE_BYTES||xe;function H(e){return h.sep==="\\"?e.replace(/\\/g,"/"):e}function ce(e,r){return H(h.relative(e,r))}function ue(e,r){return e?`${e}/${r}`:r}function q(e){return e!=null&&e.limit!=null&&e.pushed>=e.limit}function Z(e){e!=null&&(e.pushed+=1)}async function fe(e,r,t,n,a,o={}){const{typeFilter:s=null,limitState:p=null,levelsLeft:u=1}=o,w=[],y=await c.promises.readdir(e,{withFileTypes:!0});y.sort((l,g)=>l.isDirectory()&&!g.isDirectory()?-1:!l.isDirectory()&&g.isDirectory()?1:l.name.toLowerCase().localeCompare(g.name.toLowerCase()));const i=ce(r,e);for(const l of y){if(q(p))break;if(l.name.startsWith(".")&&l.name!==".gitignore"||(C.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(l.name)||l.isDirectory()&&C.TRAVERSE_EXCLUDE_DIRS.includes(l.name))continue;const f=ue(i,l.name);if(l.isDirectory()){if(s!=="file"&&(w.push({name:f,isDir:!0}),Z(p)),u>1&&!q(p))try{const m=await fe(h.join(e,l.name),r,t,n,a,{typeFilter:s,limitState:p,levelsLeft:u-1});w.push(...m)}catch(m){d(t,"WARN",`Depth descent failed, skip subtree: ${f}`,{error:m.message})}continue}if(s!=="dir")try{w.push({name:f,isDir:!1,fileProxyUrl:Y(n,f,a),isLink:l.isSymbolicLink()}),Z(p)}catch(m){d(t,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${e}/${l.name}`,{error:m.message})}}return w}async function me(e,r,t,n,a="",o={}){const{typeFilter:s=null,limitState:p=null}=o,u=[];let w=0;const y=await c.promises.readdir(e,{withFileTypes:!0});y.sort((i,l)=>i.isDirectory()&&!l.isDirectory()?-1:!i.isDirectory()&&l.isDirectory()?1:i.name.toLowerCase().localeCompare(l.name.toLowerCase()));for(const i of y){if(q(p))break;const l=h.join(e,i.name);if(i.name.startsWith(".")&&i.name!==".gitignore"||(C.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(i.name)||i.isDirectory()&&C.TRAVERSE_EXCLUDE_DIRS.includes(i.name))continue;const f=ue(a,i.name);if(w+=1,i.isDirectory()){const m=await me(l,r,t,n,f,o);m.naturalCount===0?s!=="file"&&!q(p)&&(u.push({name:f,isDir:!0}),Z(p)):u.push(...m.entries)}else{if(s==="dir")continue;try{u.push({name:f,isDir:!1,fileProxyUrl:Y(t,f,n),isLink:i.isSymbolicLink()}),Z(p)}catch(m){d(r,"WARN",`\u5904\u7406\u6587\u4EF6\u5931\u8D25: ${l}`,{error:m.message})}}}return{entries:u,naturalCount:w}}function de(e,r){const t=(r==null?"":String(r)).trim();if(!t||t==="."||t==="/")return h.resolve(e);const n=h.normalize(t).replace(/^[\/\\]+/,"");if(!n||n===".")return h.resolve(e);if(h.isAbsolute(t)||n.split(h.sep).includes(".."))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:r});const a=h.resolve(e),o=h.resolve(e,n);if(o!==a&&!o.startsWith(a+h.sep))throw new E("relativePath \u975E\u6CD5\uFF0C\u4E0D\u5141\u8BB8\u8D8A\u51FA\u76EE\u6807\u76EE\u5F55",{field:"relativePath",relativePath:r});return o}function K(e,r){const t=(r==null?"":String(r)).trim();if(!t)return null;const n=h.resolve(e);let a;if(h.isAbsolute(t))a=h.resolve(t);else{const s=h.normalize(t).replace(/^[\/\\]+/,"");if(!s||s==="."||s.split(h.sep).includes(".."))return null;a=h.resolve(e,s)}if(a!==n&&!a.startsWith(n+h.sep))return null;const o=H(h.relative(n,a));return!o||o.startsWith("..")?null:{absPath:a,name:o}}function Y(e,r,t){if(!e||!r)return null;const n=r.split("/").map(o=>encodeURIComponent(o)).join("/");let a=`${e}/${n}`;return t&&(a+=`?customTargetDir=${encodeURIComponent(t)}`),a}async function Ce(e,r,t,n,a,o=null){if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});if(!t||!String(t).trim())throw new E("filePath \u4E0D\u80FD\u4E3A\u7A7A",{field:"filePath"});const s=String(e),p=String(r),u=a&&a.trim()?a.trim():null,w=u||T(o,s,p);if(!c.existsSync(w))return{exists:!1};let y=K(w,t);if(!y){const i=String(t).trim().replace(/^[\/\\]+/,"");i&&i!==String(t).trim()&&(y=K(w,i))}if(!y)return{exists:!1};try{if(!(await c.promises.stat(y.absPath)).isFile())return{exists:!1}}catch{return{exists:!1}}return{exists:!0,name:y.name,fileProxyUrl:Y(n,y.name,u)}}const _e=100,Pe=1e3,Le=8,pe=1e3;function Ae(e){return h.extname(e).replace(/^\./,"").toLowerCase()||""}async function ze(e,r,t){const n=new Array(e.length),a=Math.max(1,Math.min(r,e.length));let o=0;return await Promise.all(Array.from({length:a},async()=>{for(;;){const s=o++;if(s>=e.length)return;n[s]=await t(e[s],s)}})),n}function Te(e){return!(e.startsWith(".")&&e!==".gitignore"||(C.CONTENT_TRAVERSE_EXCLUDE_FILES||[]).includes(e)||C.TRAVERSE_EXCLUDE_DIRS.includes(e))}async function Oe(e){const r=await c.promises.opendir(e);let t=0;for await(const n of r)if(Te(n.name)&&(t+=1,t>=pe))return pe;return t}function he(e,r){return{path:e,isDir:null,isLink:null,size:null,mtimeMs:null,extension:null,mimeType:null,linkTarget:null,childCount:null,...r?{error:r}:{}}}async function $e(e,r,t){const n=(r==null?"":String(r)).trim();let a=n?K(e,n):null;if(!a&&n.startsWith("/")){const o=n.replace(/^[\/\\]+/,"");o&&o!==n&&(a=K(e,o))}if(!a)return he(n,"illegal path");try{const o=await c.promises.lstat(a.absPath),s=o.isDirectory(),p=o.isSymbolicLink(),u={path:n,isDir:s,isLink:p,size:s?null:o.size,mtimeMs:o.mtimeMs,extension:s?null:Ae(n),mimeType:s?null:De(n)||"application/octet-stream",linkTarget:null,childCount:null};if(p)try{u.linkTarget=await c.promises.readlink(a.absPath)}catch(w){d(t,"WARN","Readlink failed, linkTarget set to null",{filePath:n,error:w.message})}if(s)try{u.childCount=await Oe(a.absPath)}catch(w){d(t,"WARN","Count directory entries failed, childCount set to null",{filePath:n,error:w.message})}return u}catch(o){return he(n,o.code||o.message)}}async function Me(e,r,t,n,a=null,o=null){const s=Date.now(),p=`computer:${e}:${r}`;if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});if(!Array.isArray(t)||t.length===0)throw new E("filePaths \u5FC5\u987B\u4E3A\u975E\u7A7A\u6570\u7EC4",{field:"filePaths"});const u=Number.parseInt(o,10),w=Number.isFinite(u)&&u>0?Math.min(u,Pe):_e;if(t.length>w)throw new E(`filePaths \u5355\u6B21\u6700\u591A ${w} \u6761`,{field:"filePaths",count:t.length});const y=String(e),i=String(r),g=(n==null?"":String(n).trim())||null,f=g||T(a,y,i);if(!c.existsSync(f))return d(p,"INFO","Target directory does not exist, returning empty metas",{targetDir:f,userId:y,cId:i}),{metas:[]};const m=await ze(t,Le,S=>$e(f,S,p));return d(p,"INFO","File metadata queried",{targetDir:f,count:m.length,failed:m.filter(S=>S.error).length,customTargetDir:g,userId:y,cId:i,elapsedMs:Date.now()-s}),{metas:m}}async function we(e,r,t,n,a=""){const o=await c.promises.readdir(h.join(e,a),{withFileTypes:!0});let s=0;for(const p of o){const u=a?h.join(a,p.name):p.name,w=u.split(h.sep).filter(Boolean);if(w.some(g=>g.startsWith(".")))continue;const y=w[w.length-1];if(r.includes(y)||w.some(g=>t.includes(g)))continue;const i=h.join(e,u);let l;try{l=await c.promises.lstat(i)}catch(g){d(n,"WARN","Error occurred when getting file stats, skipping",{filePath:u.replace(/\\/g,"/"),error:g.message});continue}l.isSymbolicLink()||l.nlink>1||(l.isDirectory()?s+=await we(e,r,t,n,u):l.isFile()&&(s+=l.size))}return s}async function We(e,r,t,n,a,o,s,p,u,w=null){const y=Date.now(),i=`computer:${e}:${r}`,l=!(o===!1||o==="false");if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const g=p==null?"":String(p).trim().toLowerCase();let f=null;if(g&&g!=="all")if(g==="file")f="file";else if(g==="dir"||g==="directory")f="dir";else throw new E("type \u4EC5\u652F\u6301 file/dir/all",{field:"type",value:p});let m=null;if(u!=null&&u!==""){const D=Number(u);if(!Number.isInteger(D)||D<0)throw new E("limit \u5FC5\u987B\u4E3A\u975E\u8D1F\u6574\u6570",{field:"limit",value:u});m=D}let S=null;if(!l&&s!=null&&s!==""){const D=Number(s);if(!Number.isInteger(D)||D<1||D>10)throw new E("depth \u9700\u4E3A 1-10 \u7684\u6574\u6570",{field:"depth",value:s});S=D}const v=String(e),R=String(r),b=n&&n.trim()?n.trim():null,I=b||T(w,v,R);if(!c.existsSync(I))return d(i,"INFO","Directory does not exist, returning empty list",{targetDir:I,userId:v,cId:R}),{files:[],recursive:l,depth:S,type:f||"all",limit:m};const F=de(I,a);if(!c.existsSync(F))return d(i,"INFO","List path does not exist, returning empty list",{targetDir:I,listDir:F,relativePath:a||"",userId:v,cId:R}),{files:[],recursive:l,depth:S,type:f||"all",limit:m};if(!(await c.promises.stat(F)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:a});d(i,"DEBUG","Start getting user file list",{targetDir:I,listDir:F,relativePath:a||"",recursive:l,userId:v,cId:R});try{const D={typeFilter:f,limitState:{limit:m,pushed:0},levelsLeft:!l&&S!=null?S:1},O=l?(await me(F,i,t,b,ce(I,F),D)).entries:await fe(F,I,i,t,b,D);return d(i,"INFO","User file list obtained successfully",{fileCount:O.length,targetDir:I,listDir:F,relativePath:a||"",recursive:l,depth:S,type:f||"all",limit:m,userId:v,cId:R,elapsedMs:Date.now()-y}),{files:O,recursive:l,depth:S,type:f||"all",limit:m}}catch(D){throw D instanceof E?D:(d(i,"ERROR","Failed to get user file list",{targetDir:I,listDir:F,relativePath:a||"",recursive:l,userId:v,cId:R,error:D.message,elapsedMs:Date.now()-y}),new z(`Failed to get file list: ${D.message}`,{targetDir:I,originalError:D.message}))}}const Ue=5e3;function ne(e,r){const t=Number.parseInt(e,10);if(!Number.isFinite(t)||t<=0)throw new E(`${r} \u5FC5\u987B\u4E3A\u6B63\u6574\u6570`,{field:r,value:e});return t}function ge(e,r,t){return t?r.toLowerCase().includes(t)?!0:e.toLowerCase().includes(t):!1}const je=new Set([".git",".svn",".hg","node_modules","__pycache__",".venv","venv","virtualenv",".mypy_cache",".pytest_cache",".ruff_cache",".cache"]),Be=new Set([".DS_Store","Thumbs.db","desktop.ini"]);function ye(e,r,t){return!!(Be.has(e.name)||r.includes(e.name)||e.isDirectory()&&(je.has(e.name)||t.includes(e.name)))}function Ee(e,r,t,n){for(let a=r;a<e.length;a++)if(!ye(e[a],t,n))return!0;return!1}function Se(e,r){return Date.now()-e>=r}async function Xe(e,r,t,n,a,o,s,p,u,w,y=null){const i=Date.now(),l=`computer:${e}:${r}`;if(!e)throw new E("userId \u4E0D\u80FD\u4E3A\u7A7A",{field:"userId"});if(!r)throw new E("cId \u4E0D\u80FD\u4E3A\u7A7A",{field:"cId"});const g=(n==null?"":String(n)).trim();if(!g)throw new E("kw \u4E0D\u80FD\u4E3A\u7A7A",{field:"kw"});const f=ne(p,"limit"),m=ne(u,"maxVisit"),S=ne(w,"timeoutMs"),v=g.toLowerCase(),R=(()=>{const N=s==null?"":String(s).trim().toLowerCase();return N==="file"?"file":N==="dir"||N==="directory"?"dir":null})(),b=N=>R==null||R==="dir"===N,I=String(e),F=String(r),x=a&&a.trim()?a.trim():null,D=x||T(y,I,F);if(!c.existsSync(D))return{files:[],truncated:!1,visited:0};const O=de(D,o);if(!c.existsSync(O))return{files:[],truncated:!1,visited:0};if(!(await c.promises.stat(O)).isDirectory())throw new E("relativePath \u5FC5\u987B\u662F\u76EE\u5F55",{field:"relativePath",relativePath:o});const Fe=H(h.relative(D,O)),J=C.CONTENT_TRAVERSE_EXCLUDE_FILES||[],Q=C.TRAVERSE_EXCLUDE_DIRS||[],_=[],ee=new Set;let $=0,te=!1,L=!1;const A=[Fe],U=()=>$>=m||Se(i,S);for(;A.length>0;){if(U()){L=!0;break}if(_.length>=f){A.length>0&&(L=!0);break}const N=A.shift();if(ee.has(N))continue;ee.add(N);const j=N?h.join(D,N):D;let M;try{M=await c.promises.readdir(j,{withFileTypes:!0})}catch(k){d(l,"WARN","search readdir failed",{dirRel:N,error:k.message});continue}M.sort((k,P)=>k.isDirectory()&&!P.isDirectory()?-1:!k.isDirectory()&&P.isDirectory()?1:k.name.toLowerCase().localeCompare(P.name.toLowerCase()));const re=[];let X=!1,V=!1;for(let k=0;k<M.length;k++){const P=M[k];if(ye(P,J,Q))continue;if(U()){L=!0,X=!0,V=!0;break}$+=1;const oe=h.join(j,P.name),W=H(h.relative(D,oe));if(P.isDirectory()){if(re.push(W),b(!0)&&_.length<f&&ge(W,P.name,v)&&(_.push({name:W,isDir:!0}),_.length>=f)){X=!0,V=Ee(M,k+1,J,Q);break}continue}try{if(b(!1)&&_.length<f&&ge(W,P.name,v)&&(_.push({name:W,isDir:!1,fileProxyUrl:Y(t,W,x),isLink:P.isSymbolicLink()}),_.length>=f)){X=!0,V=Ee(M,k+1,J,Q);break}}catch(Ie){d(l,"WARN",`search \u5904\u7406\u6587\u4EF6\u5931\u8D25: ${oe}`,{error:Ie.message})}}if(X||U()){(U()||V||re.length>0||A.length>0)&&(L=!0);continue}for(const k of re){if(U()){L=!0;break}if(A.length>=Ue){L=!0;break}if($+A.length>=m){L=!0;break}ee.has(k)||A.push(k)}}return _.sort((N,j)=>N.isDir!==j.isDir?N.isDir?-1:1:String(N.name).localeCompare(String(j.name))),te=L||A.length>0||$>=m||Se(i,S),d(l,"INFO","File search completed",{kw:g,matchCount:_.length,visited:$,truncated:te,relativePath:o||"",elapsedMs:Date.now()-i}),{files:_,truncated:te,visited:$}}async function Ve(e,r,t,n,a=null){const o=Date.now(),s=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(t))throw new E("files must be an array",{field:"files"});const p=String(e),u=String(r),w=n&&n.trim()?n.trim():null,y=w||T(a,p,u);c.existsSync(y)||c.mkdirSync(y,{recursive:!0});for(let i=0;i<t.length;i++){const l=t[i];if(!l||typeof l.operation!="string")throw new E(`files[${i}].operation cannot be empty`,{field:`files[${i}].operation`});if(!l.name||typeof l.name!="string")throw new E(`files[${i}].name cannot be empty`,{field:`files[${i}].name`});const g=l.operation.toLowerCase();if(!["create","delete","rename","modify"].includes(g))throw new E(`files[${i}].operation must be one of create, delete, rename or modify`,{field:`files[${i}].operation`});if(g==="rename"&&!l.renameFrom)throw new E(`files[${i}].renameFrom cannot be empty (rename operation requires)`,{field:`files[${i}].renameFrom`});if(g==="modify"&&l.isDir!==!0&&typeof l.contents!="string")throw new E(`files[${i}].contents must be a string (modify operation requires)`,{field:`files[${i}].contents`})}d(s,"DEBUG","Start updating user files",{userId:p,cId:u,filesCount:t.length});try{for(const i of t){const l=i.operation.toLowerCase(),g=i.name,f=h.normalize(g).replace(/^[\/\\]+/,""),m=h.join(y,f),S=h.resolve(m),v=h.resolve(y);if(!S.startsWith(v+h.sep)&&S!==v){d(s,"WARN","File path is not secure, skipping",{filePath:f,resolvedPath:S});continue}switch(l){case"create":{if(i.isDir===!0){if(c.existsSync(m)){if((await c.promises.stat(m)).isFile())throw new E("Cannot create directory, file with the same name already exists",{filePath:f});d(s,"INFO","Directory already exists, skipping creation",{filePath:f});break}await c.promises.mkdir(m,{recursive:!0}),d(s,"INFO","Directory created successfully",{filePath:f});break}if(c.existsSync(m)){if((await c.promises.stat(m)).isDirectory())throw new E("Cannot create file, directory with the same name already exists",{filePath:f});d(s,"INFO","File already exists, skipping creation",{filePath:f});break}await c.promises.mkdir(h.dirname(m),{recursive:!0});const R=i.contents||"";await c.promises.writeFile(m,R,"utf8"),d(s,"INFO","File created successfully",{filePath:f});break}case"delete":{c.existsSync(m)?(await c.promises.stat(m)).isDirectory()?(await c.promises.rm(m,{recursive:!0,force:!0}),d(s,"INFO","Directory deleted successfully",{filePath:f})):(await c.promises.unlink(m),d(s,"INFO","File deleted successfully",{filePath:f})):d(s,"WARN","The file or directory to be deleted does not exist",{filePath:f});break}case"rename":{const R=i.renameFrom;if(!R||typeof R!="string"){d(s,"WARN","Rename operation missing renameFrom",{filePath:f});break}const b=h.normalize(R).replace(/^[\/\\]+/,""),I=h.join(y,b),F=h.resolve(I);if(!F.startsWith(v+h.sep)&&F!==v){d(s,"WARN","Source path is not secure, skipping rename",{sourcePath:b,targetPath:f});break}if(c.existsSync(I)){const D=(await c.promises.stat(I)).isDirectory();await c.promises.mkdir(h.dirname(m),{recursive:!0}),await c.promises.rename(I,m),d(s,"INFO",D?"Directory renamed successfully":"File renamed successfully",{sourcePath:b,targetPath:f})}else d(s,"WARN","The file or directory to be renamed does not exist",{sourcePath:b});break}case"modify":{if(!c.existsSync(m)){d(s,"WARN","The file to be modified does not exist",{filePath:f});break}if((await c.promises.stat(m)).isDirectory()){d(s,"INFO","The target is a directory, skipping modification",{filePath:f});break}const b=typeof i.contents=="string"?i.contents:"";if(await c.promises.readFile(m,"utf8")===b){d(s,"INFO","File content has no changes, skipping write",{filePath:f});break}await c.promises.writeFile(m,b,"utf8"),d(s,"INFO","File modified successfully",{filePath:f});break}default:{d(s,"WARN","Unsupported operation type",{operation:l,filePath:f});break}}}return d(s,"INFO","User files updated successfully",{userId:p,cId:u,filesCount:t.length,elapsedMs:Date.now()-o}),{success:!0,message:"User files updated successfully",userId:p,cId:u,filesCount:t.length}}catch(i){throw d(s,"ERROR","User files updated failed",{userId:p,cId:u,error:i.message,elapsedMs:Date.now()-o}),new z(`User files updated failed: ${i.message}`,{userId:p,cId:u,originalError:i.message})}}async function se(e,r,t,n,a,o=null){const s=Date.now(),p=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!t)throw new E("file cannot be empty",{field:"file"});if(!n||typeof n!="string")throw new E("filePath cannot be empty",{field:"filePath"});const u=String(e),w=String(r),y=a&&a.trim()?a.trim():null,i=y||T(o,u,w);c.existsSync(i)||c.mkdirSync(i,{recursive:!0});const l=h.normalize(n).replace(/^[\/\\]+/,""),g=h.join(i,l),f=h.resolve(g),m=h.resolve(i);if(!f.startsWith(m+h.sep)&&f!==m)throw new E("File path is not secure, cannot exceed user directory",{field:"filePath",providedPath:n,resolvedPath:f});try{if(await c.promises.mkdir(h.dirname(g),{recursive:!0}),t.buffer)await c.promises.writeFile(g,t.buffer);else if(typeof t.contents=="string")await c.promises.writeFile(g,t.contents,"utf8");else throw new E("File content format is incorrect",{field:"file",hasBuffer:!!t.buffer,hasContents:typeof t.contents});return d(p,"INFO","File uploaded successfully",{userId:u,cId:w,filePath:l,targetPath:f,fileSize:t.buffer?t.buffer.length:t.contents?t.contents.length:0,elapsedMs:Date.now()-s}),{success:!0,message:"File uploaded successfully",fileSize:t.buffer?t.buffer.length:t.contents?t.contents.length:0}}catch(S){throw d(p,"ERROR","File upload failed",{userId:u,cId:w,filePath:l,error:S.message,elapsedMs:Date.now()-s}),new z(`File upload failed: ${S.message}`,{userId:u,cId:w,filePath:l,originalError:S.message})}}async function Ge(e,r,t,n,a,o=null){const s=Date.now(),p=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!Array.isArray(t))throw new E("files must be an array",{field:"files"});if(!Array.isArray(n))throw new E("filePaths must be an array",{field:"filePaths"});if(t.length!==n.length)throw new E(`File count (${t.length}) does not match path count (${n.length})`,{field:"filePaths"});d(p,"DEBUG","Start batch uploading files",{userId:e,cId:r,filesCount:t.length});const u=[];try{for(let i=0;i<t.length;i++){const l=t[i],g=n[i];if(!l){d(p,"WARN","Empty file object encountered in batch upload, skipping",{index:i,filePath:g}),u.push({success:!1,filePath:g,error:"Empty file object"});continue}if(!g||typeof g!="string"){d(p,"WARN","Invalid file path in batch upload, skipping",{index:i,originalname:l.originalname}),u.push({success:!1,filePath:g||"",originalname:l.originalname,error:"Invalid file path"});continue}try{const f=await se(e,r,l,g,a,o);u.push({success:!0,filePath:g,originalname:l.originalname,...f})}catch(f){d(p,"ERROR","Single file upload failed in batch upload",{filePath:g,originalname:l.originalname,error:f.message}),u.push({success:!1,filePath:g,originalname:l.originalname,error:f.message})}}const w=u.filter(i=>i.success).length,y=u.filter(i=>!i.success).length;return d(p,"INFO","Batch upload files completed",{userId:e,cId:r,totalCount:t.length,successCount:w,failCount:y,elapsedMs:Date.now()-s}),{success:!0,message:"Batch upload completed",totalCount:t.length,successCount:w,failCount:y,results:u}}catch(w){throw d(p,"ERROR","Batch upload files failed",{userId:e,cId:r,error:w.message,elapsedMs:Date.now()-s}),new z(`Batch upload files failed: ${w.message}`,{userId:e,cId:r,originalError:w.message})}}async function He(e,r,t,n=null){const a=Date.now(),o=`computer:${e}:${r}`,s=le(n);if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!s&&!n?.workspacePath)throw new z("COMPUTER_WORKSPACE_DIR is not configured, cannot create zip");const p=String(e),u=String(r),w=t&&t.trim()?t.trim():null,y=w||T(n,p,u);if(!c.existsSync(y)){const S=`${p}_${u}.zip`;d(o,"WARN","Workspace directory does not exist, returning empty zip",{targetDir:y,userId:p,cId:u,zipFileName:S});const v=ae("zip",{zlib:{level:9}});return v.append(null,{name:`${p}_${u}/`,type:"directory"}),v.on("warning",R=>{if(R.code==="ENOENT")d(o,"WARN","Encountered file problem when creating empty zip",{message:R.message,code:R.code});else throw d(o,"ERROR","Encountered warning when creating empty zip",{message:R.message,code:R.code}),R}),v.on("error",R=>{d(o,"ERROR","Failed to create empty zip",{message:R.message})}),{archive:v,zipFileName:S}}const i=`${p}_${u}.zip`;d(o,"DEBUG","Start creating workspace directory zip",{targetDir:y,zipFileName:i});const l=ae("zip",{zlib:{level:9}}),g=C.CONTENT_TRAVERSE_EXCLUDE_FILES||[],f=C.TRAVERSE_EXCLUDE_DIRS||[],m=await we(y,g,f,o);if(m>G){const S=G/1024/1024,v=(m/1024/1024).toFixed(2);throw d(o,"WARN","Download rejected due to oversized workspace",{targetDir:y,downloadableSize:m,maxSizeBytes:G}),new E(`Download failed: total file size ${v}MB exceeds limit ${S}MB`,{field:"downloadSize",downloadableSize:m,maxSizeBytes:G})}return l.directory(y,`${p}_${u}`,S=>{const v=S.name||"",R=v.split(/[\/\\]/).filter(Boolean);if(R.some(I=>I.startsWith(".")))return!1;const b=R[R.length-1];if(g.includes(b)||R.some(I=>f.includes(I)))return!1;try{const I=h.join(y,v),F=c.lstatSync(I);if(F.isSymbolicLink()||F.nlink>1)return!1}catch(I){return d(o,"WARN","Error occurred when detecting link file, skipping",{filePath:v,error:I.message}),!1}return S}),l.on("warning",S=>{if(S.code==="ENOENT")d(o,"WARN","Encountered file problem when creating zip",{message:S.message,code:S.code});else throw d(o,"ERROR","Encountered warning when creating zip",{message:S.message,code:S.code}),S}),l.on("error",S=>{d(o,"ERROR","Failed to create zip",{message:S.message,elapsedMs:Date.now()-a})}),l.on("end",()=>{d(o,"INFO","Workspace directory zip created successfully",{targetDir:y,zipFileName:i,elapsedMs:Date.now()-a})}),{archive:l,zipFileName:i}}async function qe(e,r,t=200,n=null){const a=Date.now(),o=`computer:${e}:${r}`;if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});const s=String(e),p=String(r),u=ke(n,s,p);if(!u)return d(o,"WARN","COMPUTER_WORKSPACE_DIR is not configured"),{success:!0,message:"Log workspace is not configured",logs:[],totalLines:0,startIndex:1,logFileName:null};if(!c.existsSync(u))return d(o,"DEBUG","Log directory does not exist",{logDir:u}),{success:!0,message:"Log directory does not exist",logs:[],totalLines:0,startIndex:1,logFileName:null};const y=(await c.promises.readdir(u,{withFileTypes:!0})).filter(F=>F.isFile()).map(F=>F.name);if(y.length===0)return d(o,"DEBUG","No log file found",{logDir:u}),{success:!0,message:"No log file found",logs:[],totalLines:0,startIndex:1,logFileName:null};const i=[];for(const F of y){const x=h.join(u,F),D=await c.promises.stat(x);i.push({name:F,fullPath:x,mtime:D.mtimeMs,size:D.size})}i.sort((F,x)=>x.mtime-F.mtime);const l=i[0],f=(await c.promises.readFile(l.fullPath,"utf8")).split(`
2
+ `).filter(F=>F.length>0),m=f.length,S=Math.max(1,t),v=Math.max(0,m-S),R=v+1,I=f.slice(v).map((F,x)=>({line:R+x,content:F}));return d(o,"DEBUG","Get latest logs",{fileName:l.name,fileSize:l.size,totalLines:m,returnedLines:I.length,elapsedMs:Date.now()-a}),{success:!0,message:"Get log successfully",logs:I,totalLines:m,startIndex:R,logFileName:l.name}}async function Re(e,r){try{const n=(await c.promises.readdir(e,{withFileTypes:!0})).filter(p=>!p.name.startsWith(".")&&p.name!=="node_modules");if(n.length!==1||!n[0].isDirectory())return;const a=h.join(e,n[0].name),o=h.join(e,`..tmp_${Date.now()}_${Math.round(Math.random()*1e6)}`);try{await c.promises.rename(a,o)}catch(p){if(p.code==="EXDEV")await c.promises.cp(a,o,{recursive:!0}),await c.promises.rm(a,{recursive:!0,force:!0});else throw p}const s=await c.promises.readdir(o);for(const p of s){const u=h.join(o,p),w=h.join(e,p);try{await c.promises.rename(u,w)}catch(y){if(y.code==="EXDEV")(await c.promises.lstat(u)).isDirectory()?await Ne(u,w):(await c.promises.copyFile(u,w),await c.promises.unlink(u));else throw y}}await c.promises.rm(o,{recursive:!0,force:!0}),d(r,"INFO","Removed single top-level directory from imported zip",{removedDir:n[0].name})}catch(t){d(r,"WARN","Failed to remove top-level directory from imported zip, continuing",{error:t.message})}}async function Ze(e,r){if(!c.existsSync(e)){await c.promises.mkdir(e,{recursive:!0});return}const t=await c.promises.readdir(e,{withFileTypes:!0});for(const n of t){if(B.has(n.name))continue;const a=h.join(e,n.name);await c.promises.rm(a,{recursive:!0,force:!0}),d(r,"DEBUG","Removed workspace entry during import",{name:n.name})}}async function Ke(e,r,t){if(await c.promises.mkdir(r,{recursive:!0}),!c.existsSync(e)){await c.promises.mkdir(e,{recursive:!0});return}const n=await c.promises.readdir(e,{withFileTypes:!0});for(const a of n){if(B.has(a.name))continue;const o=h.join(e,a.name),s=h.join(r,a.name);await ie(o,s),d(t,"DEBUG","Backed up workspace entry before import",{name:a.name})}}async function Ye(e,r,t){if(!c.existsSync(e))return;const n=await c.promises.readdir(e,{withFileTypes:!0});for(const a of n){if(B.has(a.name))continue;const o=h.join(e,a.name),s=h.join(r,a.name);await ie(o,s)}d(t,"INFO","Workspace restored from backup after import failure")}async function Je(e,r,t){const n=await c.promises.readdir(e,{withFileTypes:!0}),a=[];try{for(const o of n){if(B.has(o.name)){d(t,"INFO","Skipping preserved entry from imported zip",{name:o.name});continue}const s=h.join(e,o.name),p=h.join(r,o.name);await ie(s,p),a.push(o.name)}}catch(o){throw o.mergedEntries=a,o}}async function Qe(e,r,t,n,a=null){const o=Date.now(),s=`computer:${e}:${r}`,p=le(a);if(!e)throw new E("userId cannot be empty",{field:"userId"});if(!r)throw new E("cId cannot be empty",{field:"cId"});if(!t||!t.path)throw new E("file is required",{field:"file"});if(!p&&!a?.workspacePath)throw new z("COMPUTER_WORKSPACE_DIR is not configured");if(h.extname(t.originalname||t.filename||"").toLowerCase()!==".zip")throw new E("Only zip files are supported",{field:"file",originalName:t.originalname});const w=String(e),y=String(r),i=n&&n.trim()?n.trim():T(a,w,y),l=h.join(i,".tmp"),g=h.join(l,`import_project_extract_${Date.now()}_${Math.round(Math.random()*1e6)}`);let f=null;d(s,"INFO","Start importing project from zip",{userId:w,cId:y,targetDir:i,fileName:t.originalname});try{await c.promises.mkdir(i,{recursive:!0}),await c.promises.mkdir(l,{recursive:!0}),await c.promises.mkdir(g,{recursive:!0}),await be(t.path,g),await Re(g,s),f=h.join(l,`import_backup_${Date.now()}_${Math.round(Math.random()*1e6)}`),await Ke(i,f,s);try{await Je(g,i,s)}catch(m){throw d(s,"ERROR","Merge imported project failed, restoring workspace",{error:m.message,mergedEntries:m.mergedEntries||[]}),await Ze(i,s),await Ye(f,i,s),m}return c.existsSync(f)&&(await c.promises.rm(f,{recursive:!0,force:!0}),f=null),d(s,"INFO","Project imported successfully",{userId:w,cId:y,targetDir:i,elapsedMs:Date.now()-o}),{success:!0,message:"Project imported successfully",userId:w,cId:y,targetDir:i}}catch(m){throw d(s,"ERROR","Failed to import project",{userId:w,cId:y,targetDir:i,error:m.message,elapsedMs:Date.now()-o}),m instanceof E||m instanceof z||m instanceof ve?m:new z(`Failed to import project: ${m.message}`,{userId:w,cId:y,originalError:m.message})}finally{if(c.existsSync(g))try{await c.promises.rm(g,{recursive:!0,force:!0})}catch(m){d(s,"WARN","Failed to clean import extract directory",{extractRoot:g,error:m.message})}if(f&&c.existsSync(f))try{await c.promises.rm(f,{recursive:!0,force:!0})}catch(m){d(s,"WARN","Failed to clean import backup directory",{backupDir:f,error:m.message})}if(t?.path&&c.existsSync(t.path))try{await c.promises.unlink(t.path)}catch(m){d(s,"WARN","Failed to clean uploaded zip file",{tempZipPath:t.path,error:m.message})}}}async function et(e,r,t,n,a,o=null){const s=`computer:${e}:${r}`;if(!t||typeof t!="string"||!t.trim())throw new E("fileName cannot be empty",{field:"fileName"});if(n!=null&&typeof n!="string")throw new E("content must be a string",{field:"content"});const p=t.trim(),u=n??"";return d(s,"INFO","Generate file from text content",{userId:e,cId:r,fileName:p,contentLength:u.length}),{...await se(e,r,{contents:u,originalname:h.basename(p),size:Buffer.byteLength(u,"utf8")},p,a,o),message:"File generated successfully",fileName:p}}export{We as getFileList,Me as getFileMeta,Ce as resolveExistingFile,Xe as searchFiles,Ve as updateFiles,se as uploadFile,Ge as uploadFiles,et as generateFile,He as downloadAllFiles,qe as getLatestLogs,Qe as importProject,B as IMPORT_PROJECT_PRESERVED_ENTRIES,Re as removeTopLevelDir};
@@ -1,8 +1,8 @@
1
- import C from"path";import e from"fs";import L from"crypto";import i from"isomorphic-git";import{createPatch as O}from"diff";import P from"../../appConfig/index.js";import{cleanEmptyParentDirs as N}from"./nativeGitUtils.js";function T(t,s){return{name:t||P.GIT_DEFAULT_AUTHOR_NAME,email:s||P.GIT_DEFAULT_AUTHOR_EMAIL}}function M(t){for(let s=0;s<Math.min(t.length,8e3);s++)if(t[s]===0)return!0;return!1}function W(t){const s=Buffer.from(`blob ${t.length}\0`);return L.createHash("sha1").update(Buffer.concat([s,t])).digest("hex")}async function D(t){return i.resolveRef({fs:e,dir:t,ref:"HEAD"})}async function I(t){try{return await i.resolveRef({fs:e,dir:t,ref:"HEAD"}),!0}catch{return!1}}async function B(t,s,o){try{const{blob:a}=await i.readBlob({fs:e,dir:t,oid:s,filepath:o}),n=Buffer.from(a);return{content:n.toString("utf8"),buf:n}}catch{return null}}function G(t,s,o,a,n,r,f){const w=O(t,a?s:"",n?o:"",a?`a/${t}`:"/dev/null",n?`b/${t}`:"/dev/null").split(`
2
- `).slice(4);w.length>0&&w[w.length-1]===""&&w.pop();const u=[];let d=0,g=0;for(const m of w){if(m.startsWith("@@")){const x=m.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(x){const H=x[1],E=x[2]!==void 0?parseInt(x[2],10):1,F=x[3],v=x[4]!==void 0?parseInt(x[4],10):1,A=E===1?H:`${H},${E}`,$=v===1?F:`${F},${v}`;u.push(`@@ -${A} +${$} @@`);continue}}m.startsWith("+")&&!m.startsWith("+++")?d++:m.startsWith("-")&&!m.startsWith("---")&&g++,u.push(m)}const p=a&&s!==""&&!s.endsWith(`
1
+ import A from"path";import e from"fs";import j from"crypto";import r from"isomorphic-git";import{createPatch as U}from"diff";import P from"../../appConfig/index.js";import{cleanEmptyParentDirs as D}from"./nativeGitUtils.js";function $(t,s){return{name:t||P.GIT_DEFAULT_AUTHOR_NAME,email:s||P.GIT_DEFAULT_AUTHOR_EMAIL}}function M(t){for(let s=0;s<Math.min(t.length,8e3);s++)if(t[s]===0)return!0;return!1}function B(t){const s=Buffer.from(`blob ${t.length}\0`);return j.createHash("sha1").update(Buffer.concat([s,t])).digest("hex")}async function W(t){return r.resolveRef({fs:e,dir:t,ref:"HEAD"})}async function T(t){try{return await r.resolveRef({fs:e,dir:t,ref:"HEAD"}),!0}catch{return!1}}async function N(t,s,o){try{const{blob:a}=await r.readBlob({fs:e,dir:t,oid:s,filepath:o}),n=Buffer.from(a);return{content:n.toString("utf8"),buf:n}}catch{return null}}function V(t,s,o,a,n,c,i){const w=U(t,a?s:"",n?o:"",a?`a/${t}`:"/dev/null",n?`b/${t}`:"/dev/null").split(`
2
+ `).slice(4);w.length>0&&w[w.length-1]===""&&w.pop();const h=[];let d=0,g=0;for(const m of w){if(m.startsWith("@@")){const x=m.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(x){const k=x[1],C=x[2]!==void 0?parseInt(x[2],10):1,F=x[3],v=x[4]!==void 0?parseInt(x[4],10):1,I=C===1?k:`${k},${C}`,H=v===1?F:`${F},${v}`;h.push(`@@ -${I} +${H} @@`);continue}}m.startsWith("+")&&!m.startsWith("+++")?d++:m.startsWith("-")&&!m.startsWith("---")&&g++,h.push(m)}const p=a&&s!==""&&!s.endsWith(`
3
3
  `),S=n&&o!==""&&!o.endsWith(`
4
- `);if((p||S)&&u.length>0){let m=0;for(let v=0;v<u.length;v++)u[v].startsWith("@@")&&(m=v);let x=-1,H=-1,E=-1;for(let v=u.length-1;v>m;v--){const A=u[v];A.startsWith("-")&&!A.startsWith("---")&&x<0?x=v:A.startsWith("+")&&!A.startsWith("++")&&H<0?H=v:A.startsWith(" ")&&E<0&&(E=v)}const F=Math.max(x,H,E);if(F>=0){const v=u[F];if(v.startsWith(" "))(p||S)&&u.splice(F+1,0,"\");else if(v.startsWith("+")){let A=-1;for(let $=F-1;$>m;$--)if(u[$].startsWith("-")&&!u[$].startsWith("---")){A=$;break}A>=0&&p?(u.splice(A+1,0,"\"),S&&u.splice(F+2,0,"\")):S&&u.splice(F+1,0,"\")}else v.startsWith("-")&&p&&u.splice(F+1,0,"\")}}const b=a&&r?W(r).substring(0,7):"0000000",k=n&&f?W(f).substring(0,7):"0000000",c=[];return c.push(`diff --git a/${t} b/${t}`),a?n?c.push(`index ${b}..${k} 100644`):(c.push("deleted file mode 100644"),c.push(`index ${b}..0000000`)):(c.push("new file mode 100644"),c.push(`index 0000000..${k}`)),c.push(`--- ${a?`a/${t}`:"/dev/null"}`),c.push(`+++ ${n?`b/${t}`:"/dev/null"}`),{diff:[...c,...u].join(`
4
+ `);if((p||S)&&h.length>0){let m=0;for(let v=0;v<h.length;v++)h[v].startsWith("@@")&&(m=v);let x=-1,k=-1,C=-1;for(let v=h.length-1;v>m;v--){const I=h[v];I.startsWith("-")&&!I.startsWith("---")&&x<0?x=v:I.startsWith("+")&&!I.startsWith("++")&&k<0?k=v:I.startsWith(" ")&&C<0&&(C=v)}const F=Math.max(x,k,C);if(F>=0){const v=h[F];if(v.startsWith(" "))(p||S)&&h.splice(F+1,0,"\");else if(v.startsWith("+")){let I=-1;for(let H=F-1;H>m;H--)if(h[H].startsWith("-")&&!h[H].startsWith("---")){I=H;break}I>=0&&p?(h.splice(I+1,0,"\"),S&&h.splice(F+2,0,"\")):S&&h.splice(F+1,0,"\")}else v.startsWith("-")&&p&&h.splice(F+1,0,"\")}}const b=a&&c?B(c).substring(0,7):"0000000",E=n&&i?B(i).substring(0,7):"0000000",l=[];return l.push(`diff --git a/${t} b/${t}`),a?n?l.push(`index ${b}..${E} 100644`):(l.push("deleted file mode 100644"),l.push(`index ${b}..0000000`)):(l.push("new file mode 100644"),l.push(`index 0000000..${E}`)),l.push(`--- ${a?`a/${t}`:"/dev/null"}`),l.push(`+++ ${n?`b/${t}`:"/dev/null"}`),{diff:[...l,...h].join(`
5
5
  `)+`
6
- `,insertions:d,deletions:g}}async function V(t,s){const{authorName:o,authorEmail:a,defaultBranch:n="main"}=s;await i.init({fs:e,dir:t,defaultBranch:n}),await i.setConfig({fs:e,dir:t,path:"user.name",value:o}),await i.setConfig({fs:e,dir:t,path:"user.email",value:a})}async function q(t){const s=await i.currentBranch({fs:e,dir:t,fullname:!1}),o=await i.statusMatrix({fs:e,dir:t}),a=[],n=[],r=[],f=[],l=[];for(const[h,w,u,d]of o)w!==d&&a.push(h),w===0&&d!==0&&r.push(h),(w===1&&d===0||u===0&&d!==0)&&f.push(h),d!==0&&u!==0&&u!==d&&n.push(h),w===0&&d===0&&u!==0&&l.push(h);return{current:s,staged:[...new Set(a)],modified:[...new Set(n)],created:[...new Set(r)],deleted:[...new Set(f)],untracked:[...new Set(l)],conflicted:[],ahead:0,behind:0,tracking:null}}async function _(t,s={}){const{cache:o}=s,a=[];return await i.walk({fs:e,dir:t,cache:o,trees:[i.WORKDIR()],map:async(n,[r])=>{if(!r)return null;if(n===".")return;const f=await r.type();if(f==="tree")return await i.isIgnored({fs:e,dir:t,filepath:n})?null:void 0;if(f!=="blob"||await i.isIgnored({fs:e,dir:t,filepath:n}))return null;a.push(n)}}),a}async function j(t,s={}){const{cache:o}=s,a=await _(t,{cache:o});return a.length>0&&await i.add({fs:e,dir:t,filepath:a,parallel:!0,cache:o,force:!0}),{hasChanges:a.length>0,toAdd:a,toRemove:[]}}async function R(t,s={}){const{cache:o}=s;if(!await I(t))return j(t,{cache:o});const a=await i.statusMatrix({fs:e,dir:t,cache:o}),n=[],r=[];for(const[l,h,w,u]of a)w===2&&u!==2&&n.push(l),h===1&&w===0&&u!==0&&r.push(l);n.length>0&&await i.add({fs:e,dir:t,filepath:n,parallel:!0,cache:o,force:!0});for(const l of r)await i.remove({fs:e,dir:t,filepath:l,cache:o});return{hasChanges:n.length>0||r.length>0||a.some(([,,,l])=>l!==1),toAdd:n,toRemove:r}}async function U(t,s,o={}){const{cache:a,force:n=!1}=o,r=[],f=[];for(const l of s){const h=C.join(t,l);e.existsSync(h)?r.push(l):f.push(l)}r.length>0&&await i.add({fs:e,dir:t,filepath:r,parallel:!0,cache:a,force:n});for(const l of f)await i.remove({fs:e,dir:t,filepath:l,cache:a})}async function K(t,s){const{message:o,authorName:a,authorEmail:n,cache:r}=s,{hasChanges:f}=await R(t,{cache:r});return f?{nothingToCommit:!1,commitHash:await i.commit({fs:e,dir:t,message:o,author:T(a,n),cache:r})}:{nothingToCommit:!0}}async function z(t,s){const{message:o,authorName:a,authorEmail:n,files:r,cache:f={}}=s;return await U(t,r,{cache:f,force:!0}),(await i.statusMatrix({fs:e,dir:t,cache:f,filepaths:r})).some(([,,,u])=>u!==1)?{nothingToCommit:!1,commitHash:await i.commit({fs:e,dir:t,message:o,author:T(a,n),cache:f})}:{nothingToCommit:!0}}async function J(t,s){if(Array.isArray(s)&&s.length>0){for(const n of s)await i.resetIndex({fs:e,dir:t,filepath:n});return{files:s}}const a=(await i.statusMatrix({fs:e,dir:t})).filter(([,,,n])=>n!==1).map(([n])=>n);for(const n of a)await i.resetIndex({fs:e,dir:t,filepath:n});return{files:"all"}}async function Q(t,s){const o=await i.statusMatrix({fs:e,dir:t}),a=Array.isArray(s)&&s.length>0?new Set(s):null,n=[],r=[],f=[];for(const[l,h,w,u]of o)a&&!a.has(l)||(h!==0?(u!==1||w!==1)&&n.push(l):h===0&&u!==0?r.push(l):h===0&&u===0&&w!==0&&f.push(l));if(n.length>0&&await I(t)){const l=await D(t);for(const h of n){const w=await B(t,l,h);if(!w)continue;const u=C.join(t,h);e.mkdirSync(C.dirname(u),{recursive:!0}),e.writeFileSync(u,w.buf),await i.add({fs:e,dir:t,filepath:h})}}for(const l of r){try{await i.remove({fs:e,dir:t,filepath:l})}catch{}const h=C.join(t,l);e.existsSync(h)&&await e.promises.unlink(h)}r.length>0&&await N(t,r);for(const l of f){const h=C.join(t,l);e.existsSync(h)&&await e.promises.unlink(h)}return f.length>0&&await N(t,f),{discardedCount:n.length+r.length+f.length,trackedFiles:n,newFiles:r,untrackedFiles:f}}async function X(t,s={}){const{maxCount:o=50,skip:a=0,branch:n,filePath:r}=s;if(!await I(t))return[];const f={fs:e,dir:t,depth:o+a};n&&(f.ref=n),r&&(f.filepath=r);try{return(await i.log(f)).slice(a,a+o).map(w=>({hash:w.oid,date:new Date(w.commit.author.timestamp*1e3).toISOString(),message:w.commit.message,author_name:w.commit.author.name,author_email:w.commit.author.email}))}catch(l){if(l?.code==="NotFoundError"||/NotFoundError|Could not find|unable to resolve|does not have any commits/i.test(String(l?.message||"")))return[];throw l}}async function Y(t,s={}){const{source:o="worktree",from:a,to:n,paths:r}=s,f=Array.isArray(r)&&r.length>0?new Set(r):null;let l="";const h=[];let w=0,u=0;async function d(g,p,S){const b=!!p,k=!!S;if(b&&k&&p.content===S.content)return;let c=!1;if(b&&M(p.buf)&&(c=!0),k&&!c&&M(S.buf)&&(c=!0),c){const H=b?W(p.buf).substring(0,7):"0000000",E=k?W(S.buf).substring(0,7):"0000000",F=[`diff --git a/${g} b/${g}`];b?k?F.push(`index ${H}..${E} 100644`):(F.push("deleted file mode 100644"),F.push(`index ${H}..0000000`)):(F.push("new file mode 100644"),F.push(`index 0000000..${E}`)),F.push(`Binary files ${b?`a/${g}`:"/dev/null"} and ${k?`b/${g}`:"/dev/null"} differ`),l+=F.join(`
6
+ `,insertions:d,deletions:g}}async function G(t,s){const{authorName:o,authorEmail:a,defaultBranch:n="main"}=s;await r.init({fs:e,dir:t,defaultBranch:n}),await r.setConfig({fs:e,dir:t,path:"user.name",value:o}),await r.setConfig({fs:e,dir:t,path:"user.email",value:a})}async function q(t){const s=await r.currentBranch({fs:e,dir:t,fullname:!1}),o=await r.statusMatrix({fs:e,dir:t}),a=[],n=[],c=[],i=[],f=[];for(const[u,w,h,d]of o)w!==d&&a.push(u),w===0&&d!==0&&c.push(u),(w===1&&d===0||h===0&&d!==0)&&i.push(u),d!==0&&h!==0&&h!==d&&n.push(u),w===0&&d===0&&h!==0&&f.push(u);return{current:s,staged:[...new Set(a)],modified:[...new Set(n)],created:[...new Set(c)],deleted:[...new Set(i)],untracked:[...new Set(f)],conflicted:[],ahead:0,behind:0,tracking:null}}async function R(t,s={}){const{cache:o}=s,a=[];return await r.walk({fs:e,dir:t,cache:o,trees:[r.WORKDIR()],map:async(n,[c])=>{if(!c)return null;if(n===".")return;const i=await c.type();if(i==="tree")return await r.isIgnored({fs:e,dir:t,filepath:n})?null:void 0;if(i!=="blob"||await r.isIgnored({fs:e,dir:t,filepath:n}))return null;a.push(n)}}),a}async function L(t,s={}){const{cache:o}=s,a=await R(t,{cache:o});return a.length>0&&await r.add({fs:e,dir:t,filepath:a,parallel:!0,cache:o,force:!0}),{hasChanges:a.length>0,toAdd:a,toRemove:[]}}async function O(t,s={}){const{cache:o}=s;if(!await T(t))return L(t,{cache:o});const a=await r.statusMatrix({fs:e,dir:t,cache:o}),n=[],c=[];for(const[f,u,w,h]of a)w===2&&h!==2&&n.push(f),u===1&&w===0&&h!==0&&c.push(f);n.length>0&&await r.add({fs:e,dir:t,filepath:n,parallel:!0,cache:o,force:!0});for(const f of c)await r.remove({fs:e,dir:t,filepath:f,cache:o});return{hasChanges:n.length>0||c.length>0||a.some(([,,,f])=>f!==1),toAdd:n,toRemove:c}}async function _(t,s,o={}){const{cache:a,force:n=!1}=o,c=[],i=[];for(const f of s){const u=A.join(t,f);e.existsSync(u)?c.push(f):i.push(f)}c.length>0&&await r.add({fs:e,dir:t,filepath:c,parallel:!0,cache:a,force:n});for(const f of i)await r.remove({fs:e,dir:t,filepath:f,cache:a})}async function K(t,s){const{message:o,authorName:a,authorEmail:n,cache:c}=s,{hasChanges:i}=await O(t,{cache:c});return i?{nothingToCommit:!1,commitHash:await r.commit({fs:e,dir:t,message:o,author:$(a,n),cache:c})}:{nothingToCommit:!0}}async function z(t,s){const{message:o,authorName:a,authorEmail:n,files:c,cache:i={}}=s;return await _(t,c,{cache:i,force:!0}),(await r.statusMatrix({fs:e,dir:t,cache:i,filepaths:c})).some(([,,,h])=>h!==1)?{nothingToCommit:!1,commitHash:await r.commit({fs:e,dir:t,message:o,author:$(a,n),cache:i})}:{nothingToCommit:!0}}async function J(t,s){if(Array.isArray(s)&&s.length>0){for(const n of s)await r.resetIndex({fs:e,dir:t,filepath:n});return{files:s}}const a=(await r.statusMatrix({fs:e,dir:t})).filter(([,,,n])=>n!==1).map(([n])=>n);for(const n of a)await r.resetIndex({fs:e,dir:t,filepath:n});return{files:"all"}}async function Q(t,s){const o=await r.statusMatrix({fs:e,dir:t}),a=Array.isArray(s)&&s.length>0?new Set(s):null,n=[],c=[],i=[];for(const[f,u,w,h]of o)a&&!a.has(f)||(u!==0?(h!==1||w!==1)&&n.push(f):u===0&&h!==0?c.push(f):u===0&&h===0&&w!==0&&i.push(f));if(n.length>0&&await T(t)){const f=await W(t);for(const u of n){const w=await N(t,f,u);if(!w)continue;const h=A.join(t,u);e.mkdirSync(A.dirname(h),{recursive:!0}),e.writeFileSync(h,w.buf),await r.add({fs:e,dir:t,filepath:u})}}for(const f of c){try{await r.remove({fs:e,dir:t,filepath:f})}catch{}const u=A.join(t,f);e.existsSync(u)&&await e.promises.unlink(u)}c.length>0&&await D(t,c);for(const f of i){const u=A.join(t,f);e.existsSync(u)&&await e.promises.unlink(u)}return i.length>0&&await D(t,i),{discardedCount:n.length+c.length+i.length,trackedFiles:n,newFiles:c,untrackedFiles:i}}async function X(t,s={}){const{maxCount:o=50,skip:a=0,branch:n,filePath:c}=s;if(!await T(t))return[];const i={fs:e,dir:t,depth:o+a};n&&(i.ref=n),c&&(i.filepath=c);try{return(await r.log(i)).slice(a,a+o).map(w=>({hash:w.oid,date:new Date(w.commit.author.timestamp*1e3).toISOString(),message:w.commit.message,author_name:w.commit.author.name,author_email:w.commit.author.email}))}catch(f){if(f?.code==="NotFoundError"||/NotFoundError|Could not find|unable to resolve|does not have any commits/i.test(String(f?.message||"")))return[];throw f}}async function Y(t,s={}){const{source:o="worktree",from:a,to:n,paths:c}=s,i=Array.isArray(c)&&c.length>0?new Set(c):null;let f="";const u=[];let w=0,h=0;async function d(g,p,S){const b=!!p,E=!!S;if(b&&E&&p.content===S.content)return;let l=!1;if(b&&M(p.buf)&&(l=!0),E&&!l&&M(S.buf)&&(l=!0),l){const k=b?B(p.buf).substring(0,7):"0000000",C=E?B(S.buf).substring(0,7):"0000000",F=[`diff --git a/${g} b/${g}`];b?E?F.push(`index ${k}..${C} 100644`):(F.push("deleted file mode 100644"),F.push(`index ${k}..0000000`)):(F.push("new file mode 100644"),F.push(`index 0000000..${C}`)),F.push(`Binary files ${b?`a/${g}`:"/dev/null"} and ${E?`b/${g}`:"/dev/null"} differ`),f+=F.join(`
7
7
  `)+`
8
- `,h.push({file:g,changes:0,insertions:0,deletions:0,binary:!0});return}const{diff:y,insertions:m,deletions:x}=G(g,b?p.content:"",k?S.content:"",b,k,b?p.buf:null,k?S.buf:null);l+=y,h.push({file:g,changes:m+x,insertions:m,deletions:x,binary:!1}),w+=m,u+=x}if(o==="commit"){let g,p;if(a&&n)g=a,p=n;else if(a){const c=await i.readCommit({fs:e,dir:t,oid:a});c.commit.parent&&c.commit.parent.length>0?(g=c.commit.parent[0],p=a):(g=null,p=a)}else{const c=new Error("source=commit requires at least 'from'");throw c.code="VALIDATION",c}const S=g?new Set(await i.listFiles({fs:e,dir:t,ref:g})):new Set,b=new Set(await i.listFiles({fs:e,dir:t,ref:p})),k=new Set([...S,...b]);for(const c of k){if(f&&!f.has(c))continue;const y=S.has(c)?await B(t,g,c):null,m=b.has(c)?await B(t,p,c):null;await d(c,y,m)}}else{if(!await I(t))return{diff:"",summary:{files:[],insertions:0,deletions:0}};const g=await D(t),p=await i.statusMatrix({fs:e,dir:t});for(const[S,b,k,c]of p){if(f&&!f.has(S))continue;if(o==="staged"){if(c===1||b===0&&c===0)continue}else if(b===0&&c===0||b===1&&k===1&&c===1)continue;const y=b!==0?await B(t,g,S):null;let m=null;if(k!==0){const x=C.join(t,S);if(e.existsSync(x))try{const H=e.readFileSync(x);m={content:H.toString("utf8"),buf:H}}catch{}}await d(S,y,m)}}return{diff:l,summary:{files:h,insertions:w,deletions:u}}}async function Z(t,s){const{ref:o,filePath:a}=s;if(o==="worktree"||o==="staged"||o===""){const n=C.join(t,a);return e.existsSync(n)?e.readFileSync(n,"utf8"):""}try{const n=await i.resolveRef({fs:e,dir:t,ref:o}),{blob:r}=await i.readBlob({fs:e,dir:t,oid:n,filepath:a});return Buffer.from(r).toString("utf8")}catch{return""}}async function tt(t,s){const{target:o,mode:a}=s;if(!await I(t)){const h=new Error("Cannot reset: repository has no commits yet");throw h.code="BUSINESS",h}const n=await i.log({fs:e,dir:t,depth:1}),r=n.length>0?n[0].oid:null,f=await i.currentBranch({fs:e,dir:t,fullname:!1});if(!f){const h=new Error("Cannot reset: detached HEAD");throw h.code="BUSINESS",h}const l=a==="hard"?new Set(await i.listFiles({fs:e,dir:t,ref:"HEAD"})):null;if(await i.writeRef({fs:e,dir:t,ref:`refs/heads/${f}`,value:o,force:!0}),a==="mixed"||a==="hard"){const h=await i.listFiles({fs:e,dir:t,ref:o}),w=new Set(h);for(const d of h)await i.resetIndex({fs:e,dir:t,filepath:d,ref:o});const u=await i.statusMatrix({fs:e,dir:t});for(const[d,,,g]of u)if(!w.has(d)&&g!==0)try{await i.remove({fs:e,dir:t,filepath:d})}catch{}}if(a==="hard"){const h=await i.listFiles({fs:e,dir:t,ref:o}),w=new Set(h);for(const u of h){const d=await B(t,o,u);if(!d)continue;const g=C.join(t,u);e.mkdirSync(C.dirname(g),{recursive:!0}),e.writeFileSync(g,d.buf)}if(l){for(const u of l)if(!w.has(u)){const d=C.join(t,u);e.existsSync(d)&&e.unlinkSync(d)}}}return{previousHead:r}}async function et(t,s){const{target:o,message:a,authorName:n,authorEmail:r,beforeCommit:f}=s;if(!await I(t)){const c=new Error("Cannot revert: repository has no commits yet");throw c.code="BUSINESS",c}let l;try{l=(await i.readCommit({fs:e,dir:t,oid:o})).oid}catch{const y=new Error("Revert target commit does not exist");throw y.code="VALIDATION",y.field="target",y.target=o,y}const h=await i.statusMatrix({fs:e,dir:t});if(h.some(([,c,y,m])=>c===0&&m===0?!1:y!==1||m!==1)){const c=h.filter(([,m])=>m!==0),y=new Error("Working directory is not clean, please commit or stash your changes before reverting");throw y.code="BUSINESS",y.staged=c.filter(([,,,m])=>m!==1).map(([m])=>m),y.modified=c.filter(([,,m])=>m!==1).map(([m])=>m),y}const u=new Set(await i.listFiles({fs:e,dir:t,ref:l})),d=await D(t),g=new Set(await i.listFiles({fs:e,dir:t,ref:d})),p=[];for(const c of u){const y=await B(t,l,c);if(!y)continue;const m=C.join(t,c);e.mkdirSync(C.dirname(m),{recursive:!0}),e.writeFileSync(m,y.buf),await i.add({fs:e,dir:t,filepath:c})}for(const c of g)if(!u.has(c)){p.push(c);try{await i.remove({fs:e,dir:t,filepath:c})}catch{}const y=C.join(t,c);e.existsSync(y)&&await e.promises.unlink(y)}return p.length>0&&await N(t,p),typeof f=="function"&&await f(),(await i.statusMatrix({fs:e,dir:t})).some(([,,,c])=>c!==1)?{nothingToCommit:!1,commitHash:await i.commit({fs:e,dir:t,message:a,author:T(n,r)}),targetOid:l,previousHead:d}:{nothingToCommit:!0,targetOid:l,previousHead:d}}async function nt(t,s){const o=await i.listFiles({fs:e,dir:t,ref:s});for(const a of o){const n=await B(t,s,a);if(!n)continue;const r=C.join(t,a);e.mkdirSync(C.dirname(r),{recursive:!0}),e.writeFileSync(r,n.buf),await i.add({fs:e,dir:t,filepath:a})}}async function at(t){return i.listTags({fs:e,dir:t})}async function st(t,s){const{tagName:o,message:a,authorName:n,authorEmail:r}=s;a?await i.annotatedTag({fs:e,dir:t,ref:o,message:a,tagger:T(n,r)}):await i.tag({fs:e,dir:t,ref:o})}async function ot(t,s){await i.deleteRef({fs:e,dir:t,ref:`refs/tags/${s}`})}async function it(t){const s=await i.listBranches({fs:e,dir:t}),o=await i.currentBranch({fs:e,dir:t,fullname:!1}),a={};for(const n of s)a[n]={name:n,current:n===o};return{branches:a,current:o}}async function rt(t,s){const{branchName:o,startPoint:a}=s;await i.branch({fs:e,dir:t,ref:o,object:a||"HEAD",checkout:!0})}async function ct(t,s){const o=await i.statusMatrix({fs:e,dir:t});if(o.some(([,n,r,f])=>n===0&&f===0?!1:r!==1||f!==1)){const n=o.filter(([,f])=>f!==0),r=new Error("Working directory is not clean, please commit or stash your changes before switching branches");throw r.code="BUSINESS",r.staged=n.filter(([,,,f])=>f!==1).map(([f])=>f),r.modified=n.filter(([,,f])=>f!==1).map(([f])=>f),r}await i.checkout({fs:e,dir:t,ref:s})}async function ft(t,s){const{branchName:o,force:a=!1}=s;if(await i.currentBranch({fs:e,dir:t,fullname:!1})===o){const r=new Error("Cannot delete the current branch, please switch to another branch first");throw r.code="BUSINESS",r}await i.deleteBranch({fs:e,dir:t,ref:o,force:a})}export{I as isoHasHead,V as isoInit,q as isoStatus,R as isoAddAll,U as isoStageFiles,K as isoCommitAll,z as isoCommitFiles,J as isoUnstage,Q as isoDiscard,X as isoLog,Y as isoDiff,Z as isoFileContent,tt as isoReset,et as isoRevertToTree,nt as isoCheckoutFiles,at as isoListTags,st as isoCreateTag,ot as isoDeleteTag,it as isoListBranches,rt as isoCreateBranch,ct as isoSwitchBranch,ft as isoDeleteBranch,_ as listWorkdirFilesSkippingIgnored,j as addAllFirstCommitWithIsomorphic};
8
+ `,u.push({file:g,changes:0,insertions:0,deletions:0,binary:!0});return}const{diff:y,insertions:m,deletions:x}=V(g,b?p.content:"",E?S.content:"",b,E,b?p.buf:null,E?S.buf:null);f+=y,u.push({file:g,changes:m+x,insertions:m,deletions:x,binary:!1}),w+=m,h+=x}if(o==="commit"){let g,p;if(a&&n)g=a,p=n;else if(a){const l=await r.readCommit({fs:e,dir:t,oid:a});l.commit.parent&&l.commit.parent.length>0?(g=l.commit.parent[0],p=a):(g=null,p=a)}else{const l=new Error("source=commit requires at least 'from'");throw l.code="VALIDATION",l}const S=g?new Set(await r.listFiles({fs:e,dir:t,ref:g})):new Set,b=new Set(await r.listFiles({fs:e,dir:t,ref:p})),E=new Set([...S,...b]);for(const l of E){if(i&&!i.has(l))continue;const y=S.has(l)?await N(t,g,l):null,m=b.has(l)?await N(t,p,l):null;await d(l,y,m)}}else{if(!await T(t))return{diff:"",summary:{files:[],insertions:0,deletions:0}};const g=await W(t),p=await r.statusMatrix({fs:e,dir:t});for(const[S,b,E,l]of p){if(i&&!i.has(S))continue;if(o==="staged"){if(l===1||b===0&&l===0)continue}else if(b===0&&l===0||b===1&&E===1&&l===1)continue;const y=b!==0?await N(t,g,S):null;let m=null;if(E!==0){const x=A.join(t,S);if(e.existsSync(x))try{const k=e.readFileSync(x);m={content:k.toString("utf8"),buf:k}}catch{}}await d(S,y,m)}}return{diff:f,summary:{files:u,insertions:w,deletions:h}}}async function Z(t,s){const{ref:o,filePath:a}=s,n=A.resolve(t),c=A.resolve(t,a||"");if(c!==n&&!c.startsWith(n+A.sep)){const i=new Error("filePath is outside the workspace");throw i.code="VALIDATION",i.field="filePath",i}if(o==="worktree"||o==="staged"||o===""){let i;try{i=e.lstatSync(c)}catch{return""}if(i.isSymbolicLink())try{return e.readlinkSync(c,"utf8")}catch(f){if(f.code==="ENOENT")return"";throw f}if(i.isDirectory()){const f=new Error("filePath is a directory, file-content only supports files");throw f.code="VALIDATION",f.field="filePath",f}try{return e.readFileSync(c,"utf8")}catch(f){if(f.code==="ENOENT")return"";if(f.code==="EISDIR"){const u=new Error("filePath is a directory, file-content only supports files");throw u.code="VALIDATION",u.field="filePath",u}throw f}}try{const i=await r.resolveRef({fs:e,dir:t,ref:o}),{blob:f}=await r.readBlob({fs:e,dir:t,oid:i,filepath:a});return Buffer.from(f).toString("utf8")}catch{return""}}async function tt(t,s){const{target:o,mode:a}=s;if(!await T(t)){const u=new Error("Cannot reset: repository has no commits yet");throw u.code="BUSINESS",u}const n=await r.log({fs:e,dir:t,depth:1}),c=n.length>0?n[0].oid:null,i=await r.currentBranch({fs:e,dir:t,fullname:!1});if(!i){const u=new Error("Cannot reset: detached HEAD");throw u.code="BUSINESS",u}const f=a==="hard"?new Set(await r.listFiles({fs:e,dir:t,ref:"HEAD"})):null;if(await r.writeRef({fs:e,dir:t,ref:`refs/heads/${i}`,value:o,force:!0}),a==="mixed"||a==="hard"){const u=await r.listFiles({fs:e,dir:t,ref:o}),w=new Set(u);for(const d of u)await r.resetIndex({fs:e,dir:t,filepath:d,ref:o});const h=await r.statusMatrix({fs:e,dir:t});for(const[d,,,g]of h)if(!w.has(d)&&g!==0)try{await r.remove({fs:e,dir:t,filepath:d})}catch{}}if(a==="hard"){const u=await r.listFiles({fs:e,dir:t,ref:o}),w=new Set(u);for(const h of u){const d=await N(t,o,h);if(!d)continue;const g=A.join(t,h);e.mkdirSync(A.dirname(g),{recursive:!0}),e.writeFileSync(g,d.buf)}if(f){for(const h of f)if(!w.has(h)){const d=A.join(t,h);e.existsSync(d)&&e.unlinkSync(d)}}}return{previousHead:c}}async function et(t,s){const{target:o,message:a,authorName:n,authorEmail:c,beforeCommit:i}=s;if(!await T(t)){const l=new Error("Cannot revert: repository has no commits yet");throw l.code="BUSINESS",l}let f;try{f=(await r.readCommit({fs:e,dir:t,oid:o})).oid}catch{const y=new Error("Revert target commit does not exist");throw y.code="VALIDATION",y.field="target",y.target=o,y}const u=await r.statusMatrix({fs:e,dir:t});if(u.some(([,l,y,m])=>l===0&&m===0?!1:y!==1||m!==1)){const l=u.filter(([,m])=>m!==0),y=new Error("Working directory is not clean, please commit or stash your changes before reverting");throw y.code="BUSINESS",y.staged=l.filter(([,,,m])=>m!==1).map(([m])=>m),y.modified=l.filter(([,,m])=>m!==1).map(([m])=>m),y}const h=new Set(await r.listFiles({fs:e,dir:t,ref:f})),d=await W(t),g=new Set(await r.listFiles({fs:e,dir:t,ref:d})),p=[];for(const l of h){const y=await N(t,f,l);if(!y)continue;const m=A.join(t,l);e.mkdirSync(A.dirname(m),{recursive:!0}),e.writeFileSync(m,y.buf),await r.add({fs:e,dir:t,filepath:l})}for(const l of g)if(!h.has(l)){p.push(l);try{await r.remove({fs:e,dir:t,filepath:l})}catch{}const y=A.join(t,l);e.existsSync(y)&&await e.promises.unlink(y)}return p.length>0&&await D(t,p),typeof i=="function"&&await i(),(await r.statusMatrix({fs:e,dir:t})).some(([,,,l])=>l!==1)?{nothingToCommit:!1,commitHash:await r.commit({fs:e,dir:t,message:a,author:$(n,c)}),targetOid:f,previousHead:d}:{nothingToCommit:!0,targetOid:f,previousHead:d}}async function nt(t,s){const o=await r.listFiles({fs:e,dir:t,ref:s});for(const a of o){const n=await N(t,s,a);if(!n)continue;const c=A.join(t,a);e.mkdirSync(A.dirname(c),{recursive:!0}),e.writeFileSync(c,n.buf),await r.add({fs:e,dir:t,filepath:a})}}async function at(t){return r.listTags({fs:e,dir:t})}async function st(t,s){const{tagName:o,message:a,authorName:n,authorEmail:c}=s;a?await r.annotatedTag({fs:e,dir:t,ref:o,message:a,tagger:$(n,c)}):await r.tag({fs:e,dir:t,ref:o})}async function ot(t,s){await r.deleteRef({fs:e,dir:t,ref:`refs/tags/${s}`})}async function it(t){const s=await r.listBranches({fs:e,dir:t}),o=await r.currentBranch({fs:e,dir:t,fullname:!1}),a={};for(const n of s)a[n]={name:n,current:n===o};return{branches:a,current:o}}async function rt(t,s){const{branchName:o,startPoint:a}=s;await r.branch({fs:e,dir:t,ref:o,object:a||"HEAD",checkout:!0})}async function ct(t,s){const o=await r.statusMatrix({fs:e,dir:t});if(o.some(([,n,c,i])=>n===0&&i===0?!1:c!==1||i!==1)){const n=o.filter(([,i])=>i!==0),c=new Error("Working directory is not clean, please commit or stash your changes before switching branches");throw c.code="BUSINESS",c.staged=n.filter(([,,,i])=>i!==1).map(([i])=>i),c.modified=n.filter(([,,i])=>i!==1).map(([i])=>i),c}await r.checkout({fs:e,dir:t,ref:s})}async function ft(t,s){const{branchName:o,force:a=!1}=s;if(await r.currentBranch({fs:e,dir:t,fullname:!1})===o){const c=new Error("Cannot delete the current branch, please switch to another branch first");throw c.code="BUSINESS",c}await r.deleteBranch({fs:e,dir:t,ref:o,force:a})}export{T as isoHasHead,G as isoInit,q as isoStatus,O as isoAddAll,_ as isoStageFiles,K as isoCommitAll,z as isoCommitFiles,J as isoUnstage,Q as isoDiscard,X as isoLog,Y as isoDiff,Z as isoFileContent,tt as isoReset,et as isoRevertToTree,nt as isoCheckoutFiles,at as isoListTags,st as isoCreateTag,ot as isoDeleteTag,it as isoListBranches,rt as isoCreateBranch,ct as isoSwitchBranch,ft as isoDeleteBranch,R as listWorkdirFilesSkippingIgnored,L as addAllFirstCommitWithIsomorphic};
@@ -1,7 +1,7 @@
1
- import tt from"cross-spawn";import v from"path";import y from"fs";import L from"../../appConfig/index.js";let U=null,G=0;const et=30*1e3,nt=10*60*1e3;function rt(){U=null,G=0}function W(){return L.GIT_USE_NATIVE!==!1}function ot(t){if(!t||typeof t!="object")return!1;const e=t;if(e.code==="ENOENT"||e.code==="NATIVE_GIT_UNAVAILABLE")return!0;const n=`${e.message||""} ${e.stderr||""}`;return/spawn\s+git(\.exe)?\s+ENOENT|git(\.exe)?:?\s*command not found|git(\.exe)?\s+not found|is not recognized as an internal or external command/i.test(n)}function j(){U=null,G=Date.now()+et}function u(t,e,n={}){const{allowFailure:r=!1,env:o={},timeoutMs:i=nt}=n;return new Promise((a,s)=>{const c=tt("git",e,{cwd:t,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...o},windowsHide:!0});let f="",l="",w=!1,C=!1,h=null;const p=i>0?setTimeout(()=>{C=!0;try{c.kill("SIGTERM")}catch{}h=setTimeout(()=>{try{c.kill("SIGKILL")}catch{}},2e3)},i):null,m=d=>{w||(w=!0,p&&clearTimeout(p),h&&clearTimeout(h),d())};c.stdout?.on("data",d=>{f+=d.toString()}),c.stderr?.on("data",d=>{l+=d.toString()}),c.on("error",d=>{m(()=>{if(r){a({stdout:f,stderr:l||d.message,exitCode:1});return}s(d)})}),c.on("close",d=>{m(()=>{if(C){const x=new Error(`git ${e.join(" ")} timed out after ${i}ms`);if(x.code="ETIMEDOUT",x.exitCode=-1,x.stdout=f,x.stderr=l,r){a({stdout:f,stderr:l||x.message,exitCode:-1});return}s(x);return}const g=d??1;if(g!==0&&!r){const x=(l||f||"").trim()||`git ${e.join(" ")} failed`,T=new Error(x);T.exitCode=g,T.stdout=f,T.stderr=l,s(T);return}a({stdout:f,stderr:l,exitCode:g})})})})}function F(t,e){return{GIT_AUTHOR_NAME:t,GIT_AUTHOR_EMAIL:e,GIT_COMMITTER_NAME:t,GIT_COMMITTER_EMAIL:e}}async function q(){if(!W())return!1;if(U===!0)return!0;if(Date.now()<G)return!1;try{if((await u(process.cwd(),["--version"],{allowFailure:!0,timeoutMs:5e3})).exitCode===0)return U=!0,G=0,!0}catch{}return j(),!1}async function it(){return q()}async function A(t){return(await u(t,["rev-parse","--verify","HEAD"],{allowFailure:!0})).exitCode===0}async function I(t,e){const{stdout:n}=await u(t,["rev-parse",e]);return n.trim()}async function N(t,e){const{stdout:n}=await u(t,["ls-tree","-r","--name-only",e]);return n.split(`
2
- `).map(r=>r.trim()).filter(Boolean)}async function at(t,e){const{authorName:n,authorEmail:r,defaultBranch:o="main"}=e;(await u(t,["init","-b",o],{allowFailure:!0})).exitCode!==0&&(await u(t,["init"]),await u(t,["symbolic-ref","HEAD",`refs/heads/${o}`],{allowFailure:!0})),await u(t,["config","user.name",n]),await u(t,["config","user.email",r])}async function D(t){const{stdout:e}=await u(t,["status","--porcelain=v1","-b"]),n=e.split(`
3
- `).filter(p=>p.length>0);let r=null,o=null,i=0,a=0;const s=[],c=[],f=[],l=[],w=[],C=[];for(const p of n){if(p.startsWith("## ")){const R=p.slice(3).trim(),$=R.match(/\s*\[([^\]]+)\]\s*$/),P=$?$[1]:null,E=$?R.slice(0,$.index).trim():R;if(E.startsWith("HEAD (")||E==="HEAD"||/^HEAD\b/i.test(E)&&E.includes("Detached"))r=null;else if(E.startsWith("No commits yet on "))r=E.slice(18).trim()||null;else{const k=E.indexOf("...");k>=0?(r=E.slice(0,k)||null,o=E.slice(k+3)||null):r=E||null}if(P){const k=P.match(/ahead\s+(\d+)/),O=P.match(/behind\s+(\d+)/);k&&(i=parseInt(k[1],10)),O&&(a=parseInt(O[1],10))}continue}const m=p.slice(0,2);let d=p.slice(3);d.includes(" -> ")&&(d=d.split(" -> ").pop()),d=J(d);const g=m[0],x=m[1];if(m==="??"){w.push(d);continue}if(m==="!!")continue;(g==="U"||x==="U"||m==="AA"||m==="DD")&&C.push(d),g!==" "&&g!=="?"&&(s.push(d),(g==="A"||g==="C")&&f.push(d),g==="D"&&l.push(d)),(x==="M"||x==="T")&&c.push(d),x==="D"&&l.push(d)}const h=await u(t,["branch","--show-current"],{allowFailure:!0});return h.exitCode===0&&(r=h.stdout.trim()||null),{current:r,staged:[...new Set(s)],modified:[...new Set(c)],created:[...new Set(f)],deleted:[...new Set(l)],untracked:[...new Set(w)],conflicted:[...new Set(C)],ahead:i,behind:a,tracking:o}}async function V(t){await u(t,["add","-A"]);const e=await u(t,["diff","--cached","--quiet"],{allowFailure:!0});if(e.exitCode===0)return{hasChanges:!1,toAdd:[],toRemove:[]};if(e.exitCode===1)return{hasChanges:!0,toAdd:[],toRemove:[]};const n=(e.stderr||e.stdout||"").trim()||`git diff --cached --quiet failed (exit ${e.exitCode})`,r=new Error(n);throw r.exitCode=e.exitCode,r.stderr=e.stderr,r.stdout=e.stdout,r}async function z(t,e,n={}){const{force:r=!1}=n;if(!Array.isArray(e)||e.length===0)return;const o=[],i=[];for(const s of e)y.existsSync(v.join(t,s))?o.push(s):i.push(s);await st(t,r?["add","-A","-f"]:["add","-A"],o);for(const s of i){const c=await u(t,["rm","--cached","-f","--ignore-unmatch","--",_(s)],{allowFailure:!0});if(c.exitCode!==0&&!K(c)){const f=(c.stderr||c.stdout||"").trim()||`git rm --cached failed for ${s}`,l=new Error(f);throw l.exitCode=c.exitCode,l}}}function K(t){const e=`${t.stderr||""} ${t.stdout||""}`;return/did not match any file|pathspec.*did not match|No such file|exists on disk, but not in the index/i.test(e)}async function st(t,e,n){if(!n||n.length===0)return;const r=200;for(let o=0;o<n.length;o+=r){const i=n.slice(o,o+r);try{await u(t,[...e,"--",...b(i)])}catch{for(const s of i){const c=await u(t,[...e,"--",_(s)],{allowFailure:!0});if(c.exitCode===0||K(c))continue;const f=(c.stderr||c.stdout||"").trim()||`git ${e.join(" ")} failed for ${s}`,l=new Error(f);throw l.exitCode=c.exitCode,l}}}}async function ct(t,e){const{message:n,authorName:r,authorEmail:o}=e,i=F(r,o),{hasChanges:a}=await V(t);if(!a)return{nothingToCommit:!0};await u(t,["commit","-m",n],{env:i});const{stdout:s}=await u(t,["rev-parse","HEAD"]),c=s.trim();if(!c)throw new Error("Native git commit succeeded but HEAD is empty");return{nothingToCommit:!1,commitHash:c}}async function X(t,e){const{message:n,authorName:r,authorEmail:o}=e,i=await u(t,["diff","--cached","--quiet"],{allowFailure:!0});if(i.exitCode===0)return{nothingToCommit:!0};if(i.exitCode!==1){const s=(i.stderr||i.stdout||"").trim()||`git diff --cached --quiet failed (exit ${i.exitCode})`,c=new Error(s);throw c.exitCode=i.exitCode,c}await u(t,["commit","-m",n],{env:F(r,o)});const{stdout:a}=await u(t,["rev-parse","HEAD"]);return{nothingToCommit:!1,commitHash:a.trim()}}async function Y(t,e){if(!Array.isArray(e)||e.length===0){const n=await u(t,["diff","--cached","--quiet"],{allowFailure:!0});if(n.exitCode===0)return!1;if(n.exitCode===1)return!0;const r=(n.stderr||n.stdout||"").trim()||`git diff --cached --quiet failed (exit ${n.exitCode})`,o=new Error(r);throw o.exitCode=n.exitCode,o}for(let n=0;n<e.length;n+=200){const r=b(e.slice(n,n+200)),o=await u(t,["diff","--cached","--quiet","--",...r],{allowFailure:!0});if(o.exitCode===1)return!0;if(o.exitCode!==0){const i=(o.stderr||o.stdout||"").trim()||`git diff --cached --quiet failed (exit ${o.exitCode})`,a=new Error(i);throw a.exitCode=o.exitCode,a}}return!1}async function lt(t,e){const{message:n,files:r,authorName:o,authorEmail:i,force:a=!0}=e;return await z(t,r,{force:a}),await Y(t,r)?X(t,{message:n,authorName:o,authorEmail:i}):{nothingToCommit:!0}}function S(t){const e=`${t.stderr||""} ${t.stdout||""}`;return/did not match any file|pathspec.*did not match|unstaged changes after reset|No changes|ambiguous argument 'HEAD'/i.test(e)}async function M(t,e,n,r={},o=200){if(!(!n||n.length===0))for(let i=0;i<n.length;i+=o){const a=b(n.slice(i,i+o));await u(t,[...e,"--",...a],r)}}function _(t){let e=String(t||"").replace(/\\/g,"/");return e.startsWith(":(")||e.startsWith(":!")||e.startsWith(":^")?e:`:(literal)${e}`}function b(t){return(t||[]).map(_)}function J(t){const e=String(t||"");if(e.length<2||e[0]!=='"'||e[e.length-1]!=='"')return e;const n=e.slice(1,-1);let r="";for(let o=0;o<n.length;o++){const i=n[o];if(i!=="\\"){r+=i;continue}if(o+=1,o>=n.length)break;const a=n[o];switch(a){case"\\":r+="\\";break;case'"':r+='"';break;case"a":r+="\x07";break;case"b":r+="\b";break;case"t":r+=" ";break;case"n":r+=`
4
- `;break;case"v":r+="\v";break;case"f":r+="\f";break;case"r":r+="\r";break;default:if(a>="0"&&a<="7"){let s=a;o+1<n.length&&n[o+1]>="0"&&n[o+1]<="7"&&(s+=n[++o],o+1<n.length&&n[o+1]>="0"&&n[o+1]<="7"&&(s+=n[++o])),r+=String.fromCharCode(parseInt(s,8))}else r+=a;break}}return r}function Q(t){let e=String(t||"").replace(/\\/g,"/");return e.length>1&&e.endsWith("/")&&(e=e.replace(/\/+$/,"")),e}function Z(t,e){const n=[...e].map(Q).filter(Boolean),r=(t||[]).map(Q).filter(Boolean),o=new Set(r),i=new Set;for(const a of n){o.has(a)&&i.add(a);let s=v.posix.dirname(a);for(;s&&s!==".";){o.has(s)&&i.add(s);const c=v.posix.dirname(s);if(c===s)break;s=c}}for(const a of r)for(const s of n)if(s===a||s.startsWith(`${a}/`)){i.add(a);break}return[...i]}async function H(t,e,n){let r=n;if(r||(r=(await D(t)).untracked),!r||r.length===0)return;const o=Z(r,e);for(const i of o){const a=v.join(t,i);y.existsSync(a)&&await y.promises.rm(a,{recursive:!0,force:!0})}o.length>0&&await B(t,o)}async function ut(t,e){const n=await A(t);if(Array.isArray(e)&&e.length>0){if(n){let f=null;try{for(let h=0;h<e.length;h+=200){const p=b(e.slice(h,h+200)),m=await u(t,["restore","--staged","--",...p],{allowFailure:!0});if(m.exitCode!==0&&!S(m)){f=m;break}}}catch(h){f={stderr:h.message,stdout:"",exitCode:1}}if(!f)return;let l=null;for(let h=0;h<e.length;h+=200){const p=b(e.slice(h,h+200)),m=await u(t,["reset","HEAD","--",...p],{allowFailure:!0});if(m.exitCode!==0&&!S(m)){l=m;break}}if(!l)return;const w=(l.stderr||l.stdout||f.stderr||f.stdout||"").trim()||"git unstage failed",C=new Error(w);throw C.exitCode=l.exitCode||f.exitCode,C}let a=null;for(let f=0;f<e.length;f+=200){const l=b(e.slice(f,f+200)),w=await u(t,["rm","--cached","-f","--",...l],{allowFailure:!0});if(w.exitCode!==0&&!S(w)){a=w;break}}if(!a)return;const s=(a.stderr||a.stdout||"").trim()||"git unstage (rm --cached) failed",c=new Error(s);throw c.exitCode=a.exitCode,c}if(n){const a=await u(t,["restore","--staged","."],{allowFailure:!0});if(a.exitCode===0||S(a))return;const s=await u(t,["reset","HEAD"],{allowFailure:!0});if(s.exitCode===0||S(s))return;const c=(s.stderr||s.stdout||a.stderr||a.stdout||"").trim()||"git unstage all failed",f=new Error(c);throw f.exitCode=s.exitCode||a.exitCode,f}const r=await u(t,["reset"],{allowFailure:!0});if(r.exitCode===0||S(r))return;const o=(r.stderr||r.stdout||"").trim()||"git unstage all failed",i=new Error(o);throw i.exitCode=r.exitCode,i}async function B(t,e){const n=new Set;for(const o of e){let i=v.dirname(o);for(;i&&i!==".";)n.add(i),i=v.dirname(i)}const r=[...n].sort((o,i)=>{const a=o.split(/[/\\]/).length;return i.split(/[/\\]/).length-a});for(const o of r){const i=v.join(t,o);try{(await y.promises.readdir(i)).length===0&&await y.promises.rmdir(i)}catch{}}}async function ft(t,e){const n=await D(t),r=Array.isArray(e)&&e.length>0?new Set(e):null,o=[],i=[],a=[],s=new Set([...n.staged,...n.modified,...n.deleted]);for(const l of n.created)s.delete(l);for(const l of s)r&&!r.has(l)||o.push(l);const c=new Set(o);for(const l of n.created)r&&!r.has(l)||c.has(l)||i.push(l);for(const l of n.untracked)r&&!r.has(l)||c.has(l)||a.push(l);const f=await A(t);if(o.length>0&&f&&(await H(t,o,n.untracked),await M(t,["restore","--source=HEAD","--staged","--worktree"],o)),i.length>0){await M(t,["rm","-f","--cached"],i,{allowFailure:!0});for(const l of i){const w=v.join(t,l);y.existsSync(w)&&await y.promises.unlink(w)}await B(t,i)}for(const l of a){const w=v.join(t,l);y.existsSync(w)&&(y.statSync(w).isDirectory()?await y.promises.rm(w,{recursive:!0,force:!0}):await y.promises.unlink(w))}return a.length>0&&await B(t,a),{discardedCount:o.length+i.length+a.length,trackedFiles:o,newFiles:i,untrackedFiles:a}}function dt(t){return/unknown revision|bad revision|invalid object name|ambiguous argument|does not have any commits|Needed a single revision|not a valid object name|unknown revision or path not in the working tree/i.test(t)}async function ht(t,e={}){const{maxCount:n=50,skip:r=0,branch:o,filePath:i}=e;if(!await A(t))return[];const a=["log",`--skip=${r}`,"-n",String(n),"--format=%H%x00%aI%x00%B%x00%an%x00%ae%x1e"];o&&a.push(o),i&&a.push("--",_(i));const s=await u(t,a,{allowFailure:!0});if(s.exitCode!==0){const f=(s.stderr||s.stdout||"").trim();if(dt(f))return[];const l=new Error(f||`git log failed (exit ${s.exitCode})`);throw l.exitCode=s.exitCode,l.stderr=s.stderr,l.stdout=s.stdout,l}return s.stdout.split("").filter(f=>f.trim()).map(f=>{const l=f.replace(/^\n/,"").split("\0"),[w,C,h,p,m]=l;let d="";if(C){const g=new Date(C);d=Number.isNaN(g.getTime())?C:g.toISOString()}return{hash:(w||"").trim(),date:d,message:(h||"").replace(/\n$/,""),author_name:p||"",author_email:m||""}}).filter(f=>f.hash)}function mt(t){const e=[];for(const n of t.split(`
5
- `)){if(!n.trim())continue;const r=n.split(" ");if(r.length<3)continue;const[o,i,a]=r,s=o==="-"||i==="-",c=s?0:parseInt(o,10)||0,f=s?0:parseInt(i,10)||0;e.push({file:a,changes:c+f,insertions:c,deletions:f,binary:s})}return e}async function wt(t,e={}){const{source:n="worktree",from:r,to:o,paths:i}=e,a=Array.isArray(i)&&i.length>0?["--",...b(i)]:[];if(n!=="commit"&&!await A(t))return{diff:"",summary:{files:[],insertions:0,deletions:0}};let s,c;if(n==="commit")if(r&&o)s=["diff",r,o,...a],c=["diff","--numstat",r,o,...a];else if(r){const d=((await u(t,["rev-list","--parents","-n","1",r],{allowFailure:!0})).stdout||"").trim().split(/\s+/).filter(Boolean);if(d.length<=1){const g=await u(t,["hash-object","-t","tree","/dev/null"],{allowFailure:!0});s=["show","--format=","--patch",r,...a],c=["show","--format=","--numstat",r,...a]}else{const g=d[1];s=["diff",g,r,...a],c=["diff","--numstat",g,r,...a]}}else{const m=new Error("source=commit requires at least 'from'");throw m.code="VALIDATION",m}else n==="staged"?(s=["diff","--cached",...a],c=["diff","--cached","--numstat",...a]):(s=["diff","HEAD",...a],c=["diff","HEAD","--numstat",...a]);const[f,l]=await Promise.all([u(t,s,{allowFailure:!0}),u(t,c,{allowFailure:!0})]),w=f.exitCode===0||f.exitCode===1?f.stdout:"";if(f.exitCode>1&&!w)throw new Error((f.stderr||f.stdout||"git diff failed").trim());const C=l.exitCode===0||l.exitCode===1?mt(l.stdout):[];let h=0,p=0;for(const m of C)h+=m.insertions,p+=m.deletions;return{diff:w,summary:{files:C,insertions:h,deletions:p}}}async function gt(t,e){const{ref:n,filePath:r}=e;if(n==="worktree"||n==="staged"||n===""){const i=v.join(t,r);return y.existsSync(i)?y.readFileSync(i,"utf8"):""}const o=await u(t,["show",`${n}:${r}`],{allowFailure:!0});return o.exitCode!==0?"":o.stdout}async function Ct(t,e){const{target:n,mode:r}=e;if(!await A(t)){const s=new Error("Cannot reset: repository has no commits yet");throw s.code="BUSINESS",s}const o=await u(t,["branch","--show-current"],{allowFailure:!0});if(!(o.exitCode===0?o.stdout.trim():"")){const s=new Error("Cannot reset: detached HEAD");throw s.code="BUSINESS",s}const a=await I(t,"HEAD");if(r==="hard"){let s=[];try{s=await N(t,n)}catch{s=[]}s.length>0&&await H(t,s)}return await u(t,["reset",`--${r}`,n]),{previousHead:a}}async function pt(t,e){const{target:n,message:r,authorName:o,authorEmail:i,beforeCommit:a}=e;if(!await A(t)){const d=new Error("Cannot revert: repository has no commits yet");throw d.code="BUSINESS",d}let s;try{s=await I(t,n)}catch{const g=new Error("Revert target commit does not exist");throw g.code="VALIDATION",g.field="target",g.target=n,g}const c=await D(t);if(c.staged.length>0||c.modified.length>0||c.deleted.length>0||c.created.length>0||c.conflicted.length>0){const d=new Error("Working directory is not clean, please commit or stash your changes before reverting");throw d.code="BUSINESS",d.staged=c.staged,d.modified=c.modified,d}const l=await I(t,"HEAD"),w=new Set(await N(t,l)),C=new Set(await N(t,s));C.size>0&&(await H(t,C,c.untracked),await u(t,["restore",`--source=${s}`,"--worktree","--staged","."]));const h=[...w].filter(d=>!C.has(d));return h.length>0&&(await M(t,["rm","-f"],h),await B(t,h)),typeof a=="function"&&await a(),(await u(t,["diff","--cached","--quiet"],{allowFailure:!0})).exitCode===0?{nothingToCommit:!0,targetOid:s,previousHead:l}:(await u(t,["commit","-m",r],{env:F(o,i)}),{nothingToCommit:!1,commitHash:await I(t,"HEAD"),targetOid:s,previousHead:l})}async function xt(t,e){const n=await N(t,e);n.length!==0&&(await H(t,n),await M(t,["restore",`--source=${e}`,"--worktree","--staged"],n))}async function yt(t){const{stdout:e}=await u(t,["tag","--list"]);return e.split(`
6
- `).map(n=>n.trim()).filter(Boolean)}async function Et(t,e){const{tagName:n,message:r,authorName:o,authorEmail:i}=e;r?await u(t,["tag","-a",n,"-m",r],{env:F(o||L.GIT_DEFAULT_AUTHOR_NAME,i||L.GIT_DEFAULT_AUTHOR_EMAIL)}):await u(t,["tag",n])}async function vt(t,e){await u(t,["tag","-d",e])}async function bt(t){const{stdout:e}=await u(t,["branch","--format=%(refname:short)"]),n=e.split(`
7
- `).map(a=>a.trim()).filter(Boolean),r=await u(t,["branch","--show-current"],{allowFailure:!0}),o=r.exitCode===0&&r.stdout.trim()?r.stdout.trim():null,i={};for(const a of n)i[a]={name:a,current:a===o};return{branches:i,current:o}}async function At(t,e){const{branchName:n,startPoint:r}=e;r?await u(t,["checkout","-b",n,r]):await u(t,["checkout","-b",n])}async function kt(t,e){const n=await D(t);if(n.staged.length>0||n.modified.length>0||n.deleted.length>0||n.created.length>0||n.conflicted.length>0){const o=new Error("Working directory is not clean, please commit or stash your changes before switching branches");throw o.code="BUSINESS",o.staged=n.staged,o.modified=n.modified,o}await u(t,["checkout",e])}async function St(t,e){const{branchName:n,force:r=!1}=e;if((await u(t,["branch","--show-current"],{allowFailure:!0})).stdout.trim()===n){const i=new Error("Cannot delete the current branch, please switch to another branch first");throw i.code="BUSINESS",i}await u(t,["branch",r?"-D":"-d",n])}export{W as isNativeGitEnabled,q as isNativeGitAvailable,it as shouldUseNativeGit,ot as isNativeGitUnavailableError,j as markNativeGitMissing,u as runGit,F as buildAuthorEnv,A as nativeHasHead,I as nativeResolveOid,N as nativeListFiles,at as nativeInit,D as nativeStatus,V as nativeAddAll,z as nativeStageFiles,ct as nativeAddAllAndCommit,X as nativeCommitStaged,lt as nativeCommitFiles,Y as nativeHasStagedChangesForPaths,_ as toLiteralPathspec,b as toLiteralPathspecs,ut as nativeUnstage,ft as nativeDiscard,ht as nativeLog,wt as nativeDiff,gt as nativeFileContent,Ct as nativeReset,pt as nativeRevertToTree,xt as nativeCheckoutFiles,yt as nativeListTags,Et as nativeCreateTag,vt as nativeDeleteTag,bt as nativeListBranches,At as nativeCreateBranch,kt as nativeSwitchBranch,St as nativeDeleteBranch,rt as resetNativeGitAvailabilityCache,B as cleanEmptyParentDirs,Z as collectUntrackedRestoreBlockers,H as removeUntrackedBlockingRestore,J as decodeGitPorcelainPath};
1
+ import tt from"cross-spawn";import E from"path";import y from"fs";import O from"../../appConfig/index.js";let $=null,R=0;const et=30*1e3,nt=10*60*1e3;function rt(){$=null,R=0}function q(){return O.GIT_USE_NATIVE!==!1}function ot(t){if(!t||typeof t!="object")return!1;const e=t;if(e.code==="ENOENT"||e.code==="NATIVE_GIT_UNAVAILABLE")return!0;const n=`${e.message||""} ${e.stderr||""}`;return/spawn\s+git(\.exe)?\s+ENOENT|git(\.exe)?:?\s*command not found|git(\.exe)?\s+not found|is not recognized as an internal or external command/i.test(n)}function V(){$=null,R=Date.now()+et}function f(t,e,n={}){const{allowFailure:r=!1,env:a={},timeoutMs:i=nt}=n;return new Promise((o,s)=>{const c=tt("git",["-c","core.quotePath=false",...e],{cwd:t,env:{...process.env,GIT_TERMINAL_PROMPT:"0",...a},windowsHide:!0});let l="",u="",w=!1,p=!1,h=null;const C=i>0?setTimeout(()=>{p=!0;try{c.kill("SIGTERM")}catch{}h=setTimeout(()=>{try{c.kill("SIGKILL")}catch{}},2e3)},i):null,m=d=>{w||(w=!0,C&&clearTimeout(C),h&&clearTimeout(h),d())};c.stdout?.on("data",d=>{l+=d.toString()}),c.stderr?.on("data",d=>{u+=d.toString()}),c.on("error",d=>{m(()=>{if(r){o({stdout:l,stderr:u||d.message,exitCode:1});return}s(d)})}),c.on("close",d=>{m(()=>{if(p){const x=new Error(`git ${e.join(" ")} timed out after ${i}ms`);if(x.code="ETIMEDOUT",x.exitCode=-1,x.stdout=l,x.stderr=u,r){o({stdout:l,stderr:u||x.message,exitCode:-1});return}s(x);return}const g=d??1;if(g!==0&&!r){const x=(u||l||"").trim()||`git ${e.join(" ")} failed`,T=new Error(x);T.exitCode=g,T.stdout=l,T.stderr=u,s(T);return}o({stdout:l,stderr:u,exitCode:g})})})})}function I(t,e){return{GIT_AUTHOR_NAME:t,GIT_AUTHOR_EMAIL:e,GIT_COMMITTER_NAME:t,GIT_COMMITTER_EMAIL:e}}async function j(){if(!q())return!1;if($===!0)return!0;if(Date.now()<R)return!1;try{if((await f(process.cwd(),["--version"],{allowFailure:!0,timeoutMs:5e3})).exitCode===0)return $=!0,R=0,!0}catch{}return V(),!1}async function it(){return j()}async function A(t){return(await f(t,["rev-parse","--verify","HEAD"],{allowFailure:!0})).exitCode===0}async function N(t,e){const{stdout:n}=await f(t,["rev-parse",e]);return n.trim()}async function F(t,e){const{stdout:n}=await f(t,["ls-tree","-r","--name-only",e]);return n.split(`
2
+ `).map(r=>r.trim()).filter(Boolean).map(r=>G(r))}async function at(t,e){const{authorName:n,authorEmail:r,defaultBranch:a="main"}=e;(await f(t,["init","-b",a],{allowFailure:!0})).exitCode!==0&&(await f(t,["init"]),await f(t,["symbolic-ref","HEAD",`refs/heads/${a}`],{allowFailure:!0})),await f(t,["config","user.name",n]),await f(t,["config","user.email",r])}async function D(t){const{stdout:e}=await f(t,["status","--porcelain=v1","-b"]),n=e.split(`
3
+ `).filter(C=>C.length>0);let r=null,a=null,i=0,o=0;const s=[],c=[],l=[],u=[],w=[],p=[];for(const C of n){if(C.startsWith("## ")){const M=C.slice(3).trim(),B=M.match(/\s*\[([^\]]+)\]\s*$/),L=B?B[1]:null,v=B?M.slice(0,B.index).trim():M;if(v.startsWith("HEAD (")||v==="HEAD"||/^HEAD\b/i.test(v)&&v.includes("Detached"))r=null;else if(v.startsWith("No commits yet on "))r=v.slice(18).trim()||null;else{const S=v.indexOf("...");S>=0?(r=v.slice(0,S)||null,a=v.slice(S+3)||null):r=v||null}if(L){const S=L.match(/ahead\s+(\d+)/),W=L.match(/behind\s+(\d+)/);S&&(i=parseInt(S[1],10)),W&&(o=parseInt(W[1],10))}continue}const m=C.slice(0,2);let d=C.slice(3);d.includes(" -> ")&&(d=d.split(" -> ").pop()),d=G(d);const g=m[0],x=m[1];if(m==="??"){w.push(d);continue}if(m==="!!")continue;(g==="U"||x==="U"||m==="AA"||m==="DD")&&p.push(d),g!==" "&&g!=="?"&&(s.push(d),(g==="A"||g==="C")&&l.push(d),g==="D"&&u.push(d)),(x==="M"||x==="T")&&c.push(d),x==="D"&&u.push(d)}const h=await f(t,["branch","--show-current"],{allowFailure:!0});return h.exitCode===0&&(r=h.stdout.trim()||null),{current:r,staged:[...new Set(s)],modified:[...new Set(c)],created:[...new Set(l)],deleted:[...new Set(u)],untracked:[...new Set(w)],conflicted:[...new Set(p)],ahead:i,behind:o,tracking:a}}async function z(t){await f(t,["add","-A"]);const e=await f(t,["diff","--cached","--quiet"],{allowFailure:!0});if(e.exitCode===0)return{hasChanges:!1,toAdd:[],toRemove:[]};if(e.exitCode===1)return{hasChanges:!0,toAdd:[],toRemove:[]};const n=(e.stderr||e.stdout||"").trim()||`git diff --cached --quiet failed (exit ${e.exitCode})`,r=new Error(n);throw r.exitCode=e.exitCode,r.stderr=e.stderr,r.stdout=e.stdout,r}async function K(t,e,n={}){const{force:r=!1}=n;if(!Array.isArray(e)||e.length===0)return;const a=[],i=[];for(const s of e)y.existsSync(E.join(t,s))?a.push(s):i.push(s);await st(t,r?["add","-A","-f"]:["add","-A"],a);for(const s of i){const c=await f(t,["rm","--cached","-f","--ignore-unmatch","--",_(s)],{allowFailure:!0});if(c.exitCode!==0&&!X(c)){const l=(c.stderr||c.stdout||"").trim()||`git rm --cached failed for ${s}`,u=new Error(l);throw u.exitCode=c.exitCode,u}}}function X(t){const e=`${t.stderr||""} ${t.stdout||""}`;return/did not match any file|pathspec.*did not match|No such file|exists on disk, but not in the index/i.test(e)}async function st(t,e,n){if(!n||n.length===0)return;const r=200;for(let a=0;a<n.length;a+=r){const i=n.slice(a,a+r);try{await f(t,[...e,"--",...b(i)])}catch{for(const s of i){const c=await f(t,[...e,"--",_(s)],{allowFailure:!0});if(c.exitCode===0||X(c))continue;const l=(c.stderr||c.stdout||"").trim()||`git ${e.join(" ")} failed for ${s}`,u=new Error(l);throw u.exitCode=c.exitCode,u}}}}async function ct(t,e){const{message:n,authorName:r,authorEmail:a}=e,i=I(r,a),{hasChanges:o}=await z(t);if(!o)return{nothingToCommit:!0};await f(t,["commit","-m",n],{env:i});const{stdout:s}=await f(t,["rev-parse","HEAD"]),c=s.trim();if(!c)throw new Error("Native git commit succeeded but HEAD is empty");return{nothingToCommit:!1,commitHash:c}}async function Y(t,e){const{message:n,authorName:r,authorEmail:a}=e,i=await f(t,["diff","--cached","--quiet"],{allowFailure:!0});if(i.exitCode===0)return{nothingToCommit:!0};if(i.exitCode!==1){const s=(i.stderr||i.stdout||"").trim()||`git diff --cached --quiet failed (exit ${i.exitCode})`,c=new Error(s);throw c.exitCode=i.exitCode,c}await f(t,["commit","-m",n],{env:I(r,a)});const{stdout:o}=await f(t,["rev-parse","HEAD"]);return{nothingToCommit:!1,commitHash:o.trim()}}async function J(t,e){if(!Array.isArray(e)||e.length===0){const n=await f(t,["diff","--cached","--quiet"],{allowFailure:!0});if(n.exitCode===0)return!1;if(n.exitCode===1)return!0;const r=(n.stderr||n.stdout||"").trim()||`git diff --cached --quiet failed (exit ${n.exitCode})`,a=new Error(r);throw a.exitCode=n.exitCode,a}for(let n=0;n<e.length;n+=200){const r=b(e.slice(n,n+200)),a=await f(t,["diff","--cached","--quiet","--",...r],{allowFailure:!0});if(a.exitCode===1)return!0;if(a.exitCode!==0){const i=(a.stderr||a.stdout||"").trim()||`git diff --cached --quiet failed (exit ${a.exitCode})`,o=new Error(i);throw o.exitCode=a.exitCode,o}}return!1}async function lt(t,e){const{message:n,files:r,authorName:a,authorEmail:i,force:o=!0}=e;return await K(t,r,{force:o}),await J(t,r)?Y(t,{message:n,authorName:a,authorEmail:i}):{nothingToCommit:!0}}function k(t){const e=`${t.stderr||""} ${t.stdout||""}`;return/did not match any file|pathspec.*did not match|unstaged changes after reset|No changes|ambiguous argument 'HEAD'/i.test(e)}async function U(t,e,n,r={},a=200){if(!(!n||n.length===0))for(let i=0;i<n.length;i+=a){const o=b(n.slice(i,i+a));await f(t,[...e,"--",...o],r)}}function _(t){let e=String(t||"").replace(/\\/g,"/");return e.startsWith(":(")||e.startsWith(":!")||e.startsWith(":^")?e:`:(literal)${e}`}function b(t){return(t||[]).map(_)}function G(t){const e=String(t||"");if(e.length<2||e[0]!=='"'||e[e.length-1]!=='"')return e;const n=e.slice(1,-1);let r="",a=null;const i=()=>{if(a&&a.length){const o=Buffer.from(a),s=o.toString("utf8");r+=s.includes("\uFFFD")?o.toString("latin1"):s}a=null};for(let o=0;o<n.length;o++){const s=n[o];if(s!=="\\"){i(),r+=s;continue}if(o+=1,o>=n.length)break;const c=n[o];switch(c){case"\\":i(),r+="\\";break;case'"':i(),r+='"';break;case"a":i(),r+="\x07";break;case"b":i(),r+="\b";break;case"t":i(),r+=" ";break;case"n":i(),r+=`
4
+ `;break;case"v":i(),r+="\v";break;case"f":i(),r+="\f";break;case"r":i(),r+="\r";break;default:if(c>="0"&&c<="7"){let l=c;o+1<n.length&&n[o+1]>="0"&&n[o+1]<="7"&&(l+=n[++o],o+1<n.length&&n[o+1]>="0"&&n[o+1]<="7"&&(l+=n[++o])),(a??=[]).push(parseInt(l,8)&255)}else i(),r+=c;break}}return i(),r}function Q(t){let e=String(t||"").replace(/\\/g,"/");return e.length>1&&e.endsWith("/")&&(e=e.replace(/\/+$/,"")),e}function Z(t,e){const n=[...e].map(Q).filter(Boolean),r=(t||[]).map(Q).filter(Boolean),a=new Set(r),i=new Set;for(const o of n){a.has(o)&&i.add(o);let s=E.posix.dirname(o);for(;s&&s!==".";){a.has(s)&&i.add(s);const c=E.posix.dirname(s);if(c===s)break;s=c}}for(const o of r)for(const s of n)if(s===o||s.startsWith(`${o}/`)){i.add(o);break}return[...i]}async function H(t,e,n){let r=n;if(r||(r=(await D(t)).untracked),!r||r.length===0)return;const a=Z(r,e);for(const i of a){const o=E.join(t,i);y.existsSync(o)&&await y.promises.rm(o,{recursive:!0,force:!0})}a.length>0&&await P(t,a)}async function ut(t,e){const n=await A(t);if(Array.isArray(e)&&e.length>0){if(n){let l=null;try{for(let h=0;h<e.length;h+=200){const C=b(e.slice(h,h+200)),m=await f(t,["restore","--staged","--",...C],{allowFailure:!0});if(m.exitCode!==0&&!k(m)){l=m;break}}}catch(h){l={stderr:h.message,stdout:"",exitCode:1}}if(!l)return;let u=null;for(let h=0;h<e.length;h+=200){const C=b(e.slice(h,h+200)),m=await f(t,["reset","HEAD","--",...C],{allowFailure:!0});if(m.exitCode!==0&&!k(m)){u=m;break}}if(!u)return;const w=(u.stderr||u.stdout||l.stderr||l.stdout||"").trim()||"git unstage failed",p=new Error(w);throw p.exitCode=u.exitCode||l.exitCode,p}let o=null;for(let l=0;l<e.length;l+=200){const u=b(e.slice(l,l+200)),w=await f(t,["rm","--cached","-f","--",...u],{allowFailure:!0});if(w.exitCode!==0&&!k(w)){o=w;break}}if(!o)return;const s=(o.stderr||o.stdout||"").trim()||"git unstage (rm --cached) failed",c=new Error(s);throw c.exitCode=o.exitCode,c}if(n){const o=await f(t,["restore","--staged","."],{allowFailure:!0});if(o.exitCode===0||k(o))return;const s=await f(t,["reset","HEAD"],{allowFailure:!0});if(s.exitCode===0||k(s))return;const c=(s.stderr||s.stdout||o.stderr||o.stdout||"").trim()||"git unstage all failed",l=new Error(c);throw l.exitCode=s.exitCode||o.exitCode,l}const r=await f(t,["reset"],{allowFailure:!0});if(r.exitCode===0||k(r))return;const a=(r.stderr||r.stdout||"").trim()||"git unstage all failed",i=new Error(a);throw i.exitCode=r.exitCode,i}async function P(t,e){const n=new Set;for(const a of e){let i=E.dirname(a);for(;i&&i!==".";)n.add(i),i=E.dirname(i)}const r=[...n].sort((a,i)=>{const o=a.split(/[/\\]/).length;return i.split(/[/\\]/).length-o});for(const a of r){const i=E.join(t,a);try{(await y.promises.readdir(i)).length===0&&await y.promises.rmdir(i)}catch{}}}async function ft(t,e){const n=await D(t),r=Array.isArray(e)&&e.length>0?new Set(e):null,a=[],i=[],o=[],s=new Set([...n.staged,...n.modified,...n.deleted]);for(const u of n.created)s.delete(u);for(const u of s)r&&!r.has(u)||a.push(u);const c=new Set(a);for(const u of n.created)r&&!r.has(u)||c.has(u)||i.push(u);for(const u of n.untracked)r&&!r.has(u)||c.has(u)||o.push(u);const l=await A(t);if(a.length>0&&l&&(await H(t,a,n.untracked),await U(t,["restore","--source=HEAD","--staged","--worktree"],a)),i.length>0){await U(t,["rm","-f","--cached"],i,{allowFailure:!0});for(const u of i){const w=E.join(t,u);y.existsSync(w)&&await y.promises.unlink(w)}await P(t,i)}for(const u of o){const w=E.join(t,u);y.existsSync(w)&&(y.statSync(w).isDirectory()?await y.promises.rm(w,{recursive:!0,force:!0}):await y.promises.unlink(w))}return o.length>0&&await P(t,o),{discardedCount:a.length+i.length+o.length,trackedFiles:a,newFiles:i,untrackedFiles:o}}function dt(t){return/unknown revision|bad revision|invalid object name|ambiguous argument|does not have any commits|Needed a single revision|not a valid object name|unknown revision or path not in the working tree/i.test(t)}async function ht(t,e={}){const{maxCount:n=50,skip:r=0,branch:a,filePath:i}=e;if(!await A(t))return[];const o=["log",`--skip=${r}`,"-n",String(n),"--format=%H%x00%aI%x00%B%x00%an%x00%ae%x1e"];a&&o.push(a),i&&o.push("--",_(i));const s=await f(t,o,{allowFailure:!0});if(s.exitCode!==0){const l=(s.stderr||s.stdout||"").trim();if(dt(l))return[];const u=new Error(l||`git log failed (exit ${s.exitCode})`);throw u.exitCode=s.exitCode,u.stderr=s.stderr,u.stdout=s.stdout,u}return s.stdout.split("").filter(l=>l.trim()).map(l=>{const u=l.replace(/^\n/,"").split("\0"),[w,p,h,C,m]=u;let d="";if(p){const g=new Date(p);d=Number.isNaN(g.getTime())?p:g.toISOString()}return{hash:(w||"").trim(),date:d,message:(h||"").replace(/\n$/,""),author_name:C||"",author_email:m||""}}).filter(l=>l.hash)}function mt(t){const e=[];for(const n of t.split(`
5
+ `)){if(!n.trim())continue;const r=n.split(" ");if(r.length<3)continue;const[a,i,o]=r,s=a==="-"||i==="-",c=s?0:parseInt(a,10)||0,l=s?0:parseInt(i,10)||0;e.push({file:G(o),changes:c+l,insertions:c,deletions:l,binary:s})}return e}async function wt(t,e={}){const{source:n="worktree",from:r,to:a,paths:i}=e,o=Array.isArray(i)&&i.length>0?["--",...b(i)]:[];if(n!=="commit"&&!await A(t))return{diff:"",summary:{files:[],insertions:0,deletions:0}};let s,c;if(n==="commit")if(r&&a)s=["diff",r,a,...o],c=["diff","--numstat",r,a,...o];else if(r){const d=((await f(t,["rev-list","--parents","-n","1",r],{allowFailure:!0})).stdout||"").trim().split(/\s+/).filter(Boolean);if(d.length<=1){const g=await f(t,["hash-object","-t","tree","/dev/null"],{allowFailure:!0});s=["show","--format=","--patch",r,...o],c=["show","--format=","--numstat",r,...o]}else{const g=d[1];s=["diff",g,r,...o],c=["diff","--numstat",g,r,...o]}}else{const m=new Error("source=commit requires at least 'from'");throw m.code="VALIDATION",m}else n==="staged"?(s=["diff","--cached",...o],c=["diff","--cached","--numstat",...o]):(s=["diff","HEAD",...o],c=["diff","HEAD","--numstat",...o]);const[l,u]=await Promise.all([f(t,s,{allowFailure:!0}),f(t,c,{allowFailure:!0})]),w=l.exitCode===0||l.exitCode===1?l.stdout:"";if(l.exitCode>1&&!w)throw new Error((l.stderr||l.stdout||"git diff failed").trim());const p=u.exitCode===0||u.exitCode===1?mt(u.stdout):[];let h=0,C=0;for(const m of p)h+=m.insertions,C+=m.deletions;return{diff:w,summary:{files:p,insertions:h,deletions:C}}}async function gt(t,e){const{ref:n,filePath:r}=e,a=E.resolve(t),i=E.resolve(t,r||"");if(i!==a&&!i.startsWith(a+E.sep)){const c=new Error("filePath is outside the workspace");throw c.code="VALIDATION",c.field="filePath",c}if(n==="worktree"||n==="staged"||n===""){let c;try{c=y.lstatSync(i)}catch{return""}if(c.isSymbolicLink())try{return y.readlinkSync(i,"utf8")}catch(l){if(l.code==="ENOENT")return"";throw l}if(c.isDirectory()){const l=new Error("filePath is a directory, file-content only supports files");throw l.code="VALIDATION",l.field="filePath",l}try{return y.readFileSync(i,"utf8")}catch(l){if(l.code==="ENOENT")return"";if(l.code==="EISDIR"){const u=new Error("filePath is a directory, file-content only supports files");throw u.code="VALIDATION",u.field="filePath",u}throw l}}const o=await f(t,["cat-file","-t",`${n}:${r}`],{allowFailure:!0});if(o.exitCode!==0)return"";if(o.stdout.trim()!=="blob"){const c=new Error("filePath is not a file in this ref (directory)");throw c.code="VALIDATION",c.field="filePath",c}const s=await f(t,["show",`${n}:${r}`],{allowFailure:!0});return s.exitCode!==0?"":s.stdout}async function pt(t,e){const{target:n,mode:r}=e;if(!await A(t)){const s=new Error("Cannot reset: repository has no commits yet");throw s.code="BUSINESS",s}const a=await f(t,["branch","--show-current"],{allowFailure:!0});if(!(a.exitCode===0?a.stdout.trim():"")){const s=new Error("Cannot reset: detached HEAD");throw s.code="BUSINESS",s}const o=await N(t,"HEAD");if(r==="hard"){let s=[];try{s=await F(t,n)}catch{s=[]}s.length>0&&await H(t,s)}return await f(t,["reset",`--${r}`,n]),{previousHead:o}}async function Ct(t,e){const{target:n,message:r,authorName:a,authorEmail:i,beforeCommit:o}=e;if(!await A(t)){const d=new Error("Cannot revert: repository has no commits yet");throw d.code="BUSINESS",d}let s;try{s=await N(t,n)}catch{const g=new Error("Revert target commit does not exist");throw g.code="VALIDATION",g.field="target",g.target=n,g}const c=await D(t);if(c.staged.length>0||c.modified.length>0||c.deleted.length>0||c.created.length>0||c.conflicted.length>0){const d=new Error("Working directory is not clean, please commit or stash your changes before reverting");throw d.code="BUSINESS",d.staged=c.staged,d.modified=c.modified,d}const u=await N(t,"HEAD"),w=new Set(await F(t,u)),p=new Set(await F(t,s));p.size>0&&(await H(t,p,c.untracked),await f(t,["restore",`--source=${s}`,"--worktree","--staged","."]));const h=[...w].filter(d=>!p.has(d));return h.length>0&&(await U(t,["rm","-f","--ignore-unmatch"],h),await P(t,h)),typeof o=="function"&&await o(),(await f(t,["diff","--cached","--quiet"],{allowFailure:!0})).exitCode===0?{nothingToCommit:!0,targetOid:s,previousHead:u}:(await f(t,["commit","-m",r],{env:I(a,i)}),{nothingToCommit:!1,commitHash:await N(t,"HEAD"),targetOid:s,previousHead:u})}async function yt(t,e){const n=await F(t,e);n.length!==0&&(await H(t,n),await U(t,["restore",`--source=${e}`,"--worktree","--staged"],n))}async function xt(t){const{stdout:e}=await f(t,["tag","--list"]);return e.split(`
6
+ `).map(n=>n.trim()).filter(Boolean)}async function Et(t,e){const{tagName:n,message:r,authorName:a,authorEmail:i}=e;r?await f(t,["tag","-a",n,"-m",r],{env:I(a||O.GIT_DEFAULT_AUTHOR_NAME,i||O.GIT_DEFAULT_AUTHOR_EMAIL)}):await f(t,["tag",n])}async function vt(t,e){await f(t,["tag","-d",e])}async function bt(t){const{stdout:e}=await f(t,["branch","--format=%(refname:short)"]),n=e.split(`
7
+ `).map(o=>o.trim()).filter(Boolean),r=await f(t,["branch","--show-current"],{allowFailure:!0}),a=r.exitCode===0&&r.stdout.trim()?r.stdout.trim():null,i={};for(const o of n)i[o]={name:o,current:o===a};return{branches:i,current:a}}async function At(t,e){const{branchName:n,startPoint:r}=e;r?await f(t,["checkout","-b",n,r]):await f(t,["checkout","-b",n])}async function St(t,e){const n=await D(t);if(n.staged.length>0||n.modified.length>0||n.deleted.length>0||n.created.length>0||n.conflicted.length>0){const a=new Error("Working directory is not clean, please commit or stash your changes before switching branches");throw a.code="BUSINESS",a.staged=n.staged,a.modified=n.modified,a}await f(t,["checkout",e])}async function kt(t,e){const{branchName:n,force:r=!1}=e;if((await f(t,["branch","--show-current"],{allowFailure:!0})).stdout.trim()===n){const i=new Error("Cannot delete the current branch, please switch to another branch first");throw i.code="BUSINESS",i}await f(t,["branch",r?"-D":"-d",n])}export{q as isNativeGitEnabled,j as isNativeGitAvailable,it as shouldUseNativeGit,ot as isNativeGitUnavailableError,V as markNativeGitMissing,f as runGit,I as buildAuthorEnv,A as nativeHasHead,N as nativeResolveOid,F as nativeListFiles,at as nativeInit,D as nativeStatus,z as nativeAddAll,K as nativeStageFiles,ct as nativeAddAllAndCommit,Y as nativeCommitStaged,lt as nativeCommitFiles,J as nativeHasStagedChangesForPaths,_ as toLiteralPathspec,b as toLiteralPathspecs,ut as nativeUnstage,ft as nativeDiscard,ht as nativeLog,wt as nativeDiff,gt as nativeFileContent,pt as nativeReset,Ct as nativeRevertToTree,yt as nativeCheckoutFiles,xt as nativeListTags,Et as nativeCreateTag,vt as nativeDeleteTag,bt as nativeListBranches,At as nativeCreateBranch,St as nativeSwitchBranch,kt as nativeDeleteBranch,rt as resetNativeGitAvailabilityCache,P as cleanEmptyParentDirs,Z as collectUntrackedRestoreBlockers,H as removeUntrackedBlockingRestore,G as decodeGitPorcelainPath};
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.5.3",
4
+ "version": "1.5.5",
5
5
  "description": "Cross-platform file service deployment tool with start/stop/restart CLI commands",
6
6
  "type": "module",
7
7
  "main": "index.js",