Comparing version 0.23.0-dev.0 to 0.23.0-dev.1
@@ -10,2 +10,3 @@ Object.defineProperty(exports,"packageName",{enumerable:!0,get:function(){return _package.name}}) | ||
var _net=require("../library/node/net") | ||
var _Stream=require("../library/node/data/Stream") | ||
var _function2=require("../library/node/file/function") | ||
@@ -24,40 +25,40 @@ var _Directory=require("../library/node/file/Directory") | ||
exports.evalScript=evalScript | ||
const evalReadlineExtend=async(e,r,t)=>{const{onLineSync:o,getResult:n,logLineInterval:a=0}=e | ||
const evalReadlineExtend=async(e,r,t)=>{const{onLineSync:o,getResult:a,logLineInterval:n=0}=e | ||
let s=0 | ||
let i="" | ||
const c=a&&(0,_time.createStepper)() | ||
const l=a?()=>s%a==0&&t(`line: ${(0,_format.decimal)(s)} (+${(0,_format.time)(c())})`):()=>{} | ||
await(0,_function2.createReadlineFromFileAsync)(r,e=>{i=e | ||
const c=n&&(0,_time.createStepper)() | ||
const l=n?()=>s%n==0&&t(`line: ${(0,_format.decimal)(s)} (+${(0,_format.time)(c())})`):()=>{} | ||
await(0,_Stream.createReadlineFromStreamAsync)((0,_function2.createReadStream)(r),e=>{i=e | ||
l() | ||
o(i,s) | ||
s++}) | ||
return n()} | ||
return a()} | ||
exports.evalReadlineExtend=evalReadlineExtend | ||
const fetchWithJump=async(e,r={},t=0,o)=>{let n=e | ||
let a=0 | ||
const fetchWithJump=async(e,r={},t=0,o)=>{let a=e | ||
let n=0 | ||
let s=r.headers&&r.headers.cookie?[r.headers.cookie]:[] | ||
for(;;){o&&await o(n,a,s) | ||
const e=await(0,_net.fetchLikeRequest)(n,Object.assign({},r,{headers:Object.assign({},r.headers,{cookie:s.join(";")})})) | ||
const i=()=>JSON.stringify({url:n,status:e.status,headers:e.headers},null,2) | ||
for(;;){o&&await o(a,n,s) | ||
const e=await(0,_net.fetchLikeRequest)(a,Object.assign({},r,{headers:Object.assign({},r.headers,{cookie:s.join(";")})})) | ||
const i=()=>JSON.stringify({url:a,status:e.status,headers:e.headers},null,2) | ||
if(e.ok)return e | ||
if(!(e.status>=300&&e.status<=399&&e.headers.location))throw new Error(`bad status: ${i()}`) | ||
if(++a>t)throw new Error(`${t} max jump reached: ${i()}`) | ||
n=new URL(e.headers.location,n).href | ||
if(++n>t)throw new Error(`${t} max jump reached: ${i()}`) | ||
a=new URL(e.headers.location,a).href | ||
s=[...s,...(e.headers["set-cookie"]||[]).map(e=>e.split(";")[0])]}} | ||
exports.fetchWithJump=fetchWithJump | ||
const prettyStringifyFileTree=async e=>{const{subInfoListMap:r}=await(0,_Directory.getDirectoryInfoTree)(e) | ||
const t=[];(0,_Tree.prettyStringifyTree)([[e,"NAME"],-1,!1],([[e],t,o])=>r[e]&&r[e].map(({path:e,name:r},o,{length:n})=>[[e,r],t+1,o!==n-1]),(e,[,r])=>t.push(`${e}${r}`)) | ||
const t=[];(0,_Tree.prettyStringifyTree)([[e,"NAME"],-1,!1],([[e],t,o])=>r[e]&&r[e].map(({path:e,name:r},o,{length:a})=>[[e,r],t+1,o!==a-1]),(e,[,r])=>t.push(`${e}${r}`)) | ||
return t.join("\n")} | ||
const collectFile=async(e,r)=>"file-list"===e?(await(0,_Directory.getDirectorySubInfoList)(r)).map(({name:e,stat:r})=>r.isDirectory()?`${e}/`:e):"file-list-all"===e?(0,_Directory.getFileList)(r):"file-tree"===e?prettyStringifyFileTree(r):"" | ||
exports.collectFile=collectFile | ||
const describeServer=({baseUrl:e,protocol:r,hostname:t,port:o},n,a=[])=>(0,_string.indentList)(`[${n}]`,[`pid: ${process.pid}`,...a,`baseUrl: '${e}'`,"0.0.0.0"===t&&(0,_string.indentList)("localUrl:",[{address:"localhost"},...(0,_NetworkAddress.getNetworkIPv4AddressList)()].map(({address:e})=>`'${r}//${e}:${o}'`))].filter(Boolean)) | ||
const describeServer=({baseUrl:e,protocol:r,hostname:t,port:o},a,n=[])=>(0,_string.indentList)(`[${a}]`,[`pid: ${process.pid}`,...n,`baseUrl: '${e}'`,"0.0.0.0"===t&&(0,_string.indentList)("localUrl:",[{address:"localhost"},...(0,_NetworkAddress.getNetworkIPv4AddressList)()].map(({address:e})=>`'${r}//${e}:${o}'`))].filter(Boolean)) | ||
exports.describeServer=describeServer | ||
const commonStartServer=async({protocol:e,hostname:r,port:t,routeConfigList:o,isAddFavicon:n,title:a,extraInfoList:s,log:i})=>{const{server:c,option:l,start:p,stop:d}=(0,_Server.createServer)({protocol:e,hostname:r,port:t}) | ||
const commonStartServer=async({protocol:e,hostname:r,port:t,routeConfigList:o,isAddFavicon:a,title:n,extraInfoList:s,log:i})=>{const{server:c,option:l,start:p,stop:d}=(0,_Server.createServer)({protocol:e,hostname:r,port:t}) | ||
const v=(0,_Common.createResponderLogEnd)({log:i}) | ||
n&&(o=[...o,[["/favicon","/favicon.ico"],"GET",(0,_Send.createResponderFavicon)()]]) | ||
a&&(o=[...o,[["/favicon","/favicon.ico"],"GET",(0,_Send.createResponderFavicon)()]]) | ||
c.on("request",(0,_Server.createRequestListener)({responderList:[(0,_Common.createResponderLog)({log:i}),(0,_Router.createResponderRouter)({routeMap:(0,_Router.createRouteMap)(o),baseUrl:l.baseUrl})],responderEnd:e=>{(0,_Common.responderEnd)(e) | ||
v(e)}})) | ||
await p() | ||
i(describeServer(l,a,s)) | ||
i(describeServer(l,n,s)) | ||
return{server:c,option:l,start:p,stop:d}} | ||
exports.commonStartServer=commonStartServer |
@@ -10,3 +10,3 @@ #!/usr/bin/env node | ||
var n=require("../library/node/data/Stream") | ||
var c=require("../library/node/file/File") | ||
var c=require("../library/node/file/Directory") | ||
var u=require("../library/node/file/Modify") | ||
@@ -17,3 +17,3 @@ var l=require("../library/node/server/function") | ||
var d=require("../library/node/system/Run") | ||
var y=require("../library/node/system/ProcessStatus") | ||
var y=require("../library/node/system/Process") | ||
var f=require("../library/node/system/Status") | ||
@@ -32,4 +32,4 @@ var v=require("./server/serveStatic") | ||
const x=T("input-file") | ||
const F=T("output-file") | ||
const j=async()=>{const e=(T("host")||"").split(":") | ||
const j=T("output-file") | ||
const C=async()=>{const e=(T("host")||"").split(":") | ||
const r=e[0]||"0.0.0.0" | ||
@@ -39,3 +39,3 @@ return{hostname:r,port:Number(e[1]||await(0,l.autoTestServerPort)([80,8080,8888,8800,8e3],r))}} | ||
"eval-readline"===b&&(t=await(0,w.evalReadlineExtend)(t,O("root"),A)) | ||
return void 0!==t&&(e=>F?(0,r.writeFileSync)(F,e):(0,n.pipeStreamAsync)(process.stdout,(0,n.bufferToReadableStream)(e)))(t instanceof Buffer?t:Buffer.from(String(t)))}case"repl":return(0,t.start)({prompt:"> ",input:process.stdin,output:process.stdout,useGlobal:!0}).context.require=require | ||
return void 0!==t&&(e=>j?(0,r.writeFileSync)(j,e):(0,n.pipeStreamAsync)(process.stdout,(0,n.bufferToReadableStream)(e)))(t instanceof Buffer?t:Buffer.from(String(t)))}case"repl":return(0,t.start)({prompt:"> ",input:process.stdin,output:process.stdout,useGlobal:!0}).context.require=require | ||
case"wait":{const e=P[0]||2e3 | ||
@@ -50,9 +50,9 @@ return(0,o.setTimeoutAsync)(e)}case"echo":return h(P) | ||
case"open":{const r=P[0]||"." | ||
return(0,d.runSync)({command:(0,m.getDefaultOpen)(),argList:[r.includes("://")?r:(0,e.normalize)(r)]})}case"status":return h(k?{system:(0,f.getSystemStatus)(),process:(0,f.getCurrentProcessStatus)()}:(0,f.describeSystemStatus)()) | ||
return(0,d.runSync)({command:(0,m.getDefaultOpen)(),argList:[r.includes("://")?r:(0,e.normalize)(r)]})}case"status":return h(k?(0,f.getSystemStatus)():(0,f.describeSystemStatus)()) | ||
case"file-list":case"file-list-all":case"file-tree":return h(await(0,w.collectFile)(b,P[0]||process.cwd())) | ||
case"file-create-directory":for(const e of P)await N(c.createDirectory,e) | ||
return | ||
case"file-modify-copy":return u.modify.copy(P[0],P[1]) | ||
case"file-modify-move":return u.modify.move(P[0],P[1]) | ||
case"file-modify-delete":for(const e of P)await N(u.modify.delete,e) | ||
case"file-modify-copy":return(0,u.modifyCopy)(P[0],P[1]) | ||
case"file-modify-move":return(0,u.modifyMove)(P[0],P[1]) | ||
case"file-modify-delete":for(const e of P)await N(u.modifyDelete,e) | ||
return | ||
@@ -67,3 +67,3 @@ case"file-merge":{const[e,...t]=P | ||
A(`[fetch] get status: ${o.status}, fetch response content${i?` (${(0,s.binary)(i)}B)`:""}...`) | ||
await(e=>(0,n.pipeStreamAsync)(F?(0,r.createWriteStream)(F):process.stdout,e))(o.stream()) | ||
await(e=>(0,n.pipeStreamAsync)(j?(0,r.createWriteStream)(j):process.stdout,e))(o.stream()) | ||
return A("\n[fetch] done")}case"process-status":{const[e="pid--"]=P | ||
@@ -73,7 +73,7 @@ return h(await(k?y.getAllProcessStatusAsync:y.describeAllProcessStatusAsync)(e))}case"json-format":{const[e=2]=P | ||
const a=(0,s.prettyStringifyJSON)(t,e) | ||
return(0,r.writeFileSync)(F||x,a)}case"server-serve-static":case"server-serve-static-simple":{const[e=5e3]=P | ||
return(0,r.writeFileSync)(j||x,a)}case"server-serve-static":case"server-serve-static-simple":{const[e=5e3]=P | ||
const r="server-serve-static-simple"===b | ||
const t=T("root")||process.cwd() | ||
return(0,v.startServerServeStatic)(Object.assign({isSimpleServe:r,expireTime:Number(e),staticRoot:t,log:A},await j()))}case"server-websocket-group":return(0,S.startServerWebSocketGroup)(Object.assign({log:A},await j())) | ||
case"server-test-connection":return(0,g.startServerTestConnection)(Object.assign({log:A},await j())) | ||
return(0,v.startServerServeStatic)(Object.assign({isSimpleServe:r,expireTime:Number(e),staticRoot:t,log:A},await C()))}case"server-websocket-group":return(0,S.startServerWebSocketGroup)(Object.assign({log:A},await C())) | ||
case"server-test-connection":return(0,g.startServerTestConnection)(Object.assign({log:A},await C())) | ||
case"server-tcp-proxy":{let e | ||
@@ -88,3 +88,3 @@ let r | ||
A(`[CONNECT] ${r.remoteAddress}:${r.remotePort} => ${s.hostname}:${s.port}`) | ||
return s}}const{option:t,start:s}=(0,p.createTCPProxyServer)(Object.assign({getTargetOption:r},await j())) | ||
return s}}const{option:t,start:s}=(0,p.createTCPProxyServer)(Object.assign({getTargetOption:r},await C())) | ||
await s() | ||
@@ -91,0 +91,0 @@ return A((0,a.indentList)("[TCPProxy]",[`pid: ${process.pid}`,`at: ${t.hostname}:${t.port}`,...e.map(e=>`proxy to: ${e.hostname}:${e.port}`)]))}}};(async()=>{const e=await(0,b.parseOption)() |
@@ -5,4 +5,4 @@ var e=require("path") | ||
var o=require("../../library/common/string") | ||
var i=require("../../library/common/module/MIME") | ||
var a=require("../../library/node/file/function") | ||
var a=require("../../library/common/module/MIME") | ||
var i=require("../../library/node/file/Path") | ||
var n=require("../../library/node/file/Directory") | ||
@@ -15,14 +15,14 @@ var s=require("../../library/node/server/Responder/Common") | ||
var d=require("../function") | ||
exports.startServerServeStatic=async({isSimpleServe:e,expireTime:r,staticRoot:o,protocol:i="http:",hostname:n,port:c,log:m})=>{const u=(0,a.createPathPrefixLock)(o) | ||
exports.startServerServeStatic=async({isSimpleServe:e,expireTime:r,staticRoot:o,protocol:a="http:",hostname:n,port:c,log:m})=>{const u=(0,i.createPathPrefixLock)(o) | ||
const f=e=>u(decodeURIComponent((0,l.getRouteParamAny)(e))) | ||
const y=(0,p.createResponderServeStatic)({expireTime:r}) | ||
const b=[[e?"/*":"/file/*","GET",e=>y(e,f(e))],!e&&["/list/*","GET",e=>v(e,f(e),o)],!e&&[["/","/*","/file","/list"],"GET",e=>(0,s.responderEndWithRedirect)(e,{redirectUrl:"/list/"})]].filter(Boolean) | ||
await(0,d.commonStartServer)({protocol:i,hostname:n,port:c,routeConfigList:b,isAddFavicon:!e,title:`ServerServeStatic|${e?"no-list":"with-list"}`,extraInfoList:[`staticRoot: '${o}'`,`expireTime: ${(0,t.time)(r)}`],log:m})} | ||
const h=[[e?"/*":"/file/*","GET",e=>y(e,f(e))],!e&&["/list/*","GET",e=>v(e,f(e),o)],!e&&[["/","/*","/file","/list"],"GET",e=>(0,s.responderEndWithRedirect)(e,{redirectUrl:"/list/"})]].filter(Boolean) | ||
await(0,d.commonStartServer)({protocol:a,hostname:n,port:c,routeConfigList:h,isAddFavicon:!e,title:`ServerServeStatic|${e?"no-list":"with-list"}`,extraInfoList:[`staticRoot: '${o}'`,`expireTime: ${(0,t.time)(r)}`],log:m})} | ||
const v=async(r,t,s)=>{const l=(0,e.relative)(s,t) | ||
const p=`/${(0,o.escapeHTML)((0,a.toPosixPath)(l))}` | ||
const p=`/${(0,o.escapeHTML)((0,i.toPosixPath)(l))}` | ||
const d=[] | ||
const v=[];(await(0,n.getDirectorySubInfoList)(t)).forEach(e=>e.stat.isDirectory()?d.push(e):v.push(e)) | ||
return(0,c.responderSendBufferCompress)(r,{type:i.BASIC_EXTENSION_MAP.html,buffer:Buffer.from((0,m.COMMON_LAYOUT)([`<title>${p}</title>`,(0,m.COMMON_STYLE)(),u],[`<b class="auto-height">${p}</b>`,l&&y("/list",[(0,e.dirname)(l)],"🔙",".."),...d.sort(f).map(({name:e,stat:{mtimeMs:r}})=>y("/list",[l,e],"📁",`${e}/`,0,r)),...v.sort(f).map(({name:e,stat:{size:r,mtimeMs:t}})=>y("/file",[l,e],"📄",e,r,t,!0))]))})} | ||
return(0,c.responderSendBufferCompress)(r,{type:a.BASIC_EXTENSION_MAP.html,buffer:Buffer.from((0,m.COMMON_LAYOUT)([`<title>${p}</title>`,(0,m.COMMON_STYLE)(),u],[`<b class="auto-height">${p}</b>`,l&&y("/list",[(0,e.dirname)(l)],"🔙",".."),...d.sort(f).map(({name:e,stat:{mtimeMs:r}})=>y("/list",[l,e],"📁",`${e}/`,0,r)),...v.sort(f).map(({name:e,stat:{size:r,mtimeMs:t}})=>y("/file",[l,e],"📄",e,r,t,!0))]))})} | ||
const u="<style>\nbody { white-space: pre; }\na, b { display: flex; align-items: center; }\na { text-decoration: none; border-top: 1px solid #ddd; }\na:hover { background: #eee; }\np.name { overflow: hidden; text-overflow: ellipsis; }\np.size, p.date { padding-left: 1em; text-align: right; opacity: 0.5 }\np.size { flex: 1; }\n@media only screen and (max-width: 768px) { p.date { display: none; } }\n</style>" | ||
const f=({name:e},{name:t})=>(0,r.compareStringWithNumber)(e,t) | ||
const y=(r,i,n,s,c,l,p,m=`href="${r}/${encodeURIComponent((0,a.toPosixPath)((0,e.join)(...i)))}"`,d=(0,o.escapeHTML)(s))=>`<a class="auto-height" ${m} ${p?`download="${d}"`:""}>\n<object class="name">${p?`<a ${m} target="_blank">${n}</a>`:n}</object>\n<p class="name">|${d}</p>\n<p class="size">${c?`${(0,t.binary)(c)}B`:""}</p>\n<p class="date">${l?(0,o.escapeHTML)(new Date(l).toISOString()):""}</p>\n</a>` | ||
const y=(r,a,n,s,c,l,p,m=`href="${r}/${encodeURIComponent((0,i.toPosixPath)((0,e.join)(...a)))}"`,d=(0,o.escapeHTML)(s))=>`<a class="auto-height" ${m} ${p?`download="${d}"`:""}>\n<object class="name">${p?`<a ${m} target="_blank">${n}</a>`:n}</object>\n<p class="name">|${d}</p>\n<p class="size">${c?`${(0,t.binary)(c)}B`:""}</p>\n<p class="date">${l?(0,o.escapeHTML)(new Date(l).toISOString()):""}</p>\n</a>` |
var e=require("stream") | ||
var r=require("readline") | ||
exports.pipeStreamAsync=(e,r)=>new Promise((o,n)=>{r.on("error",n) | ||
@@ -10,1 +11,6 @@ r.on("end",()=>{r.off("error",n) | ||
return o} | ||
exports.createReadlineFromStreamAsync=(e,o)=>new Promise((n,a)=>{const s=(0,r.createInterface)({input:e,historySize:0,crlfDelay:1/0}) | ||
s.on("error",e=>{s.close() | ||
a(e)}) | ||
s.on("close",()=>{n()}) | ||
s.on("line",e=>{o(e)})}) |
var t=require("path") | ||
var o=require("./function") | ||
var e=require("./File") | ||
const a=async(a,r)=>{void 0===r&&(r=await(0,e.getPathStat)(a)) | ||
if(!r.isDirectory())throw new Error(`error pathType: ${(0,e.getPathTypeFromStat)(r)} for ${a}`) | ||
var a=require("./function") | ||
var o=require("./Path") | ||
const e=async(e,r)=>{void 0===r&&(r=await(0,o.getPathStat)(e)) | ||
if(!r.isDirectory())throw new Error(`error pathType: ${(0,o.getPathTypeFromStat)(r)} for ${e}`) | ||
const s=[] | ||
for(const r of await(0,o.readdirAsync)(a)){const o=(0,t.join)(a,r) | ||
const n=await(0,e.getPathStat)(o) | ||
const c=(0,e.getPathTypeFromStat)(n) | ||
s.push({path:o,name:r,stat:n,type:c})}return s} | ||
exports.getDirectorySubInfoList=a | ||
const r=async(t,o)=>{const e={} | ||
const r=[{path:t,stat:o}] | ||
for(;r.length;){const{path:t,stat:o}=r.shift() | ||
const s=await a(t,o) | ||
e[t]=s | ||
s.forEach(t=>t.stat.isDirectory()&&r.push(t))}return{root:t,subInfoListMap:e}} | ||
for(const r of await(0,a.readdirAsync)(e)){const a=(0,t.join)(e,r) | ||
const n=await(0,o.getPathStat)(a) | ||
const c=(0,o.getPathTypeFromStat)(n) | ||
s.push({path:a,name:r,stat:n,type:c})}return s} | ||
exports.getDirectorySubInfoList=e | ||
const r=async(t,a)=>{const o={} | ||
const r=[{path:t,stat:a}] | ||
for(;r.length;){const{path:t,stat:a}=r.shift() | ||
const s=await e(t,a) | ||
o[t]=s | ||
s.forEach(t=>t.stat.isDirectory()&&r.push(t))}return{root:t,subInfoListMap:o}} | ||
exports.getDirectoryInfoTree=r | ||
const s=async({root:t,subInfoListMap:o},e)=>{const a=[{path:t}] | ||
for(;a.length;){const{path:t}=a.shift() | ||
for(const r of o[t]){r.stat.isDirectory()&&a.push(r) | ||
await e(r)}}} | ||
const s=async({root:t,subInfoListMap:a},o)=>{const e=[{path:t}] | ||
for(;e.length;){const{path:t}=e.shift() | ||
for(const r of a[t]){r.stat.isDirectory()&&e.push(r) | ||
await o(r)}}} | ||
exports.walkDirectoryInfoTree=s | ||
const n=async({root:t,subInfoListMap:o},e)=>{const a={path:t} | ||
const r=[[a,[a]]] | ||
const n=async({root:t,subInfoListMap:a},o)=>{const e={path:t} | ||
const r=[[e,[e]]] | ||
for(;r.length;){const[t,s]=r[r.length-1] | ||
if(0===s.length){t!==a&&await e(t) | ||
if(0===s.length){t!==e&&await o(t) | ||
r.pop()}else{const t=s.shift() | ||
const a=[] | ||
for(const r of o[t.path])r.stat.isDirectory()?a.push(r):await e(r) | ||
r.push([t,a])}}} | ||
const e=[] | ||
for(const r of a[t.path])r.stat.isDirectory()?e.push(r):await o(r) | ||
r.push([t,e])}}} | ||
exports.walkDirectoryInfoTreeBottomUp=n | ||
exports.copyDirectoryInfoTree=async(o,a)=>{await(0,e.createDirectory)(a) | ||
const r={[o.root]:a} | ||
return s(o,({path:o,name:a,stat:s})=>{const n=(0,t.dirname)(o) | ||
const c=(0,t.join)(r[n],a) | ||
r[o]=c | ||
return(0,e.copyPath)(o,c,s)})} | ||
exports.moveDirectoryInfoTree=async({root:o,subInfoListMap:a},r)=>{await(0,e.createDirectory)(r) | ||
for(const s of a[o]){const{path:o,name:a,stat:n}=s | ||
await(0,e.movePath)(o,(0,t.join)(r,a),n)}} | ||
exports.deleteDirectoryInfoTree=async t=>n(t,({path:t,stat:o})=>(0,e.deletePath)(t,o)) | ||
exports.getFileList=async(o,a=c)=>{const n=[] | ||
const i=await(0,e.getPathStat)(o) | ||
const p=(0,e.getPathTypeFromStat)(i) | ||
switch(p){case e.FILE_TYPE.File:a(n,{path:o,name:(0,t.basename)(o),stat:i,type:p}) | ||
exports.moveDirectoryInfoTree=async({root:a,subInfoListMap:e},r)=>{await p(r) | ||
for(const s of e[a]){const{path:a,name:e,stat:n}=s | ||
await(0,o.movePath)(a,(0,t.join)(r,e),n)}} | ||
const c=async(a,e)=>{await p(e) | ||
const r={[a.root]:e} | ||
return s(a,({path:a,name:e,stat:s})=>{const n=(0,t.dirname)(a) | ||
const c=(0,t.join)(r[n],e) | ||
r[a]=c | ||
return(0,o.copyPath)(a,c,s)})} | ||
exports.copyDirectoryInfoTree=c | ||
const i=async t=>n(t,({path:t,stat:a})=>(0,o.deletePath)(t,a)) | ||
exports.deleteDirectoryInfoTree=i | ||
const p=async(e,r)=>{void 0===r&&(r=await(0,o.getPathStat)(e)) | ||
if(!r.isDirectory()){if(r!==o.STAT_ERROR)throw new Error(`path already taken by non-directory: ${e}`) | ||
await p((0,t.dirname)(e)) | ||
await(0,a.mkdirAsync)(e)}} | ||
exports.createDirectory=p | ||
exports.copyDirectory=async(t,a,o)=>c(await r(t,o),a) | ||
exports.deleteDirectory=async(t,a)=>{await i(await r(t,a)) | ||
return(0,o.deletePath)(t,a)} | ||
exports.getFileList=async(a,e=h)=>{const n=[] | ||
const c=await(0,o.getPathStat)(a) | ||
const i=(0,o.getPathTypeFromStat)(c) | ||
switch(i){case o.PATH_TYPE.File:e(n,{path:a,name:(0,t.basename)(a),stat:c,type:i}) | ||
break | ||
case e.FILE_TYPE.Directory:await s(await r(o,i),t=>t.type===e.FILE_TYPE.File&&a(n,t)) | ||
case o.PATH_TYPE.Directory:await s(await r(a,c),t=>t.type===o.PATH_TYPE.File&&e(n,t)) | ||
break | ||
default:throw new Error(`invalid pathType: ${p} for ${o}`)}return n} | ||
const c=(t,{path:o})=>t.push(o) | ||
default:throw new Error(`invalid pathType: ${i} for ${a}`)}return n} | ||
const h=(t,{path:a})=>t.push(a) |
@@ -1,40 +0,22 @@ | ||
Object.defineProperty(exports,"createReadStream",{enumerable:!0,get:function(){return r.createReadStream}}) | ||
Object.defineProperty(exports,"createWriteStream",{enumerable:!0,get:function(){return r.createWriteStream}}) | ||
var e=require("path") | ||
var r=require("fs") | ||
var t=require("util") | ||
var s=require("readline") | ||
const[n,a,o,i,c,p,l,x,y,m,d,u]=[r.stat,r.open,r.rename,r.unlink,r.truncate,r.readFile,r.writeFile,r.appendFile,r.copyFile,r.mkdir,r.rmdir,r.readdir].map(e=>(0,t.promisify)(e)) | ||
exports.readdirAsync=u | ||
Object.defineProperty(exports,"createReadStream",{enumerable:!0,get:function(){return e.createReadStream}}) | ||
Object.defineProperty(exports,"createWriteStream",{enumerable:!0,get:function(){return e.createWriteStream}}) | ||
var e=require("fs") | ||
var r=require("util") | ||
const[t,s,n,a,c,o,i,p,y,x,d,l]=[e.stat,e.open,e.rename,e.unlink,e.truncate,e.readFile,e.writeFile,e.appendFile,e.copyFile,e.mkdir,e.rmdir,e.readdir].map(e=>(0,r.promisify)(e)) | ||
exports.readdirAsync=l | ||
exports.rmdirAsync=d | ||
exports.mkdirAsync=m | ||
exports.mkdirAsync=x | ||
exports.copyFileAsync=y | ||
exports.appendFileAsync=x | ||
exports.writeFileAsync=l | ||
exports.readFileAsync=p | ||
exports.appendFileAsync=p | ||
exports.writeFileAsync=i | ||
exports.readFileAsync=o | ||
exports.truncateAsync=c | ||
exports.unlinkAsync=i | ||
exports.renameAsync=o | ||
exports.openAsync=a | ||
exports.statAsync=n | ||
const[A,F,f,P]=[r.constants.F_OK,r.constants.R_OK,r.constants.W_OK,r.constants.X_OK].map(e=>t=>new Promise(s=>(0,r.access)(t,e,e=>s(!e)))) | ||
exports.executableAsync=P | ||
exports.writableAsync=f | ||
exports.readableAsync=F | ||
exports.visibleAsync=A | ||
exports.nearestExistAsync=async r=>{for(;r&&!await A(r);)r=(0,e.dirname)(r) | ||
return r} | ||
exports.createPathPrefixLock=r=>{r=(0,e.resolve)(r) | ||
return t=>{const s=(0,e.resolve)(r,t) | ||
if(!s.startsWith(r))throw new Error(`invalid relativePath: ${t}`) | ||
return s}} | ||
const h=(e,r)=>new Promise((t,n)=>{const a=(0,s.createInterface)({input:e,historySize:0,crlfDelay:1/0}) | ||
a.on("error",e=>{a.close() | ||
n(e)}) | ||
a.on("close",()=>{t()}) | ||
a.on("line",e=>{r(e)})}) | ||
exports.createReadlineFromStreamAsync=h | ||
exports.createReadlineFromFileAsync=(e,t)=>h((0,r.createReadStream)(e),t) | ||
exports.trimPathDepth=(r,t)=>(0,e.normalize)(r).split(e.sep).slice(0,t).join(e.sep) | ||
const v=/\\/g | ||
exports.toPosixPath=e=>e.replace(v,"/") | ||
exports.unlinkAsync=a | ||
exports.renameAsync=n | ||
exports.openAsync=s | ||
exports.statAsync=t | ||
const[m,A,u,F]=[e.constants.F_OK,e.constants.R_OK,e.constants.W_OK,e.constants.X_OK].map(r=>t=>new Promise(s=>(0,e.access)(t,r,e=>s(!e)))) | ||
exports.executableAsync=F | ||
exports.writableAsync=u | ||
exports.readableAsync=A | ||
exports.visibleAsync=m |
var e=require("path") | ||
var r=require("../../common/error") | ||
var t=require("./function") | ||
var a=require("./File") | ||
var o=require("./Directory") | ||
const i=async(r,t,o)=>{await(0,a.createDirectory)((0,e.dirname)(t)) | ||
return(0,a.movePath)(r,t,o)} | ||
exports.move=i | ||
const c=async(r,t,o)=>{await(0,a.createDirectory)((0,e.dirname)(t)) | ||
return(0,a.copyPath)(r,t,o)} | ||
exports.copyFile=c | ||
const n=(e,r)=>(0,a.deletePath)(e,r) | ||
exports.deleteFile=n | ||
const s=async(e,r,t)=>(0,o.copyDirectoryInfoTree)(await(0,o.getDirectoryInfoTree)(e,t),r) | ||
exports.copyDirectory=s | ||
const y=async(e,r)=>{await(0,o.deleteDirectoryInfoTree)(await(0,o.getDirectoryInfoTree)(e,r)) | ||
return(0,a.deletePath)(e)} | ||
exports.deleteDirectory=y | ||
const p={move:i,copy:async(e,r,t)=>{void 0===t&&(t=await(0,a.getPathStat)(e)) | ||
return t.isDirectory()?s(e,r,t):c(e,r,t)},delete:async(e,r)=>{void 0===r&&(r=await(0,a.getPathStat)(e)) | ||
return r.isDirectory()?y(e,r):n(e,r)}} | ||
exports.modify=p | ||
exports.withTempDirectory=async(o,i)=>{const c=await(0,t.nearestExistAsync)(o) | ||
await(0,a.createDirectory)(o) | ||
if(c===o)return i() | ||
const n=(0,e.resolve)(c,(0,t.trimPathDepth)((0,e.relative)(c,o),1)) | ||
const{result:s,error:p}=await(0,r.catchAsync)(i) | ||
await y(n) | ||
if(p)throw p | ||
return s} | ||
var t=require("./Path") | ||
var r=require("./Directory") | ||
const a=()=>{} | ||
exports.modifyMove=async(a,i,o)=>{await(0,r.createDirectory)((0,e.dirname)(i)) | ||
return(0,t.movePath)(a,i,o)} | ||
exports.modifyCopy=async(a,i,o)=>{void 0===o&&(o=await(0,t.getPathStat)(a)) | ||
if(o.isDirectory())return(0,r.copyDirectory)(a,i,o) | ||
await(0,r.createDirectory)((0,e.dirname)(i)) | ||
return(0,t.copyPath)(a,i,o)} | ||
const i=async(e,a)=>{void 0===a&&(a=await(0,t.getPathStat)(e)) | ||
return a.isDirectory()?(0,r.deleteDirectory)(e,a):(0,t.deletePath)(e,a)} | ||
exports.modifyDelete=i | ||
exports.modifyDeleteForce=async(e,t)=>i(e,t).catch(a) |
var e=require("path") | ||
var t=require("fs") | ||
var r=require("../../common/function") | ||
var n=require("../../common/module/Event") | ||
var a=require("./function") | ||
const s=()=>null | ||
exports.createFileWatcher=({wait:c=250,persistent:i=!1})=>{const o=(0,n.createHub)() | ||
let l | ||
var a=require("../../common/module/Event") | ||
var n=require("./function") | ||
var s=require("./Path") | ||
const c=()=>null | ||
exports.createFileWatcher=({wait:i=250,persistent:o=!1})=>{const l=(0,a.createHub)() | ||
let u | ||
let h | ||
let d | ||
let h | ||
let w | ||
let b | ||
const v=(0,r.throttle)(async()=>{const e=await(0,a.statAsync)(w).catch(s) | ||
const t=Boolean(b)!==Boolean(e) | ||
e||w!==l||await g() | ||
let v | ||
const f=(0,r.throttle)(async()=>{const e=await(0,n.statAsync)(b).catch(c) | ||
const t=Boolean(v)!==Boolean(e) | ||
e||b!==u||await p() | ||
if(!t&&!e)return | ||
const r={targetPath:w,isPathChange:t,targetStat:e} | ||
b=e | ||
o.send(r)},c) | ||
const y=async(...e)=>{await g() | ||
f("rename")} | ||
const f=(e,t)=>{v(e,t)} | ||
const m=()=>{d&&d.close() | ||
h&&h.close() | ||
l=null | ||
const r={targetPath:b,isPathChange:t,targetStat:e} | ||
v=e | ||
l.send(r)},i) | ||
const m=async(...e)=>{await p() | ||
y("rename")} | ||
const y=(e,t)=>{f(e,t)} | ||
const g=()=>{d&&d.close() | ||
w&&w.close() | ||
u=null | ||
h=null | ||
d=null | ||
h=null} | ||
const g=async()=>{const r=await(0,a.statAsync)(w).catch(s) | ||
if(r){m() | ||
l=w | ||
u=r;(d=(0,t.watch)(w,{persistent:i,recursive:!1})).addListener("error",y) | ||
d.addListener("change",f) | ||
if(r.isDirectory()){(h=(0,t.watch)((0,e.dirname)(w))).addListener("error",s) | ||
h.addListener("change",f)}}else{const e=await(0,a.nearestExistAsync)(w) | ||
if(e===l)return | ||
m() | ||
l=e | ||
u=r;(d=(0,t.watch)(e,{persistent:i,recursive:!1})).addListener("error",y) | ||
d.addListener("change",y)}} | ||
return{clear:()=>{m() | ||
o.clear() | ||
b=null},setup:async e=>{m() | ||
w=e | ||
await g() | ||
b=l===w?u:null},subscribe:e=>o.subscribe(e),unsubscribe:e=>o.unsubscribe(e)}} | ||
w=null} | ||
const p=async()=>{const r=await(0,n.statAsync)(b).catch(c) | ||
if(r){g() | ||
u=b | ||
h=r;(d=(0,t.watch)(b,{persistent:o,recursive:!1})).addListener("error",m) | ||
d.addListener("change",y) | ||
if(r.isDirectory()){(w=(0,t.watch)((0,e.dirname)(b))).addListener("error",c) | ||
w.addListener("change",y)}}else{const e=await(0,s.nearestExistPath)(b) | ||
if(e===u)return | ||
g() | ||
u=e | ||
h=r;(d=(0,t.watch)(e,{persistent:o,recursive:!1})).addListener("error",m) | ||
d.addListener("change",m)}} | ||
return{clear:()=>{g() | ||
l.clear() | ||
v=null},setup:async e=>{g() | ||
b=e | ||
await p() | ||
v=u===b?h:null},subscribe:e=>l.subscribe(e),unsubscribe:e=>l.unsubscribe(e)}} |
@@ -5,29 +5,30 @@ var t=require("path") | ||
var c=require("../../common/data/function") | ||
var i=require("../../common/immutable/StateStore") | ||
var r=require("../file/function") | ||
var n=require("../file/Directory") | ||
var o=require("./Logger") | ||
const s="factLog" | ||
const f="factCache" | ||
const l={id:0} | ||
const F={factId:0,factState:l,factCacheFile:"",factLogFile:""} | ||
var r=require("../../common/immutable/StateStore") | ||
var i=require("../data/Stream") | ||
var n=require("../file/function") | ||
var o=require("../file/Directory") | ||
var s=require("./Logger") | ||
const f="factLog" | ||
const l="factCache" | ||
const d={id:0} | ||
const F={factId:0,factState:d,factCacheFile:"",factLogFile:""} | ||
exports.INITIAL_FACT_INFO=F | ||
exports.createFactDatabase=async e=>{let{initialFactInfo:c,initialState:n=l,applyFact:u=((t,e)=>Object.assign({},t,{},e)),encodeFact:h=JSON.stringify,decodeFact:p=JSON.parse,pathFactDirectory:g,nameFactLogFile:y=s,nameFactCacheFile:I=f,onError:m}=e,S=function(t,e){if(null==t)return{} | ||
exports.createFactDatabase=async e=>{let{initialFactInfo:c,initialState:i=d,applyFact:o=((t,e)=>Object.assign({},t,{},e)),encodeFact:h=JSON.stringify,decodeFact:p=JSON.parse,pathFactDirectory:g,nameFactLogFile:m=f,nameFactCacheFile:y=l,onError:I}=e,S=function(t,e){if(null==t)return{} | ||
var a={} | ||
var c=Object.keys(t) | ||
var i,r | ||
for(r=0;r<c.length;r++){i=c[r] | ||
e.indexOf(i)>=0||(a[i]=t[i])}return a}(e,["initialFactInfo","initialState","applyFact","encodeFact","decodeFact","pathFactDirectory","nameFactLogFile","nameFactCacheFile","onError"]) | ||
void 0===c&&(c=await d(Object.assign({},F,{factState:n}),{applyFact:u,decodeFact:p,pathFactDirectory:g,nameFactLogFile:y,nameFactCacheFile:I})) | ||
var r,i | ||
for(i=0;i<c.length;i++){r=c[i] | ||
e.indexOf(r)>=0||(a[r]=t[r])}return a}(e,["initialFactInfo","initialState","applyFact","encodeFact","decodeFact","pathFactDirectory","nameFactLogFile","nameFactCacheFile","onError"]) | ||
void 0===c&&(c=await u(Object.assign({},F,{factState:i}),{applyFact:o,decodeFact:p,pathFactDirectory:g,nameFactLogFile:m,nameFactCacheFile:y})) | ||
let b=!0 | ||
let L=c.factId||0 | ||
let v=c.factCacheFile||"" | ||
const{getState:w,setState:C,subscribe:A,unsubscribe:O}=(0,i.createStateStore)(c.factState) | ||
const D=await(0,o.createLogger)(Object.assign({},S,{pathLogDirectory:g,getLogFileName:()=>`${y}.${L+1}.log`,onError:m})) | ||
const{trigger:j,getRunningPromise:x}=(0,a.lossyAsync)(async()=>{const e=(0,t.join)(g,`${I}.${L}.json`) | ||
const{getState:w,setState:C,subscribe:A,unsubscribe:O}=(0,r.createStateStore)(c.factState) | ||
const D=await(0,s.createLogger)(Object.assign({},S,{pathLogDirectory:g,getLogFileName:()=>`${m}.${L+1}.log`,onError:I})) | ||
const{trigger:j,getRunningPromise:x}=(0,a.lossyAsync)(async()=>{const e=(0,t.join)(g,`${y}.${L}.json`) | ||
if(v===e)return | ||
const a=JSON.stringify({factId:L,factState:w()}) | ||
await(0,r.writeFileAsync)(e,a) | ||
v&&await(0,r.unlinkAsync)(v).catch(t=>{}) | ||
v=e},m) | ||
await(0,n.writeFileAsync)(e,a) | ||
v&&await(0,n.unlinkAsync)(v).catch(t=>{}) | ||
v=e},I) | ||
return{getState:w,getIsActive:()=>b,getSaveFactCachePromise:x,subscribe:A,unsubscribe:O,add:t=>{if(b){if(L>=Number.MAX_SAFE_INTEGER)throw new Error(`factId is too big: ${L}`) | ||
@@ -37,36 +38,36 @@ t.id=L+1 | ||
D.add(h(t)) | ||
C(u(w(),t))}},save:()=>{b&&D.save()},split:()=>{if(b){D.split() | ||
C(o(w(),t))}},save:()=>{b&&D.save()},split:()=>{if(b){D.split() | ||
j()}},end:()=>{if(b){b=!1 | ||
D.end() | ||
j()}}}} | ||
const d=async(t,{applyFact:a,decodeFact:c,pathFactDirectory:i,nameFactLogFile:r,nameFactCacheFile:o})=>{const s=[] | ||
const u=async(t,{applyFact:a,decodeFact:c,pathFactDirectory:r,nameFactLogFile:i,nameFactCacheFile:n})=>{const s=[] | ||
const f=[] | ||
const{error:l}=await(0,e.catchAsync)(async()=>(await(0,n.getDirectorySubInfoList)(i)).forEach(({path:t,name:e})=>{e.startsWith(r)&&u.test(e)&&s.push({fileId:parseInt(u.exec(e)[1]),path:t,name:e}) | ||
e.startsWith(o)&&h.test(e)&&f.push({fileId:parseInt(h.exec(e)[1]),path:t,name:e})})) | ||
t=await p(t,{factCacheFileList:f}) | ||
return await g(t,{factLogFileList:s,decodeFact:c,applyFact:a})} | ||
exports.tryLoadFactInfo=d | ||
const u=/\.(\d+)\.log$/ | ||
const h=/\.(\d+)\.json$/ | ||
const p=async(t,{factCacheFileList:e})=>{e.sort((t,e)=>e.fileId-t.fileId) | ||
for(const a of e){const{path:e,name:i}=a | ||
const{factId:n,factState:o}=(0,c.tryParseJSONObject)(await(0,r.readFileAsync)(e)) | ||
if(n)return Object.assign({},t,{factId:n,factState:o,factCacheFile:e})}return t} | ||
const g=async(t,{factLogFileList:e,decodeFact:a,applyFact:c})=>{let{factId:i,factState:n,factLogFile:o=""}=t | ||
const s=e.reduce((t,{fileId:e})=>e<=i+1?Math.max(t,e):t,0) | ||
e=e.filter(({fileId:t})=>t>=s).sort((t,e)=>t.fileId-e.fileId) | ||
for(const t of e){const{path:e,name:s}=t | ||
await(0,r.createReadlineFromFileAsync)(e,t=>{const r=t&&a(t) | ||
if(r&&!(r.id<=i)){if(r.id!==i+1)throw new Error(`invalid factId: ${r.id}, should be: ${i+1}. file: ${s}`) | ||
n=c(n,r) | ||
i=r.id | ||
o=e}})}return Object.assign({},t,{factId:i,factState:n,factLogFile:o})} | ||
exports.tryDeleteExtraCache=async({pathFactDirectory:t,nameFactCacheFile:a=f,keepFactId:c=1/0,keepFileCount:i=2})=>{const o=(await(0,n.getDirectorySubInfoList)(t)).map(({path:t,name:e})=>{const c=e.startsWith(a)&&h.test(e)&&parseInt(h.exec(e)[1]) | ||
const{error:l}=await(0,e.catchAsync)(async()=>(await(0,o.getDirectorySubInfoList)(r)).forEach(({path:t,name:e})=>{e.startsWith(i)&&h.test(e)&&s.push({fileId:parseInt(h.exec(e)[1]),path:t,name:e}) | ||
e.startsWith(n)&&p.test(e)&&f.push({fileId:parseInt(p.exec(e)[1]),path:t,name:e})})) | ||
t=await g(t,{factCacheFileList:f}) | ||
return await m(t,{factLogFileList:s,decodeFact:c,applyFact:a})} | ||
exports.tryLoadFactInfo=u | ||
const h=/\.(\d+)\.log$/ | ||
const p=/\.(\d+)\.json$/ | ||
const g=async(t,{factCacheFileList:e})=>{e.sort((t,e)=>e.fileId-t.fileId) | ||
for(const a of e){const{path:e,name:r}=a | ||
const{factId:i,factState:o}=(0,c.tryParseJSONObject)(await(0,n.readFileAsync)(e)) | ||
if(i)return Object.assign({},t,{factId:i,factState:o,factCacheFile:e})}return t} | ||
const m=async(t,{factLogFileList:e,decodeFact:a,applyFact:c})=>{let{factId:r,factState:o,factLogFile:s=""}=t | ||
const f=e.reduce((t,{fileId:e})=>e<=r+1?Math.max(t,e):t,0) | ||
e=e.filter(({fileId:t})=>t>=f).sort((t,e)=>t.fileId-e.fileId) | ||
for(const t of e){const{path:e,name:f}=t | ||
await(0,i.createReadlineFromStreamAsync)((0,n.createReadStream)(e),t=>{const i=t&&a(t) | ||
if(i&&!(i.id<=r)){if(i.id!==r+1)throw new Error(`invalid factId: ${i.id}, should be: ${r+1}. file: ${f}`) | ||
o=c(o,i) | ||
r=i.id | ||
s=e}})}return Object.assign({},t,{factId:r,factState:o,factLogFile:s})} | ||
exports.tryDeleteExtraCache=async({pathFactDirectory:t,nameFactCacheFile:a=l,keepFactId:c=1/0,keepFileCount:r=2})=>{const i=(await(0,o.getDirectorySubInfoList)(t)).map(({path:t,name:e})=>{const c=e.startsWith(a)&&p.test(e)&&parseInt(p.exec(e)[1]) | ||
return Number.isInteger(c)&&{fileId:c,path:t,name:e}}).filter(Boolean) | ||
if(!o.length)return | ||
o.sort((t,e)=>e.fileId-t.fileId) | ||
if(!i.length)return | ||
i.sort((t,e)=>e.fileId-t.fileId) | ||
let s=0 | ||
for(const t of o){const{fileId:a,path:n,name:o}=t | ||
for(const t of i){const{fileId:a,path:i,name:o}=t | ||
if(a>=c)continue | ||
if(s<i){s+=1 | ||
continue}const{error:f}=await(0,e.catchAsync)(r.unlinkAsync,n)}} | ||
if(s<r){s+=1 | ||
continue}const{error:f}=await(0,e.catchAsync)(n.unlinkAsync,i)}} |
var e=require("path") | ||
var t=require("../data/LogQueue") | ||
var r=require("../file/File") | ||
var r=require("../file/Directory") | ||
var a=require("./SafeWrite") | ||
@@ -5,0 +5,0 @@ function l(e,t){if(null==e)return{} |
var e=require("../../../common/data/CacheMap") | ||
var t=require("../../../common/module/MIME") | ||
var r=require("../../file/function") | ||
var a=require("../../file/File") | ||
var a=require("../../file/Directory") | ||
var n=require("../../module/EntityTag") | ||
@@ -6,0 +6,0 @@ var s=require("./Send") |
var e=require("os") | ||
var t=require("../../common/format") | ||
var s=require("../../common/string") | ||
var r=require("../../common/error") | ||
var r=require("../../common/string") | ||
const o=()=>({platform:(0,e.platform)(),arch:(0,e.arch)(),release:(0,e.release)()}) | ||
exports.getSystemPlatform=o | ||
const i=({platform:e,arch:t,release:s}=o())=>`${e} ${t} [${s}]` | ||
exports.describeSystemPlatform=i | ||
const a=()=>(0,e.cpus)()||[{model:"N/A",speed:"N/A",times:{user:0,nice:0,sys:0,idle:0,irq:0}}] | ||
exports.getSystemProcessor=a | ||
const c=(e=a())=>e.map(({model:e,speed:s,times:r})=>`[${e}] speed:${s}MHz ${Object.entries(r).map(([e,s])=>`${e}:${(0,t.time)(s)}`).join(" ")}`).join("\n") | ||
exports.describeSystemProcessor=c | ||
const n=()=>({total:(0,e.totalmem)(),free:(0,e.freemem)()}) | ||
exports.getSystemMemory=n | ||
const m=({total:e,free:s}=n())=>[`Used: ${(0,t.percent)((e-s)/e)}`,`Total: ${(0,t.binary)(e)}B`,`Free: ${(0,t.binary)(s)}B`].join("\n") | ||
exports.describeSystemMemory=m | ||
const p=()=>({hostname:(0,e.hostname)(),networkInterface:(0,e.networkInterfaces)()}) | ||
exports.getSystemNetwork=p | ||
const d=({hostname:e,networkInterface:t}=p())=>[`[hostname] ${e}`,...Object.entries(t).map(([e,t])=>(0,s.indentList)(`[interface] ${e}`,t.map(({address:e,netmask:t,mac:s,internal:r,family:o,cidr:i})=>`[${o}${r?"|INTERNAL":""}] ${i||e} (${s})`)))].join("\n") | ||
exports.describeSystemNetwork=d | ||
const s=({platform:e,arch:t,release:r}=o())=>`${e} ${t} [${r}]` | ||
exports.describeSystemPlatform=s | ||
const m=()=>(0,e.cpus)()||[{model:"N/A",speed:"N/A",times:{user:0,nice:0,sys:0,idle:0,irq:0}}] | ||
exports.getSystemProcessor=m | ||
const n=(e=m())=>e.map(({model:e,speed:r,times:o})=>`[${e}] speed:${r}MHz ${Object.entries(o).map(([e,r])=>`${e}:${(0,t.time)(r)}`).join(" ")}`).join("\n") | ||
exports.describeSystemProcessor=n | ||
const a=()=>({total:(0,e.totalmem)(),free:(0,e.freemem)()}) | ||
exports.getSystemMemory=a | ||
const i=({total:e,free:r}=a())=>[`Used: ${(0,t.percent)((e-r)/e)}`,`Total: ${(0,t.binary)(e)}B`,`Free: ${(0,t.binary)(r)}B`].join("\n") | ||
exports.describeSystemMemory=i | ||
const c=()=>({hostname:(0,e.hostname)(),networkInterface:(0,e.networkInterfaces)()}) | ||
exports.getSystemNetwork=c | ||
const p=({hostname:e,networkInterface:t}=c())=>[`[hostname] ${e}`,...Object.entries(t).map(([e,t])=>(0,r.indentList)(`[interface] ${e}`,t.map(({address:e,netmask:t,mac:r,internal:o,family:s,cidr:m})=>`[${s}${o?"|INTERNAL":""}] ${m||e} (${r})`)))].join("\n") | ||
exports.describeSystemNetwork=p | ||
const l=()=>({uptime:1e3*(0,e.uptime)(),loadAverageList:(0,e.loadavg)()}) | ||
exports.getSystemActivity=l | ||
const y=({uptime:s,loadAverageList:r}=l())=>[`[uptime] ${(0,t.time)(s)}`,"win32"!==(0,e.platform)()&&`[load average] ${r.map(t.percent).join(", ")} (1min, 5min, 15min)`].filter(Boolean).join("\n") | ||
const y=({uptime:r,loadAverageList:o}=l())=>[`[uptime] ${(0,t.time)(r)}`,"win32"!==(0,e.platform)()&&`[load average] ${o.map(t.percent).join(", ")} (1min, 5min, 15min)`].filter(Boolean).join("\n") | ||
exports.describeSystemActivity=y | ||
const g=()=>({platform:o(),processor:a(),memory:n(),network:p(),activity:l()}) | ||
exports.getSystemStatus=g | ||
exports.describeSystemStatus=({platform:e,processor:t,memory:r,network:o,activity:a}=g())=>Object.entries({platform:i(e),processor:c(t),memory:m(r),network:d(o),activity:y(a)}).map(([e,t])=>`[${e}]\n${(0,s.indentLine)(t)}`).join("\n") | ||
exports.getCurrentProcessStatus=()=>({title:process.title,pid:process.pid,ppid:process.ppid,uid:(0,r.tryCall)(process,"getuid"),gid:(0,r.tryCall)(process,"getgid"),groups:(0,r.tryCall)(process,"getgroups")||[],euid:(0,r.tryCall)(process,"geteuid"),egid:(0,r.tryCall)(process,"getegid"),stdio:{stdin:u("stdin"),stdout:u("stdout"),stderr:u("stderr")},isConnectedIPC:Boolean(process.connected),execPath:process.execPath,execArgv:process.execArgv,argv:process.argv,cwd:process.cwd(),uptime:1e3*process.uptime(),cpuUsage:process.cpuUsage(),memoryUsage:process.memoryUsage()}) | ||
const u=e=>({isTTY:Boolean(process[e].isTTY)}) | ||
const d=()=>({platform:o(),processor:m(),memory:a(),network:c(),activity:l()}) | ||
exports.getSystemStatus=d | ||
exports.describeSystemStatus=({platform:e,processor:t,memory:o,network:m,activity:a}=d())=>Object.entries({platform:s(e),processor:n(t),memory:i(o),network:p(m),activity:y(a)}).map(([e,t])=>`[${e}]\n${(0,r.indentLine)(t)}`).join("\n") |
import { Readable } from "stream"; | ||
import { createInterface } from "readline"; | ||
const pipeStreamAsync = (writableStream, readableStream) => new Promise((resolve, reject) => { | ||
@@ -16,2 +17,19 @@ readableStream.on("error", reject); | ||
}; | ||
export { pipeStreamAsync, bufferToReadableStream }; | ||
const createReadlineFromStreamAsync = (readStream, onLineSync) => new Promise((resolve, reject) => { | ||
const readlineInterface = createInterface({ | ||
input: readStream, | ||
historySize: 0, | ||
crlfDelay: 1 / 0 | ||
}); | ||
readlineInterface.on("error", error => { | ||
readlineInterface.close(); | ||
reject(error); | ||
}); | ||
readlineInterface.on("close", () => { | ||
resolve(); | ||
}); | ||
readlineInterface.on("line", line => { | ||
onLineSync(line); | ||
}); | ||
}); | ||
export { pipeStreamAsync, bufferToReadableStream, createReadlineFromStreamAsync }; |
import { createGzip } from "zlib"; | ||
import { statAsync, unlinkAsync, readableAsync, createReadStream, createWriteStream } from "./function"; | ||
import { createReadStream, createWriteStream, statAsync, unlinkAsync, readableAsync } from "./function"; | ||
const compressFile = (inputFile, outputFile, compressStream = createGzip()) => new Promise((resolve, reject) => { | ||
@@ -4,0 +4,0 @@ const readStream = createReadStream(inputFile); |
@@ -1,4 +0,4 @@ | ||
import { join as joinPath, dirname, basename } from "path"; | ||
import { readdirAsync } from "./function"; | ||
import { FILE_TYPE, getPathStat, getPathTypeFromStat, createDirectory, deletePath, movePath, copyPath } from "./File"; | ||
import { join, dirname, basename } from "path"; | ||
import { readdirAsync, mkdirAsync } from "./function"; | ||
import { STAT_ERROR, PATH_TYPE, getPathStat, getPathTypeFromStat, movePath, copyPath, deletePath } from "./Path"; | ||
const getDirectorySubInfoList = async (path, pathStat) => { | ||
@@ -9,3 +9,3 @@ void 0 === pathStat && (pathStat = await getPathStat(path)); | ||
for (const name of await readdirAsync(path)) { | ||
const subPath = joinPath(path, name); | ||
const subPath = join(path, name); | ||
const stat = await getPathStat(subPath); | ||
@@ -69,2 +69,6 @@ const type = getPathTypeFromStat(stat); | ||
}; | ||
const moveDirectoryInfoTree = async ({root, subInfoListMap}, pathTo) => { | ||
await createDirectory(pathTo); | ||
for (const {path, name, stat} of subInfoListMap[root]) await movePath(path, join(pathTo, name), stat); | ||
}; | ||
const copyDirectoryInfoTree = async (infoTree, pathTo) => { | ||
@@ -77,3 +81,3 @@ await createDirectory(pathTo); | ||
const upperPath = dirname(path); | ||
const pathTo = joinPath(pathToMap[upperPath], name); | ||
const pathTo = join(pathToMap[upperPath], name); | ||
pathToMap[path] = pathTo; | ||
@@ -83,7 +87,16 @@ return copyPath(path, pathTo, stat); | ||
}; | ||
const moveDirectoryInfoTree = async ({root, subInfoListMap}, pathTo) => { | ||
await createDirectory(pathTo); | ||
for (const {path, name, stat} of subInfoListMap[root]) await movePath(path, joinPath(pathTo, name), stat); | ||
const deleteDirectoryInfoTree = async infoTree => walkDirectoryInfoTreeBottomUp(infoTree, ({path, stat}) => deletePath(path, stat)); | ||
const createDirectory = async (path, pathStat) => { | ||
void 0 === pathStat && (pathStat = await getPathStat(path)); | ||
if (!pathStat.isDirectory()) { | ||
if (pathStat !== STAT_ERROR) throw new Error(`path already taken by non-directory: ${path}`); | ||
await createDirectory(dirname(path)); | ||
await mkdirAsync(path); | ||
} | ||
}; | ||
const deleteDirectoryInfoTree = async infoTree => walkDirectoryInfoTreeBottomUp(infoTree, ({path, stat}) => deletePath(path, stat)); | ||
const copyDirectory = async (pathFrom, pathTo, pathStat) => copyDirectoryInfoTree(await getDirectoryInfoTree(pathFrom, pathStat), pathTo); | ||
const deleteDirectory = async (path, pathStat) => { | ||
await deleteDirectoryInfoTree(await getDirectoryInfoTree(path, pathStat)); | ||
return deletePath(path, pathStat); | ||
}; | ||
const getFileList = async (path, fileCollector = DEFAULT_FILE_COLLECTOR) => { | ||
@@ -94,3 +107,3 @@ const fileList = []; | ||
switch (pathType) { | ||
case FILE_TYPE.File: | ||
case PATH_TYPE.File: | ||
fileCollector(fileList, { | ||
@@ -103,4 +116,4 @@ path, | ||
break; | ||
case FILE_TYPE.Directory: | ||
await walkDirectoryInfoTree(await getDirectoryInfoTree(path, pathStat), info => info.type === FILE_TYPE.File && fileCollector(fileList, info)); | ||
case PATH_TYPE.Directory: | ||
await walkDirectoryInfoTree(await getDirectoryInfoTree(path, pathStat), info => info.type === PATH_TYPE.File && fileCollector(fileList, info)); | ||
break; | ||
@@ -113,2 +126,2 @@ default: | ||
const DEFAULT_FILE_COLLECTOR = (fileList, {path}) => fileList.push(path); | ||
export { getDirectorySubInfoList, getDirectoryInfoTree, walkDirectoryInfoTree, walkDirectoryInfoTreeBottomUp, copyDirectoryInfoTree, moveDirectoryInfoTree, deleteDirectoryInfoTree, getFileList }; | ||
export { getDirectorySubInfoList, getDirectoryInfoTree, walkDirectoryInfoTree, walkDirectoryInfoTreeBottomUp, moveDirectoryInfoTree, copyDirectoryInfoTree, deleteDirectoryInfoTree, createDirectory, copyDirectory, deleteDirectory, getFileList }; |
@@ -1,40 +0,5 @@ | ||
import { resolve as resolvePath, normalize, dirname, sep } from "path"; | ||
import { stat, open, rename, unlink, truncate, readFile, writeFile, appendFile, copyFile, mkdir, rmdir, readdir, createReadStream, createWriteStream, access, constants as fsConstants } from "fs"; | ||
import { promisify } from "util"; | ||
import { createInterface } from "readline"; | ||
const [statAsync, openAsync, renameAsync, unlinkAsync, truncateAsync, readFileAsync, writeFileAsync, appendFileAsync, copyFileAsync, mkdirAsync, rmdirAsync, readdirAsync] = [ stat, open, rename, unlink, truncate, readFile, writeFile, appendFile, copyFile, mkdir, rmdir, readdir ].map(fsFunc => promisify(fsFunc)); | ||
const [visibleAsync, readableAsync, writableAsync, executableAsync] = [ fsConstants.F_OK, fsConstants.R_OK, fsConstants.W_OK, fsConstants.X_OK ].map(mode => path => new Promise(resolve => access(path, mode, error => resolve(!error)))); | ||
const nearestExistAsync = async path => { | ||
for (;path && !await visibleAsync(path); ) path = dirname(path); | ||
return path; | ||
}; | ||
const createPathPrefixLock = rootPath => { | ||
rootPath = resolvePath(rootPath); | ||
return relativePath => { | ||
const absolutePath = resolvePath(rootPath, relativePath); | ||
if (!absolutePath.startsWith(rootPath)) throw new Error(`invalid relativePath: ${relativePath}`); | ||
return absolutePath; | ||
}; | ||
}; | ||
const createReadlineFromStreamAsync = (readStream, onLineSync) => new Promise((resolve, reject) => { | ||
const readlineInterface = createInterface({ | ||
input: readStream, | ||
historySize: 0, | ||
crlfDelay: 1 / 0 | ||
}); | ||
readlineInterface.on("error", error => { | ||
readlineInterface.close(); | ||
reject(error); | ||
}); | ||
readlineInterface.on("close", () => { | ||
resolve(); | ||
}); | ||
readlineInterface.on("line", line => { | ||
onLineSync(line); | ||
}); | ||
}); | ||
const createReadlineFromFileAsync = (filePath, onLineSync) => createReadlineFromStreamAsync(createReadStream(filePath), onLineSync); | ||
const trimPathDepth = (path, depth) => normalize(path).split(sep).slice(0, depth).join(sep); | ||
const REGEXP_PATH_SEP_WIN32 = /\\/g; | ||
const toPosixPath = path => path.replace(REGEXP_PATH_SEP_WIN32, "/"); | ||
export { createReadStream, createWriteStream, statAsync, openAsync, renameAsync, unlinkAsync, truncateAsync, readFileAsync, writeFileAsync, appendFileAsync, copyFileAsync, mkdirAsync, rmdirAsync, readdirAsync, visibleAsync, readableAsync, writableAsync, executableAsync, nearestExistAsync, createPathPrefixLock, createReadlineFromStreamAsync, createReadlineFromFileAsync, trimPathDepth, toPosixPath }; | ||
export { createReadStream, createWriteStream, statAsync, openAsync, renameAsync, unlinkAsync, truncateAsync, readFileAsync, writeFileAsync, appendFileAsync, copyFileAsync, mkdirAsync, rmdirAsync, readdirAsync, visibleAsync, readableAsync, writableAsync, executableAsync }; |
@@ -1,41 +0,20 @@ | ||
import { resolve, relative, dirname } from "path"; | ||
import { catchAsync } from "../../common/error"; | ||
import { nearestExistAsync, trimPathDepth } from "./function"; | ||
import { getPathStat, createDirectory, deletePath, movePath, copyPath } from "./File"; | ||
import { getDirectoryInfoTree, copyDirectoryInfoTree, deleteDirectoryInfoTree } from "./Directory"; | ||
const move = async (pathFrom, pathTo, pathStat) => { | ||
import { dirname } from "path"; | ||
import { getPathStat, deletePath, movePath, copyPath } from "./Path"; | ||
import { createDirectory, copyDirectory, deleteDirectory } from "./Directory"; | ||
const NULL_FUNC = () => {}; | ||
const modifyMove = async (pathFrom, pathTo, pathStat) => { | ||
await createDirectory(dirname(pathTo)); | ||
return movePath(pathFrom, pathTo, pathStat); | ||
}; | ||
const copyFile = async (pathFrom, pathTo, pathStat) => { | ||
const modifyCopy = async (pathFrom, pathTo, pathStat) => { | ||
void 0 === pathStat && (pathStat = await getPathStat(pathFrom)); | ||
if (pathStat.isDirectory()) return copyDirectory(pathFrom, pathTo, pathStat); | ||
await createDirectory(dirname(pathTo)); | ||
return copyPath(pathFrom, pathTo, pathStat); | ||
}; | ||
const deleteFile = (path, pathStat) => deletePath(path, pathStat); | ||
const copyDirectory = async (pathFrom, pathTo, pathStat) => copyDirectoryInfoTree(await getDirectoryInfoTree(pathFrom, pathStat), pathTo); | ||
const deleteDirectory = async (path, pathStat) => { | ||
await deleteDirectoryInfoTree(await getDirectoryInfoTree(path, pathStat)); | ||
return deletePath(path); | ||
const modifyDelete = async (path, pathStat) => { | ||
void 0 === pathStat && (pathStat = await getPathStat(path)); | ||
return pathStat.isDirectory() ? deleteDirectory(path, pathStat) : deletePath(path, pathStat); | ||
}; | ||
const modify = { | ||
move, | ||
copy: async (pathFrom, pathTo, pathStat) => { | ||
void 0 === pathStat && (pathStat = await getPathStat(pathFrom)); | ||
return pathStat.isDirectory() ? copyDirectory(pathFrom, pathTo, pathStat) : copyFile(pathFrom, pathTo, pathStat); | ||
}, | ||
delete: async (path, pathStat) => { | ||
void 0 === pathStat && (pathStat = await getPathStat(path)); | ||
return pathStat.isDirectory() ? deleteDirectory(path, pathStat) : deleteFile(path, pathStat); | ||
} | ||
}; | ||
const withTempDirectory = async (tempPath, asyncTask) => { | ||
const existPath = await nearestExistAsync(tempPath); | ||
await createDirectory(tempPath); | ||
if (existPath === tempPath) return asyncTask(); | ||
const deletePath = resolve(existPath, trimPathDepth(relative(existPath, tempPath), 1)); | ||
const {result, error} = await catchAsync(asyncTask); | ||
await deleteDirectory(deletePath); | ||
if (error) throw error; | ||
return result; | ||
}; | ||
export { move, copyFile, deleteFile, copyDirectory, deleteDirectory, modify, withTempDirectory }; | ||
const modifyDeleteForce = async (path, pathStat) => modifyDelete(path, pathStat).catch(NULL_FUNC); | ||
export { modifyMove, modifyCopy, modifyDelete, modifyDeleteForce }; |
@@ -5,3 +5,4 @@ import { dirname } from "path"; | ||
import { createHub } from "../../common/module/Event"; | ||
import { statAsync, nearestExistAsync } from "./function"; | ||
import { statAsync } from "./function"; | ||
import { nearestExistPath } from "./Path"; | ||
const getNull = () => null; | ||
@@ -60,8 +61,8 @@ const createFileWatcher = ({wait = 250, persistent = !1}) => { | ||
} else { | ||
const nearestExistPath = await nearestExistAsync(targetPath); | ||
if (nearestExistPath === watcherPath) return; | ||
const nearestPath = await nearestExistPath(targetPath); | ||
if (nearestPath === watcherPath) return; | ||
clearWatch(); | ||
watcherPath = nearestExistPath; | ||
watcherPath = nearestPath; | ||
watcherPathStat = targetStat; | ||
(watcher = watch(nearestExistPath, { | ||
(watcher = watch(nearestPath, { | ||
persistent, | ||
@@ -68,0 +69,0 @@ recursive: !1 |
@@ -6,3 +6,4 @@ import { join as joinPath } from "path"; | ||
import { createStateStore } from "../../common/immutable/StateStore"; | ||
import { readFileAsync, writeFileAsync, unlinkAsync, createReadlineFromFileAsync } from "../file/function"; | ||
import { createReadlineFromStreamAsync } from "../data/Stream"; | ||
import { readFileAsync, writeFileAsync, unlinkAsync, createReadStream } from "../file/function"; | ||
import { getDirectorySubInfoList } from "../file/Directory"; | ||
@@ -130,3 +131,3 @@ import { createLogger } from "./Logger"; | ||
factLogFileList = factLogFileList.filter(({fileId}) => fileId >= maxFactLogId).sort((a, b) => a.fileId - b.fileId); | ||
for (const {path, name} of factLogFileList) await createReadlineFromFileAsync(path, logText => { | ||
for (const {path, name} of factLogFileList) await createReadlineFromStreamAsync(createReadStream(path), logText => { | ||
const fact = logText && decodeFact(logText); | ||
@@ -133,0 +134,0 @@ if (fact && !(fact.id <= factId)) { |
import { resolve } from "path"; | ||
import { createLogQueue } from "../data/LogQueue"; | ||
import { createDirectory } from "../file/File"; | ||
import { createDirectory } from "../file/Directory"; | ||
import { createSafeWriteStream } from "./SafeWrite"; | ||
@@ -5,0 +5,0 @@ const createSimpleLogger = ({queueLengthThreshold, ...extraOption}) => createLogQueue({ |
import { createCacheMap } from "../../../common/data/CacheMap"; | ||
import { getMIMETypeFromFileName } from "../../../common/module/MIME"; | ||
import { readFileAsync, createReadStream } from "../../file/function"; | ||
import { getPathStat } from "../../file/File"; | ||
import { getPathStat } from "../../file/Directory"; | ||
import { getWeakEntityTagByStat } from "../../module/EntityTag"; | ||
@@ -6,0 +6,0 @@ import { responderSendBuffer, responderSendBufferRange, responderSendBufferCompress, responderSendStream, responderSendStreamRange } from "./Send"; |
import { arch, platform, release, hostname, cpus, networkInterfaces, totalmem, freemem, loadavg, uptime } from "os"; | ||
import { percent, time, binary } from "../../common/format"; | ||
import { indentLine, indentList } from "../../common/string"; | ||
import { tryCall } from "../../common/error"; | ||
const getSystemPlatform = () => ({ | ||
@@ -52,28 +51,2 @@ platform: platform(), | ||
}).map(([k, v]) => `[${k}]\n${indentLine(v)}`).join("\n"); | ||
const getCurrentProcessStatus = () => ({ | ||
title: process.title, | ||
pid: process.pid, | ||
ppid: process.ppid, | ||
uid: tryCall(process, "getuid"), | ||
gid: tryCall(process, "getgid"), | ||
groups: tryCall(process, "getgroups") || [], | ||
euid: tryCall(process, "geteuid"), | ||
egid: tryCall(process, "getegid"), | ||
stdio: { | ||
stdin: getStdio("stdin"), | ||
stdout: getStdio("stdout"), | ||
stderr: getStdio("stderr") | ||
}, | ||
isConnectedIPC: Boolean(process.connected), | ||
execPath: process.execPath, | ||
execArgv: process.execArgv, | ||
argv: process.argv, | ||
cwd: process.cwd(), | ||
uptime: 1e3 * process.uptime(), | ||
cpuUsage: process.cpuUsage(), | ||
memoryUsage: process.memoryUsage() | ||
}); | ||
const getStdio = name => ({ | ||
isTTY: Boolean(process[name].isTTY) | ||
}); | ||
export { getSystemPlatform, getSystemProcessor, getSystemMemory, getSystemNetwork, getSystemActivity, getSystemStatus, describeSystemPlatform, describeSystemProcessor, describeSystemMemory, describeSystemNetwork, describeSystemActivity, describeSystemStatus, getCurrentProcessStatus }; | ||
export { getSystemPlatform, getSystemProcessor, getSystemMemory, getSystemNetwork, getSystemActivity, getSystemStatus, describeSystemPlatform, describeSystemProcessor, describeSystemMemory, describeSystemNetwork, describeSystemActivity, describeSystemStatus }; |
@@ -1,1 +0,1 @@ | ||
{"name":"dr-js","version":"0.23.0-dev.0","description":"A collection of strange functions","author":"dr-js","license":"MIT","repository":"github:dr-js/dr-js","bin":"bin/index.js","browser":"library/Dr.browser.js","engines":{"node":">=10.16","npm":">=6.10"},"sideEffects":false} | ||
{"name":"dr-js","version":"0.23.0-dev.1","description":"A collection of strange functions","author":"dr-js","license":"MIT","repository":"github:dr-js/dr-js","bin":"bin/index.js","browser":"library/Dr.browser.js","engines":{"node":">=10.16","npm":">=6.10"},"sideEffects":false} |
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 2 instances in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 3 instances in 1 package
26
427566
9869