mock-service-cli 4.3.1 → 4.3.2
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/file-explorer.html +11 -7
- package/dist/runtime.js +1 -1
- package/package.json +1 -1
package/dist/file-explorer.html
CHANGED
|
@@ -1093,7 +1093,7 @@
|
|
|
1093
1093
|
let searchQuery = '';
|
|
1094
1094
|
let sortBy = 'name';
|
|
1095
1095
|
let sortAscending = true;
|
|
1096
|
-
let showHiddenFiles =
|
|
1096
|
+
let showHiddenFiles = false;
|
|
1097
1097
|
let showBirthtime = false;
|
|
1098
1098
|
let currentPreviewContent = '';
|
|
1099
1099
|
let currentPreviewObjectUrl = null;
|
|
@@ -1638,14 +1638,18 @@
|
|
|
1638
1638
|
}
|
|
1639
1639
|
}
|
|
1640
1640
|
|
|
1641
|
+
function getDownloadUrl(filePath) {
|
|
1642
|
+
return `/__api/file?path=${encodeURIComponent(filePath)}&download=1`;
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1641
1645
|
function downloadFile(filePath, fileName) {
|
|
1642
|
-
const url = `/__api/file?path=${encodeURIComponent(filePath)}`;
|
|
1643
1646
|
const a = document.createElement('a');
|
|
1644
|
-
a.href =
|
|
1645
|
-
a.download = fileName;
|
|
1647
|
+
a.href = getDownloadUrl(filePath);
|
|
1648
|
+
a.download = fileName || '';
|
|
1649
|
+
a.style.display = 'none';
|
|
1646
1650
|
document.body.appendChild(a);
|
|
1647
1651
|
a.click();
|
|
1648
|
-
|
|
1652
|
+
a.remove();
|
|
1649
1653
|
}
|
|
1650
1654
|
|
|
1651
1655
|
async function deletePath(filePath, fileName) {
|
|
@@ -2333,7 +2337,7 @@
|
|
|
2333
2337
|
</div>
|
|
2334
2338
|
`;
|
|
2335
2339
|
} else if (BINARY_EXTS.includes(ext)) {
|
|
2336
|
-
const downloadUrl =
|
|
2340
|
+
const downloadUrl = getDownloadUrl(path);
|
|
2337
2341
|
const fileSize = fileInfo ? formatSize(fileInfo.size) : '未知大小';
|
|
2338
2342
|
|
|
2339
2343
|
body.innerHTML = `
|
|
@@ -2351,7 +2355,7 @@
|
|
|
2351
2355
|
`;
|
|
2352
2356
|
} else {
|
|
2353
2357
|
if (isLargeFile) {
|
|
2354
|
-
const downloadUrl =
|
|
2358
|
+
const downloadUrl = getDownloadUrl(path);
|
|
2355
2359
|
body.innerHTML = `
|
|
2356
2360
|
<div class="preview-container">
|
|
2357
2361
|
<div class="binary-info">
|
package/dist/runtime.js
CHANGED
|
@@ -135,7 +135,7 @@ Opening API overview page...`));let openCommand;switch(process.platform){case"da
|
|
|
135
135
|
Enable proxy at web server on:`)),Object.keys(proxyTable).forEach(prefix=>{console.info(` ${prefix} -> ${proxyTable[prefix]}`)}))})}process.platform==="win32"&&require("readline").createInterface({input:process.stdin,output:process.stdout}).on("SIGINT",function(){process.emit("SIGINT")});process.on("SIGINT",function(){log.info(colors.red("mock-server process stopped.")),process.exit()});process.on("SIGTERM",function(){log.info(colors.red("mock-server process stopped.")),process.exit()});module2.exports={composeRouteFromJsFile,parseMockFiles}}});var require_staticServer=__commonJS({"src/lib/staticServer.js"(){var express=require_express2(),colors=require_safe(),portfinder=require_portfinder(),{dateFormat,logger,getServerHost,getServerUrls}=require_utils3(),log=logger(process.env.SILENT),argv=JSON.parse(process.env.ARGV),resHeaders={};process.env.PORT?startServer():(portfinder.basePort=8090,portfinder.getPort(function(err,port){if(err)throw err;process.env.PORT=port,startServer()}));function appendResHeaders(){return(req,res,next)=>{for(let key in resHeaders)resHeaders.hasOwnProperty(key)&&res.header(key,resHeaders[key]);next()}}function startServer(){let app=express();typeof argv.A=="string"&&(argv.A.split(/\s*,\s*/).forEach(function(h){let[key,value]=h.split("=");resHeaders[key]=value},this),app.use(appendResHeaders())),app.use(express.static(process.env.STATIC_DIRECTORY)),app.listen(Number.parseInt(process.env.PORT,10),getServerHost(),()=>{console.info([colors.yellow(`
|
|
136
136
|
Starting up Static Server, serving `),colors.cyan(process.env.STATIC_DIRECTORY),colors.yellow(` ${dateFormat("YYYY-mm-dd HH:MM:SS",new Date)}`)].join("")),console.info(colors.yellow(`
|
|
137
137
|
Static Server available on:
|
|
138
|
-
`)),getServerUrls(process.env.PORT).forEach(url=>{console.info(" "+url.replace(String(process.env.PORT),colors.green(process.env.PORT)))})})}process.platform==="win32"&&require("readline").createInterface({input:process.stdin,output:process.stdout}).on("SIGINT",function(){process.emit("SIGINT")});process.on("SIGINT",function(){log.info(colors.red("static-server process stopped.")),process.exit()});process.on("SIGTERM",function(){log.info(colors.red("static-server process stopped.")),process.exit()})}});var require_fileExplorerServer=__commonJS({"src/lib/fileExplorerServer.js"(){var express=require_express2(),{existsSync,readFileSync,statSync,rmSync,mkdirSync,writeFileSync,renameSync,realpathSync,promises:fsPromises}=require("fs"),path=require("path"),colors=require_safe(),portfinder=require_portfinder(),{exec,execFile}=require("child_process"),{dateFormat,logger,getServerHost,getServerUrls}=require_utils3(),{getPackageVersion}=require_packageInfo(),app=express(),log=logger(process.env.SILENT),argv=JSON.parse(process.env.ARGV),explorerRoot=path.resolve(process.env.EXPLORER_DIRECTORY||process.cwd()),explorerRootRealPath=realpathSync(explorerRoot),port=argv.p||argv.port,isEditMode=process.env.EXPLORER_EDIT==="true";function isPathInsideRoot(fullPath,resolvedRoot=explorerRootRealPath){let relativePath=path.relative(resolvedRoot,fullPath);return relativePath===""||!relativePath.startsWith("..")&&!path.isAbsolute(relativePath)}function normalizeExplorerInputPath(inputPath){let decodedPath=decodeURIComponent(String(inputPath||"/")).replace(/\\/g,"/");return!decodedPath||decodedPath==="."?"/":decodedPath.startsWith("/")?decodedPath:`/${decodedPath}`}function resolveExplorerPath(inputPath){let relativePath=normalizeExplorerInputPath(inputPath).replace(/^\/+/,""),fullPath=path.resolve(explorerRoot,relativePath);if(!isPathInsideRoot(fullPath,explorerRoot)){let error=new Error("Access denied");throw error.statusCode=403,error}if(!existsSync(fullPath))return fullPath;let realPath=realpathSync(fullPath);if(!isPathInsideRoot(realPath)){let error=new Error("Access denied");throw error.statusCode=403,error}return realPath}function validateEntryName(name){if(typeof name!="string")return"Name must be a string";let normalizedName=name.trim();if(!normalizedName||normalizedName==="."||normalizedName==="..")return"Invalid name";if(/[/\\\0<>:"|?*]/.test(normalizedName))return"Name contains invalid characters";if(process.platform==="win32"){let upperName=normalizedName.replace(/[. ]+$/g,"").split(".")[0].toUpperCase();if(new Set(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]).has(upperName)||normalizedName.endsWith(" ")||normalizedName.endsWith("."))return"Name is not supported on Windows"}return null}function getChildPath(parentPath,name){let nameError=validateEntryName(name);if(nameError){let error=new Error(nameError);throw error.statusCode=400,error}let parentFullPath=resolveExplorerPath(parentPath||"/");if(!existsSync(parentFullPath)||!statSync(parentFullPath).isDirectory()){let error=new Error("Parent directory not found");throw error.statusCode=404,error}let childPath=path.resolve(parentFullPath,name.trim());if(!isPathInsideRoot(childPath)){let error=new Error("Access denied");throw error.statusCode=403,error}return childPath}function requireEditMode(req,res,next){if(!isEditMode)return res.status(403).json({error:"File explorer is read-only. Restart with --edit to modify files."});next()}function deleteExplorerPath(targetPath){let fullPath=resolveExplorerPath(targetPath);if(path.resolve(fullPath)===explorerRootRealPath){let error=new Error("Cannot delete explorer root");throw error.statusCode=400,error}if(!existsSync(fullPath)){let error=new Error("Path not found");throw error.statusCode=404,error}rmSync(fullPath,{recursive:!0,force:!1})}process.env.PORT?init():(portfinder.basePort=port||8090,portfinder.getPort(function(err,foundPort){if(err)throw err;process.env.PORT=foundPort,init()}));function init(){app.use(express.json()),app.get("/",(req,res)=>{let htmlPath=path.resolve(__dirname,"./file-explorer.html");existsSync(htmlPath)?res.sendFile(htmlPath):res.status(404).send("File explorer page not found")}),app.get("/__api/config",(req,res)=>{res.json({editMode:isEditMode})}),app.get("/__api/list",async(req,res)=>{let dirPath=normalizeExplorerInputPath(req.query.path||"/"),fullPath;try{fullPath=resolveExplorerPath(dirPath)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(!existsSync(fullPath))return res.status(404).json({error:"Path not found"});try{if(!(await fsPromises.lstat(fullPath)).isDirectory())return res.status(400).json({error:"Not a directory"});let files=await fsPromises.readdir(fullPath,{withFileTypes:!0}),result=await Promise.all(files.map(async file=>{let filePath=path.join(fullPath,file.name),fileStats,hasError=!1;try{fileStats=await fsPromises.lstat(filePath)}catch{hasError=!0}let relativePath=path.posix.join(dirPath,file.name),isDirectory=hasError?file.isDirectory():fileStats.isDirectory();return{name:file.name,path:relativePath.replace(/\\/g,"/"),isDirectory,size:hasError?0:fileStats.size,mtime:hasError?new Date:fileStats.mtime,birthtime:hasError?new Date:fileStats.birthtime,isHidden:file.name.startsWith("."),error:hasError?"Cannot access file":null}}));result.sort((a,b)=>a.isDirectory!==b.isDirectory?a.isDirectory?-1:1:a.name.localeCompare(b.name)),res.json({currentPath:dirPath,parentPath:dirPath==="/"?null:path.posix.dirname(dirPath),files:result})}catch(error){res.status(500).json({error:error.message})}}),app.get("/__api/file",(req,res)=>{let filePath=normalizeExplorerInputPath(req.query.path||"/"),fullPath;try{fullPath=resolveExplorerPath(filePath)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(!existsSync(fullPath))return res.status(404).json({error:"File not found"});let stats=statSync(fullPath);if(stats.isDirectory())return res.status(400).json({error:"Is a directory"});let ext=path.extname(filePath).toLowerCase(),imageExts=[".jpg",".jpeg",".png",".gif",".bmp",".webp",".svg",".ico"],textExts=[".txt",".json",".js",".css",".html",".xml",".md",".csv",".yaml",".yml",".log"];if(imageExts.includes(ext))res.sendFile(fullPath);else if(textExts.includes(ext)||stats.size<1024*1024)try{let content=readFileSync(fullPath,"utf-8");res.json({name:path.basename(filePath),type:"text",content,size:stats.size})}catch{res.download(fullPath)}else res.download(fullPath)}),app.post("/__api/open-in-explorer",(req,res)=>{let filePath=normalizeExplorerInputPath(req.body.path||"/"),fullPath;try{fullPath=resolveExplorerPath(filePath)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(!existsSync(fullPath))return res.status(404).json({error:"Path not found"});let command,args;switch(process.platform){case"darwin":command="open",args=[fullPath];break;case"win32":command="explorer.exe",args=[fullPath];break;case"linux":command="xdg-open",args=[fullPath];break;default:return res.status(400).json({error:"Unsupported platform"})}execFile(command,args,error=>{if(error)return console.error(colors.red(`Failed to open in explorer: ${error.message}`)),res.status(500).json({error:"Failed to open in explorer"});res.json({success:!0,path:fullPath})})}),app.post("/__api/path",requireEditMode,(req,res)=>{let parentPath=req.body&&req.body.parentPath||"/",name=req.body&&req.body.name,type=req.body&&req.body.type||"file";if(type!=="file"&&type!=="directory")return res.status(400).json({error:"Invalid type"});let fullPath;try{fullPath=getChildPath(parentPath,name)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(existsSync(fullPath))return res.status(409).json({error:"Path already exists"});try{type==="directory"?mkdirSync(fullPath):writeFileSync(fullPath,""),res.json({success:!0,path:fullPath})}catch(error){console.error(colors.red(`Failed to create path: ${error.message}`)),res.status(500).json({error:"Failed to create path"})}}),app.patch("/__api/path",requireEditMode,(req,res)=>{let sourcePath=req.body&&req.body.path,name=req.body&&req.body.name,fullPath,nextPath;try{if(fullPath=resolveExplorerPath(sourcePath),path.resolve(fullPath)===explorerRootRealPath)return res.status(400).json({error:"Cannot rename explorer root"});if(!existsSync(fullPath))return res.status(404).json({error:"Path not found"});nextPath=getChildPath(path.posix.dirname(normalizeExplorerInputPath(sourcePath||"/")),name)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(existsSync(nextPath))return res.status(409).json({error:"Path already exists"});try{renameSync(fullPath,nextPath),res.json({success:!0,path:sourcePath,nextPath})}catch(error){console.error(colors.red(`Failed to rename path: ${error.message}`)),res.status(500).json({error:"Failed to rename path"})}}),app.delete("/__api/path",requireEditMode,(req,res)=>{let targetPath=req.body&&req.body.path||"/";try{deleteExplorerPath(targetPath),res.json({success:!0,path:targetPath})}catch(error){console.error(colors.red(`Failed to delete path: ${error.message}`)),res.status(error.statusCode||500).json({error:error.statusCode?error.message:"Failed to delete path"})}}),app.delete("/__api/paths",requireEditMode,(req,res)=>{let paths=req.body&&req.body.paths||[];if(!Array.isArray(paths)||paths.length===0)return res.status(400).json({error:"Paths must be a non-empty array"});let deleted=[];try{paths.forEach(targetPath=>{deleteExplorerPath(targetPath),deleted.push(targetPath)}),res.json({success:!0,deleted})}catch(error){console.error(colors.red(`Failed to delete paths: ${error.message}`)),res.status(error.statusCode||500).json({error:error.statusCode?error.message:"Failed to delete paths",deleted})}}),startServer()}function startServer(){require("http").createServer(app).listen(Number.parseInt(process.env.PORT,10),getServerHost(),()=>{if(console.info([colors.yellow(`
|
|
138
|
+
`)),getServerUrls(process.env.PORT).forEach(url=>{console.info(" "+url.replace(String(process.env.PORT),colors.green(process.env.PORT)))})})}process.platform==="win32"&&require("readline").createInterface({input:process.stdin,output:process.stdout}).on("SIGINT",function(){process.emit("SIGINT")});process.on("SIGINT",function(){log.info(colors.red("static-server process stopped.")),process.exit()});process.on("SIGTERM",function(){log.info(colors.red("static-server process stopped.")),process.exit()})}});var require_fileExplorerServer=__commonJS({"src/lib/fileExplorerServer.js"(){var express=require_express2(),{existsSync,readFileSync,statSync,rmSync,mkdirSync,writeFileSync,renameSync,realpathSync,promises:fsPromises}=require("fs"),path=require("path"),colors=require_safe(),portfinder=require_portfinder(),{exec,execFile}=require("child_process"),{dateFormat,logger,getServerHost,getServerUrls}=require_utils3(),{getPackageVersion}=require_packageInfo(),app=express(),log=logger(process.env.SILENT),argv=JSON.parse(process.env.ARGV),explorerRoot=path.resolve(process.env.EXPLORER_DIRECTORY||process.cwd()),explorerRootRealPath=realpathSync(explorerRoot),port=argv.p||argv.port,isEditMode=process.env.EXPLORER_EDIT==="true";function isPathInsideRoot(fullPath,resolvedRoot=explorerRootRealPath){let relativePath=path.relative(resolvedRoot,fullPath);return relativePath===""||!relativePath.startsWith("..")&&!path.isAbsolute(relativePath)}function normalizeExplorerInputPath(inputPath){let decodedPath=decodeURIComponent(String(inputPath||"/")).replace(/\\/g,"/");return!decodedPath||decodedPath==="."?"/":decodedPath.startsWith("/")?decodedPath:`/${decodedPath}`}function resolveExplorerPath(inputPath){let relativePath=normalizeExplorerInputPath(inputPath).replace(/^\/+/,""),fullPath=path.resolve(explorerRoot,relativePath);if(!isPathInsideRoot(fullPath,explorerRoot)){let error=new Error("Access denied");throw error.statusCode=403,error}if(!existsSync(fullPath))return fullPath;let realPath=realpathSync(fullPath);if(!isPathInsideRoot(realPath)){let error=new Error("Access denied");throw error.statusCode=403,error}return realPath}function validateEntryName(name){if(typeof name!="string")return"Name must be a string";let normalizedName=name.trim();if(!normalizedName||normalizedName==="."||normalizedName==="..")return"Invalid name";if(/[/\\\0<>:"|?*]/.test(normalizedName))return"Name contains invalid characters";if(process.platform==="win32"){let upperName=normalizedName.replace(/[. ]+$/g,"").split(".")[0].toUpperCase();if(new Set(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]).has(upperName)||normalizedName.endsWith(" ")||normalizedName.endsWith("."))return"Name is not supported on Windows"}return null}function getChildPath(parentPath,name){let nameError=validateEntryName(name);if(nameError){let error=new Error(nameError);throw error.statusCode=400,error}let parentFullPath=resolveExplorerPath(parentPath||"/");if(!existsSync(parentFullPath)||!statSync(parentFullPath).isDirectory()){let error=new Error("Parent directory not found");throw error.statusCode=404,error}let childPath=path.resolve(parentFullPath,name.trim());if(!isPathInsideRoot(childPath)){let error=new Error("Access denied");throw error.statusCode=403,error}return childPath}function requireEditMode(req,res,next){if(!isEditMode)return res.status(403).json({error:"File explorer is read-only. Restart with --edit to modify files."});next()}function deleteExplorerPath(targetPath){let fullPath=resolveExplorerPath(targetPath);if(path.resolve(fullPath)===explorerRootRealPath){let error=new Error("Cannot delete explorer root");throw error.statusCode=400,error}if(!existsSync(fullPath)){let error=new Error("Path not found");throw error.statusCode=404,error}rmSync(fullPath,{recursive:!0,force:!1})}process.env.PORT?init():(portfinder.basePort=port||8090,portfinder.getPort(function(err,foundPort){if(err)throw err;process.env.PORT=foundPort,init()}));function init(){app.use(express.json()),app.get("/",(req,res)=>{let htmlPath=path.resolve(__dirname,"./file-explorer.html");existsSync(htmlPath)?res.sendFile(htmlPath):res.status(404).send("File explorer page not found")}),app.get("/__api/config",(req,res)=>{res.json({editMode:isEditMode})}),app.get("/__api/list",async(req,res)=>{let dirPath=normalizeExplorerInputPath(req.query.path||"/"),fullPath;try{fullPath=resolveExplorerPath(dirPath)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(!existsSync(fullPath))return res.status(404).json({error:"Path not found"});try{if(!(await fsPromises.lstat(fullPath)).isDirectory())return res.status(400).json({error:"Not a directory"});let files=await fsPromises.readdir(fullPath,{withFileTypes:!0}),result=await Promise.all(files.map(async file=>{let filePath=path.join(fullPath,file.name),fileStats,hasError=!1;try{fileStats=await fsPromises.lstat(filePath)}catch{hasError=!0}let relativePath=path.posix.join(dirPath,file.name),isDirectory=hasError?file.isDirectory():fileStats.isDirectory();return{name:file.name,path:relativePath.replace(/\\/g,"/"),isDirectory,size:hasError?0:fileStats.size,mtime:hasError?new Date:fileStats.mtime,birthtime:hasError?new Date:fileStats.birthtime,isHidden:file.name.startsWith("."),error:hasError?"Cannot access file":null}}));result.sort((a,b)=>a.isDirectory!==b.isDirectory?a.isDirectory?-1:1:a.name.localeCompare(b.name)),res.json({currentPath:dirPath,parentPath:dirPath==="/"?null:path.posix.dirname(dirPath),files:result})}catch(error){res.status(500).json({error:error.message})}}),app.get("/__api/file",(req,res)=>{let filePath=normalizeExplorerInputPath(req.query.path||"/"),fullPath;try{fullPath=resolveExplorerPath(filePath)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(!existsSync(fullPath))return res.status(404).json({error:"File not found"});let stats=statSync(fullPath);if(stats.isDirectory())return res.status(400).json({error:"Is a directory"});if(req.query.download==="1")return res.download(fullPath,path.basename(filePath));let ext=path.extname(filePath).toLowerCase(),imageExts=[".jpg",".jpeg",".png",".gif",".bmp",".webp",".svg",".ico"],textExts=[".txt",".json",".js",".css",".html",".xml",".md",".csv",".yaml",".yml",".log"];if(imageExts.includes(ext))res.sendFile(fullPath);else if(textExts.includes(ext)||stats.size<1024*1024)try{let content=readFileSync(fullPath,"utf-8");res.json({name:path.basename(filePath),type:"text",content,size:stats.size})}catch{res.download(fullPath)}else res.download(fullPath)}),app.post("/__api/open-in-explorer",(req,res)=>{let filePath=normalizeExplorerInputPath(req.body.path||"/"),fullPath;try{fullPath=resolveExplorerPath(filePath)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(!existsSync(fullPath))return res.status(404).json({error:"Path not found"});let command,args;switch(process.platform){case"darwin":command="open",args=[fullPath];break;case"win32":command="explorer.exe",args=[fullPath];break;case"linux":command="xdg-open",args=[fullPath];break;default:return res.status(400).json({error:"Unsupported platform"})}execFile(command,args,error=>{if(error)return console.error(colors.red(`Failed to open in explorer: ${error.message}`)),res.status(500).json({error:"Failed to open in explorer"});res.json({success:!0,path:fullPath})})}),app.post("/__api/path",requireEditMode,(req,res)=>{let parentPath=req.body&&req.body.parentPath||"/",name=req.body&&req.body.name,type=req.body&&req.body.type||"file";if(type!=="file"&&type!=="directory")return res.status(400).json({error:"Invalid type"});let fullPath;try{fullPath=getChildPath(parentPath,name)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(existsSync(fullPath))return res.status(409).json({error:"Path already exists"});try{type==="directory"?mkdirSync(fullPath):writeFileSync(fullPath,""),res.json({success:!0,path:fullPath})}catch(error){console.error(colors.red(`Failed to create path: ${error.message}`)),res.status(500).json({error:"Failed to create path"})}}),app.patch("/__api/path",requireEditMode,(req,res)=>{let sourcePath=req.body&&req.body.path,name=req.body&&req.body.name,fullPath,nextPath;try{if(fullPath=resolveExplorerPath(sourcePath),path.resolve(fullPath)===explorerRootRealPath)return res.status(400).json({error:"Cannot rename explorer root"});if(!existsSync(fullPath))return res.status(404).json({error:"Path not found"});nextPath=getChildPath(path.posix.dirname(normalizeExplorerInputPath(sourcePath||"/")),name)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(existsSync(nextPath))return res.status(409).json({error:"Path already exists"});try{renameSync(fullPath,nextPath),res.json({success:!0,path:sourcePath,nextPath})}catch(error){console.error(colors.red(`Failed to rename path: ${error.message}`)),res.status(500).json({error:"Failed to rename path"})}}),app.delete("/__api/path",requireEditMode,(req,res)=>{let targetPath=req.body&&req.body.path||"/";try{deleteExplorerPath(targetPath),res.json({success:!0,path:targetPath})}catch(error){console.error(colors.red(`Failed to delete path: ${error.message}`)),res.status(error.statusCode||500).json({error:error.statusCode?error.message:"Failed to delete path"})}}),app.delete("/__api/paths",requireEditMode,(req,res)=>{let paths=req.body&&req.body.paths||[];if(!Array.isArray(paths)||paths.length===0)return res.status(400).json({error:"Paths must be a non-empty array"});let deleted=[];try{paths.forEach(targetPath=>{deleteExplorerPath(targetPath),deleted.push(targetPath)}),res.json({success:!0,deleted})}catch(error){console.error(colors.red(`Failed to delete paths: ${error.message}`)),res.status(error.statusCode||500).json({error:error.statusCode?error.message:"Failed to delete paths",deleted})}}),startServer()}function startServer(){require("http").createServer(app).listen(Number.parseInt(process.env.PORT,10),getServerHost(),()=>{if(console.info([colors.yellow(`
|
|
139
139
|
Starting up file-explorer-server, serving `),colors.cyan(explorerRoot),colors.yellow(` ${dateFormat("YYYY-mm-dd HH:MM:SS",new Date)}`)].join("")),console.info([colors.yellow(`
|
|
140
140
|
\u{1F30D} file-explorer-server version: `),colors.cyan(getPackageVersion()),`
|
|
141
141
|
`].join("")),console.info(colors.yellow(`
|