添加 kit 子目录
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* 系统配置
|
||||
*/
|
||||
const os = require('os');
|
||||
const process = require('process');
|
||||
const path = require("path");
|
||||
const fs = require('fs');
|
||||
|
||||
module.exports = class SystemConfig {
|
||||
|
||||
constructor() {
|
||||
}
|
||||
|
||||
static isWindows(){
|
||||
return os.platform() === 'win32'
|
||||
}
|
||||
|
||||
static isLinux(){
|
||||
return os.platform() === 'linux'
|
||||
}
|
||||
|
||||
static getShellEncode(){
|
||||
if ( this.isWindows() ) {
|
||||
return "GBK"
|
||||
} else {
|
||||
return "UTF-8"
|
||||
}
|
||||
}
|
||||
|
||||
static getLocalKitPath(){
|
||||
let path = "./"
|
||||
if ( this.isWindows() ) {
|
||||
path = require('path').dirname(require.main.filename)
|
||||
} else {
|
||||
path = process.execPath;
|
||||
}
|
||||
this.affirmDir(path)
|
||||
$logger.debug(`LocalKitPath=${path}`)
|
||||
return path;
|
||||
}
|
||||
|
||||
static getLocalStorePath(){
|
||||
const path = require("path")
|
||||
let dir = path.resolve(this.getLocalKitPath(), ".kit")
|
||||
this.affirmDir(dir)
|
||||
return dir;
|
||||
}
|
||||
|
||||
static getUserPath() {
|
||||
let userDirectory = '~';
|
||||
if ( this.isWindows() ) {
|
||||
userDirectory = process.env.USERPROFILE;
|
||||
}
|
||||
return userDirectory;
|
||||
}
|
||||
|
||||
static getUserConfigPath() {
|
||||
const path = require("path")
|
||||
const dir = path.resolve( this.getUserPath() , ".kit");
|
||||
this.affirmDir(dir)
|
||||
return dir;
|
||||
}
|
||||
|
||||
static getUserConfigFilePath() {
|
||||
const path = require("path")
|
||||
return path.resolve( this.getUserPath() , ".kit", "config.json");
|
||||
}
|
||||
|
||||
static getLogPath() {
|
||||
const path = require("path")
|
||||
let logs = path.resolve( this.getUserPath() , ".kit", "logs");
|
||||
this.affirmDir(logs)
|
||||
return logs
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保目录存在
|
||||
* @param path
|
||||
*/
|
||||
static affirmDir(path){
|
||||
// 检查文件夹是否存在
|
||||
const exists = fs.existsSync(path);
|
||||
|
||||
if (! exists) {
|
||||
// 文件夹不存在
|
||||
try {
|
||||
fs.mkdirSync(path, { recursive: true });
|
||||
} catch (err) {
|
||||
// 处理错误
|
||||
log.error(`affirmDir ${path} error ${ err }`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* 读写用户配置
|
||||
* 实时维护状态
|
||||
*/
|
||||
const fs = require("fs")
|
||||
const JSON5 = require('json5')
|
||||
module.exports = class UserConfig {
|
||||
constructor(path) {
|
||||
this.path = path
|
||||
this.init()
|
||||
}
|
||||
|
||||
init(){
|
||||
let txt = "{}";
|
||||
try {
|
||||
txt = fs.readFileSync(this.path, 'utf8')
|
||||
} catch ( err ) {
|
||||
if (err.code === 'ENOENT') {
|
||||
// File does not exist.
|
||||
txt = '{}';
|
||||
} else {
|
||||
// Some other error occurred. Throw it.
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
this.configs = JSON5.parse( txt )
|
||||
this.setDefault("man", "https://flowus.cn/fullstack/share/acd5b26f-b3d1-4d41-a58e-e4f23daf9db8")
|
||||
|
||||
}
|
||||
|
||||
get(key) {
|
||||
return this.configs[key]
|
||||
}
|
||||
|
||||
set(key, value) {
|
||||
this.configs[key] = value
|
||||
this.write()
|
||||
}
|
||||
|
||||
setDefault(key, value){
|
||||
if ( ! this.configs[key] ) {
|
||||
this.configs[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
write(){
|
||||
fs.writeFileSync(this.path, JSON5.stringify(this.configs, undefined, 4))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* config 模块处理配置相关事务
|
||||
*/
|
||||
const SystemConfig = require("./SystemConfig")
|
||||
const UserConfig = require("./UserConfig")
|
||||
|
||||
|
||||
module.exports = {
|
||||
SystemConfig, UserConfig
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* 对象管理
|
||||
* 懒加载对象
|
||||
*/
|
||||
const config = require("../config");
|
||||
module.exports = class Context {
|
||||
constructor() {
|
||||
this.beans = {}
|
||||
this.standalones = {}
|
||||
}
|
||||
standalone(name, factory){
|
||||
if ( this.standalones[name] ){
|
||||
throw `重定义 ${name}`
|
||||
}
|
||||
|
||||
if ( ! factory ) {
|
||||
throw `定义 ${name} 时未提供必须参数 factory`
|
||||
}
|
||||
|
||||
this.standalones[name] = factory
|
||||
}
|
||||
async get(name){
|
||||
if ( this.beans[name] ) {
|
||||
return this.beans[name]
|
||||
}
|
||||
if ( this.standalones[name] ){
|
||||
this.beans[name] = await this.standalones[name]()
|
||||
return this.beans[name]
|
||||
} else {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
const sm4 = require('sm-crypto').sm4
|
||||
const sm3 = require('sm-crypto').sm3
|
||||
|
||||
|
||||
module.exports.sm4en3 = function (key, data){
|
||||
let sm3key = sm3(key)
|
||||
sm3key = sm3key.substring(0, 32)
|
||||
let encryptData = sm4.encrypt(data, sm3key)
|
||||
return encryptData
|
||||
}
|
||||
|
||||
|
||||
module.exports.sm4de3 = function (key, data){
|
||||
let sm3key = sm3(key)
|
||||
sm3key = sm3key.substring(0, 32)
|
||||
let decryptData = sm4.decrypt(data, sm3key)
|
||||
return decryptData
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
/**
|
||||
* kit cli 注册和调用执行
|
||||
*/
|
||||
require("./init")
|
||||
const { CliCmdParser } = require("../../argv")
|
||||
const parser = new CliCmdParser("kit V" + $version);
|
||||
const net = require("./net")
|
||||
const shell = require("./shell")
|
||||
const {sm4en3, sm4de3} = require("./crypto");
|
||||
const convutil = require("./util/convutil")
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
const {sm3} = require("sm-crypto");
|
||||
const zlib = require("zlib");
|
||||
|
||||
parser.addCmdLine("man", "打开在线帮助;", async function (){
|
||||
const uConfig = await $context.get("uConfig")
|
||||
shell.execSync("start " + uConfig.get("man"))
|
||||
});
|
||||
parser.addCmdLine("manu", "人工维护配置;", function (){
|
||||
shell.execSync("start " + $sConfig.getUserConfigPath())
|
||||
});
|
||||
|
||||
parser.addCmdLine("run [--file] [func]", "运行项目脚本;", function (cli) {
|
||||
$logger.info( "kit 当前执行目录 " + process.cwd());
|
||||
const fs = require("fs");
|
||||
|
||||
let step = cli.getParamValue("func");
|
||||
if ( ! step ) {
|
||||
step = "main"
|
||||
}
|
||||
|
||||
let file = cli.getParamValue("file");
|
||||
if ( ! file ) {
|
||||
file = "kit"
|
||||
}
|
||||
|
||||
const stat = fs.existsSync(`./${file}.js`)
|
||||
if ( ! stat ) {
|
||||
if ( ! cli.getParamValue("file") ) {
|
||||
fs.writeFileSync("./kit.js",
|
||||
`
|
||||
async function main(){
|
||||
console.log("hello kit!")
|
||||
}
|
||||
`);
|
||||
} else {
|
||||
$logger.info( `文件 ${file} 不存在` );
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const projectScript = fs.readFileSync("./kit.js", "utf-8");
|
||||
const vm = require('node:vm');
|
||||
const script = new vm.Script(projectScript + ";" + step + "()");
|
||||
const context = {
|
||||
animal: 'cat',
|
||||
count: 2,
|
||||
$logger
|
||||
};
|
||||
|
||||
script.runInNewContext(context, {
|
||||
timeout : 10 * 60 * 1000,
|
||||
breakOnSigint : true,
|
||||
});
|
||||
$logger.info( "暂未实现" );
|
||||
});
|
||||
|
||||
parser.addCmdLine("config <key> [value]", "查询/设置配置;", async function (cli){
|
||||
let key = cli.getParamValue("key");
|
||||
let value = cli.getParamValue("value");
|
||||
const uConfig = await $context.get("uConfig")
|
||||
if (null != key && null == value) {
|
||||
let v = uConfig.get(key);
|
||||
$logger.info("{} : {}", key, v);
|
||||
} else if (null != key && null != value) {
|
||||
uConfig.set(key, value);
|
||||
$logger.info("set {} : {}", key, value);
|
||||
} else {
|
||||
$logger.error("参数异常");
|
||||
}
|
||||
});
|
||||
|
||||
parser.addCmdLine("remote-check", "验证远程仓库;", async function (){
|
||||
let remote = await $context.get("remote")
|
||||
if (! ( await remote.check()) ) {
|
||||
$logger.error("远程仓库不可用")
|
||||
return
|
||||
} else {
|
||||
$logger.info("远程仓库可用")
|
||||
}
|
||||
});
|
||||
|
||||
parser.addCmdLine("publish", "发布到远程仓库;", async function (){
|
||||
let remote = await $context.get("remote")
|
||||
if (! ( await remote.check()) ) {
|
||||
$logger.error("远程仓库不可用")
|
||||
return
|
||||
} else {
|
||||
$logger.info("远程仓库可用")
|
||||
}
|
||||
remote.publish()
|
||||
});
|
||||
parser.addCmdLine("install [module]", "安装/更新模块;", async function (cli){
|
||||
let remote = await $context.get("remote")
|
||||
if (! ( await remote.check()) ) {
|
||||
$logger.error("远程仓库不可用")
|
||||
return
|
||||
} else {
|
||||
$logger.info("远程仓库可用")
|
||||
}
|
||||
remote.install(cli.getParamValue("module"))
|
||||
});
|
||||
|
||||
parser.addCmdLine("killport <port>", "释放端口", function (cli) {
|
||||
let port = cli.getParamValue("port")
|
||||
net.killport( parseInt(port, 10) );
|
||||
});
|
||||
|
||||
|
||||
parser.addCmdLine("getport [--port]", "获取一个可用端口;或查询指定端口状态;", async function (cli) {
|
||||
const getPort = await import('get-port').then(psl => psl.default);
|
||||
let port = cli.getParamValue("port")
|
||||
if( ! port ) {
|
||||
let ret = await getPort()
|
||||
$logger.info(`端口 ${ret} 未被使用`)
|
||||
} else {
|
||||
await net.getport( port )
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
parser.addCmdLine("checkip", "获取自己的公网 ip;", async function (cli) {
|
||||
let ret = await net.checkip()
|
||||
if( "ok" === ret.ret ) {
|
||||
$logger.info( "ip : " + ret.data.ip )
|
||||
$logger.info( "location : " + ret.data.location.join(" ") )
|
||||
$logger.info("\n" + ret.data.ip)
|
||||
} else {
|
||||
$logger.error("获取失败")
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
parser.addCmdLine("telnet [--timeout] <ip-port> [port]", "验证远程 TCP 端口是否可用;", async function (cli) {
|
||||
let ip = cli.getParamValue("ip-port")
|
||||
let port = 80;
|
||||
|
||||
// 允许冒号形式指定端口
|
||||
const re = /^(?<ip>.*):(?<port>[0-9]+)$/
|
||||
const match = ip.match( re );
|
||||
if ( match ) {
|
||||
ip = match.groups.ip;
|
||||
port = match.groups.port;
|
||||
} else {
|
||||
// 如果指定了 port 参数,那么使用 port 参数
|
||||
let dport = cli.getParamValue("port")
|
||||
if ( dport ) {
|
||||
port = dport;
|
||||
}
|
||||
}
|
||||
|
||||
// 支持不填写 ip,默认访问本地
|
||||
if( "" === ip.trim() ) {
|
||||
ip = "127.0.0.1";
|
||||
}
|
||||
|
||||
try {
|
||||
await net.telnet(port, ip, cli.getParamValue("timeout"))
|
||||
$logger.info("连接成功")
|
||||
}catch (e) {
|
||||
$logger.error( e )
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
parser.addCmdLine("checklist <checkListFile>", "生成/验证文件 hash", async function (cli) {
|
||||
let checkListFile = cli.getParamValue("checkListFile")
|
||||
if ( !fs.existsSync( checkListFile ) ) {
|
||||
$logger.error(`file ${checkListFile} 不存在`)
|
||||
process.exit(-2)
|
||||
}
|
||||
const sm3 = require('sm-crypto').sm3
|
||||
const list = fs.readFileSync(checkListFile, "UTF-8")
|
||||
const files = list.split('\n').filter(line => line.trim() !== '');
|
||||
for ( let file of files ) {
|
||||
const infos = file.split(/\s+/)
|
||||
const info = {}
|
||||
if ( infos.length > 2 ) {
|
||||
info.file = infos[0]
|
||||
info.hash = infos[1]
|
||||
info.alg = infos[2]
|
||||
} else {
|
||||
info.file = infos[0]
|
||||
info.hash = infos[1]
|
||||
info.alg = "md5"
|
||||
}
|
||||
if ( "sm3" === info.alg ) {
|
||||
if ( !fs.existsSync( info.file ) ) {
|
||||
$logger.error(`file ${info.file} 不存在`)
|
||||
process.exit(-2)
|
||||
}
|
||||
|
||||
const data = fs.readFileSync(info.file);
|
||||
const arrayBuffer = Buffer.from(data);
|
||||
const uint8Array = new Uint8Array(arrayBuffer);
|
||||
let hashData = sm3( uint8Array ) // 杂凑
|
||||
if ( hashData === info.hash ) {
|
||||
$logger.info(`file ${file} 验证通过`)
|
||||
} else {
|
||||
$logger.error(`file ${file} 验证不通过`)
|
||||
process.exit(-400)
|
||||
}
|
||||
|
||||
} else {
|
||||
$logger.error(`不支持 file ${file} `)
|
||||
process.exit(-2)
|
||||
}
|
||||
}
|
||||
|
||||
$logger.info(`${checkListFile} 中的文件全部验证通过`)
|
||||
|
||||
})
|
||||
|
||||
parser.addCmdLine("sm3 [--file] [--text] [--hash]", "生成/验证 SM3 值;", async function (cli) {
|
||||
let filePath = cli.getParamValue("file")
|
||||
let text = cli.getParamValue("text")
|
||||
if( !filePath && !text ) {
|
||||
$logger.error(`file 和 text 入参不能同时有`)
|
||||
process.exit(-1)
|
||||
}
|
||||
const sm3 = require('sm-crypto').sm3
|
||||
if ( text ) {
|
||||
let hashData = sm3( text ) // 杂凑
|
||||
$logger.info( hashData )
|
||||
}
|
||||
if ( filePath ) {
|
||||
if ( !fs.existsSync( filePath ) ) {
|
||||
$logger.error(`file ${filePath} 不存在`)
|
||||
process.exit(-2)
|
||||
}
|
||||
const data = fs.readFileSync(filePath);
|
||||
const arrayBuffer = Buffer.from(data);
|
||||
const uint8Array = new Uint8Array(arrayBuffer);
|
||||
let hashData = sm3( uint8Array ) // 杂凑
|
||||
$logger.info( hashData )
|
||||
}
|
||||
});
|
||||
|
||||
parser.addCmdLine("sm4en3 <key> <data>", "sm4 加密,密钥通过 sm3 制备;", function (cli) {
|
||||
const {sm4en3} = require("./crypto");
|
||||
let key = cli.getParamValue("key")
|
||||
let data = cli.getParamValue("data")
|
||||
let out = sm4en3( key, data )
|
||||
$logger.info( out );
|
||||
});
|
||||
|
||||
parser.addCmdLine("sm4de3 <key> <data>", "sm4 解密,密钥通过 sm3 制备;", function (cli) {
|
||||
const {sm4de3} = require("./crypto");
|
||||
let key = cli.getParamValue("key")
|
||||
let data = cli.getParamValue("data")
|
||||
let out = sm4de3( key, data )
|
||||
$logger.info( out );
|
||||
});
|
||||
|
||||
// parser.addCmdLine("base64 <-en/-de> <data>", "base64 编解码", function (cli) {
|
||||
parser.addCmdLine("base64 [-en] [-de] [-hex] <data>", "base64 编解码;", function (cli) {
|
||||
let data = cli.getParamValue("data")
|
||||
if ( cli.hasFlag("de") ) {
|
||||
if ( cli.hasFlag("hex") ) {
|
||||
$logger.info( "执行 base64 decode to hex: " );
|
||||
$logger.info( convutil.base64ToHex( data ) );
|
||||
} else {
|
||||
$logger.info( "执行 base64 decode to string: " );
|
||||
$logger.info( convutil.base64ToString( data ) );
|
||||
}
|
||||
} else {
|
||||
if ( cli.hasFlag("hex") ) {
|
||||
$logger.info( "执行 hex encode to base64: " );
|
||||
$logger.info( convutil.hexToBase64( data ) );
|
||||
} else {
|
||||
$logger.info( "执行 string encode to base64: " );
|
||||
$logger.info( convutil.stringToBase64( data ) );
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
parser.addCmdLine("replace [-d] <file_name> <re1> <re2>", "文件内容正则替换;", function (cli) {
|
||||
$logger.info( "暂未实现" );
|
||||
});
|
||||
|
||||
parser.addCmdLine("crlf [-d] [-r] [--path] [--filter-name] [--filter-path] <crlf:{CRLF,CR,LF,\\r\\n,\\r,\\n}>", "回车一致化", function (cli) {
|
||||
$logger.info( "暂未实现" );
|
||||
});
|
||||
|
||||
parser.addCmdLine("tcpc [-d] [-x] [--host] [--ip] [--port] [--headlen] [--timeout] [--filepath]", "tcp 报文发收", function (cli) {
|
||||
$logger.info( "暂未实现" );
|
||||
});
|
||||
|
||||
async function main(){
|
||||
|
||||
try {
|
||||
let cmd = parser.parse(process.argv.slice(2))
|
||||
if ( ! cmd ) {
|
||||
console.log( parser.help() )
|
||||
} else {
|
||||
$logger.info(`执行命令 ${cmd.cmdline.cmd}`)
|
||||
if ( cmd.canEval() ){
|
||||
await cmd.eval()
|
||||
} else {
|
||||
console.log( parser.help() )
|
||||
}
|
||||
}
|
||||
} catch ( e ) {
|
||||
console.error( e )
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
const config = require('./config')
|
||||
const Context = require("./context")
|
||||
const log4js = require("log4js");
|
||||
// const layout = log4js.layouts.patternLayout('%m')
|
||||
if ( ! global.$inited ) {
|
||||
init()
|
||||
} else {
|
||||
// 不再初始化
|
||||
}
|
||||
|
||||
|
||||
function init(){
|
||||
global.$inited = true
|
||||
|
||||
const package = require("../package.json")
|
||||
global.$version = package.version
|
||||
|
||||
// 上下文模块
|
||||
global.$context = new Context();
|
||||
|
||||
// 载入日志
|
||||
const log4js = require('log4js');
|
||||
log4js.configure({
|
||||
appenders: {
|
||||
console: { type: 'stdout' , level: "info", layout: {
|
||||
type: "pattern",
|
||||
pattern: "%m",
|
||||
},},
|
||||
},
|
||||
categories: {
|
||||
default: { appenders: ['console'], level: 'debug' },
|
||||
}
|
||||
});
|
||||
global.$logger = log4js.getLogger();
|
||||
|
||||
|
||||
// 载入配置
|
||||
global.$sConfig = config.SystemConfig
|
||||
// 重载版本号
|
||||
try {
|
||||
global.$version = fs.readFileSync($sConfig.getLocalKitPath() + "/version", "UTF-8")
|
||||
}catch ( e ) {}
|
||||
|
||||
let logPath = global.$sConfig.getLogPath();
|
||||
global.$context.standalone("uConfig", function (){
|
||||
return new config.UserConfig( $sConfig.getUserConfigFilePath() )
|
||||
})
|
||||
log4js.addLayout('customLayout', function(config) {
|
||||
return function(logEvent) {
|
||||
const now = new Date(logEvent.startTime)
|
||||
let time = now.toLocaleTimeString();
|
||||
time += "." + now.getMilliseconds().toString().padStart(3, '0');
|
||||
const level = "" + logEvent.level;
|
||||
const categoryName = logEvent.categoryName;
|
||||
const message = logEvent.data[0];
|
||||
if ( message && message.startsWith && message.startsWith("\r") ) {
|
||||
return message;
|
||||
}
|
||||
|
||||
let logMessage = `${time} ${level} - ${message}`;
|
||||
|
||||
// Add color to log message based on log level
|
||||
switch (level) {
|
||||
case 'INFO':
|
||||
logMessage = `\x1b[32m${logMessage}\x1b[0m`; // Green color for INFO log level
|
||||
break;
|
||||
case 'WARN':
|
||||
logMessage = `\x1b[33m${logMessage}\x1b[0m`; // Yellow color for WARN log level
|
||||
break;
|
||||
case 'ERROR':
|
||||
logMessage = `\x1b[31m${logMessage}\x1b[0m`; // Red color for ERROR log level
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return logMessage;
|
||||
};
|
||||
});
|
||||
// 重置日志配置
|
||||
log4js.configure({
|
||||
appenders: {
|
||||
console: { type: 'console' , level: "info", layout: {
|
||||
type: 'customLayout'
|
||||
}},
|
||||
file: { type: 'dateFile', filename: logPath + '/kit.log', "pattern": "yyyy-MM-dd", "compress": true , alwaysIncludePattern : true, keepFileExt : true, numBackups : 7}
|
||||
},
|
||||
categories: {
|
||||
default: { appenders: ['console', 'file'], level: 'debug' },
|
||||
}
|
||||
});
|
||||
|
||||
// 注册:远程仓库
|
||||
global.$context.standalone("remote", async function (){
|
||||
const Remote = require("./remote")
|
||||
const remote = new Remote();
|
||||
await remote.init()
|
||||
return remote
|
||||
})
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
function getModuleInfo(){
|
||||
|
||||
}
|
||||
|
||||
module.exports = { getModuleInfo }
|
||||
@@ -0,0 +1,33 @@
|
||||
|
||||
|
||||
async function killport(port) {
|
||||
$logger.info(`kill process on port ${port}`);
|
||||
const util = require('util');
|
||||
const exec = util.promisify(require('child_process').exec);
|
||||
|
||||
try {
|
||||
// 查 PID
|
||||
let { stdout : stdout1 } = exec(`lsof -t -sTCP:LISTEN -i:${port}`)
|
||||
let pid = stdout1.trim();
|
||||
$logger.debug(`绑定端口号 ${port} 的进程 PID=${pid}`)
|
||||
|
||||
// 查进程信息
|
||||
let { stdout : stdout2 } = exec(`ps -p ${pid} -o comm=`)
|
||||
let processName = stdout2.trim();
|
||||
$logger.info(`绑定端口号=${port}; 进程 PID=${pid}; 程序=${processName};`);
|
||||
|
||||
// Kill 进程
|
||||
exec(`kill -9 ${pid}`)
|
||||
|
||||
} catch (e) {
|
||||
if ( 1 === e.code ) {
|
||||
$logger.error("此端口未被使用,或清理进程失败。")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
module.exports = {
|
||||
killport
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
require("./init")
|
||||
const osutil = require("./util/osutil")
|
||||
const killer = require('cross-port-killer');
|
||||
const net = require('node:net');
|
||||
|
||||
|
||||
/**
|
||||
* 模拟 telnet ,检测端口是否开放
|
||||
* @param port
|
||||
* @param host
|
||||
* @param timeout
|
||||
* @returns {Promise<unknown>}
|
||||
*/
|
||||
async function telnet(port, host, timeout=3000){
|
||||
$logger.debug(`port=${port} host=${host} timeout=${timeout}`)
|
||||
return new Promise(function (resolve, reject){
|
||||
const socket = new net.Socket();
|
||||
|
||||
socket.setTimeout(timeout, function() {
|
||||
socket.end();
|
||||
reject("链接超时")
|
||||
});
|
||||
|
||||
socket.connect(port, host);
|
||||
|
||||
socket.on('connect', function() {
|
||||
resolve('连接成功');
|
||||
socket.end();
|
||||
});
|
||||
|
||||
socket.on('error', function(err) {
|
||||
reject('连接失败');
|
||||
});
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
async function killport(port) {
|
||||
return killer.kill( port );
|
||||
// let func = osutil.choise([
|
||||
// require("./windows/net").killport,
|
||||
// require("./linux/net").killport,
|
||||
// ])
|
||||
// return func && func(port);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取端口信息
|
||||
* 因为命令输出缓存问题,有缺陷。
|
||||
* @param port
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function getport(port) {
|
||||
$logger.info( "暂未实现" );
|
||||
}
|
||||
|
||||
|
||||
async function checkip(){
|
||||
const url = "https://myip.ipip.net/json"
|
||||
const http = url.startsWith("https:") ? require("node:https") : require('node:http');
|
||||
return new Promise((resolve, reject) => {
|
||||
http.get(url, (res) => {
|
||||
let data = '';
|
||||
|
||||
// A chunk of data has been recieved.
|
||||
res.on('data', (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
|
||||
// The whole response has been received. Resolve the promise with result
|
||||
res.on('end', () => {
|
||||
resolve(JSON.parse(data));
|
||||
});
|
||||
|
||||
}).on("error", (err) => {
|
||||
// In case of any error reject the promise
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
killport, getport, telnet, checkip
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
/**
|
||||
* remote 模块用来处理远程仓库相关事务
|
||||
*/
|
||||
const path = require("path")
|
||||
const fs = require("fs")
|
||||
const JSON5 = require('json5')
|
||||
const { pipeline, Transform} = require("node:stream/promises");
|
||||
|
||||
module.exports = class Remote {
|
||||
|
||||
constructor() {
|
||||
this.init()
|
||||
this.func_publish = require("./publish")
|
||||
this.func_install = require("./install")
|
||||
}
|
||||
|
||||
|
||||
|
||||
async init() {
|
||||
this.webdav = await import("webdav");
|
||||
const uConfig = await $context.get("uConfig");
|
||||
if ( uConfig.get("remoteServer") ){
|
||||
let server = uConfig.get("remoteServer");
|
||||
if ( server.startsWith("webdav") ) {
|
||||
server = "http" + server.substring(6)
|
||||
}
|
||||
|
||||
if ( uConfig.get("remoteAuth") ) {
|
||||
let up = uConfig.get("remoteAuth");
|
||||
up = up.split(":", 2)
|
||||
this.client = this.webdav.createClient(
|
||||
server,
|
||||
{
|
||||
username: up[0],
|
||||
password: up[1]
|
||||
}
|
||||
);
|
||||
} else {
|
||||
this.client = this.webdav.createClient(
|
||||
server
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async check() {
|
||||
|
||||
if ( ! this.webdav ) {
|
||||
return false
|
||||
}
|
||||
|
||||
if ( ! this.client ) {
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
// Get directory contents
|
||||
const directoryItems = await this.client.getDirectoryContents("/");
|
||||
// 是否包含 index.json ?
|
||||
// 不包含尝试创建
|
||||
// 包含了尝试下载
|
||||
const indexJsonFile = this.getIndexJson( directoryItems );
|
||||
if ( indexJsonFile ) {
|
||||
// 包含了尝试下载
|
||||
// 下载有缓存
|
||||
this.download(indexJsonFile)
|
||||
|
||||
} else {
|
||||
// 不包含尝试创建
|
||||
await this.affireRemoteStore()
|
||||
}
|
||||
|
||||
|
||||
return true
|
||||
}catch ( e ) {
|
||||
$logger.error("remote check 过程中出错", e)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 先对比时间和长度,有不同才会真正下载,否则使用本地缓存。
|
||||
* 本地缓存路径即本地仓库路径
|
||||
* @param rFile
|
||||
*/
|
||||
download(rFile){
|
||||
const lFilePath = path.resolve($sConfig.getLocalStorePath(), rFile.filename);
|
||||
if ( fs.existsSync( lFilePath ) ) {
|
||||
const lFileInfo = fs.statSync(lFilePath);
|
||||
if ( lFileInfo.size === rFile.length
|
||||
&& lFileInfo.mtime === rFile.lastmod
|
||||
) {
|
||||
// 使用缓存
|
||||
$logger.debug("use cache")
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// 下载并覆盖
|
||||
// 不知道是同步还是异步
|
||||
this.wDownload( rFile.filename, lFilePath );
|
||||
|
||||
|
||||
}
|
||||
|
||||
async affireRemoteStore(){
|
||||
// Get directory contents
|
||||
const directoryItems = await this.client.getDirectoryContents("/");
|
||||
// 是否包含 index.json ?
|
||||
// 不包含尝试创建
|
||||
// 包含了尝试下载
|
||||
const indexJsonFile = this.getIndexJson( directoryItems );
|
||||
if ( ! indexJsonFile ) {
|
||||
// 创建 index
|
||||
await this.client.putFileContents("/index.json", JSON5.stringify({
|
||||
modules : [],
|
||||
tmpls : [],
|
||||
lists : []
|
||||
}, null, 4) , { overwrite: false });
|
||||
}
|
||||
|
||||
const modulesFolder = this.getFileInfoByName(directoryItems, "modules")
|
||||
if ( ! modulesFolder ) {
|
||||
// 创建文件夹
|
||||
await this.client.createDirectory("/modules");
|
||||
}
|
||||
|
||||
const tmplsFolder = this.getFileInfoByName(directoryItems, "tmpls")
|
||||
if ( ! tmplsFolder ) {
|
||||
// 创建文件夹
|
||||
await this.client.createDirectory("/tmpls");
|
||||
}
|
||||
|
||||
const listsFolder = this.getFileInfoByName(directoryItems, "lists")
|
||||
if ( ! listsFolder ) {
|
||||
// 创建文件夹
|
||||
await this.client.createDirectory("/lists");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
getIndexJson(items){
|
||||
return this.getFileInfoByName( items, "index.json" );
|
||||
}
|
||||
getFileInfoByName(items, name){
|
||||
if ( ! items || items.length < 1 ) {
|
||||
return false;
|
||||
}
|
||||
for ( let item of items ) {
|
||||
if ( item.basename === name ) {
|
||||
return item;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async publish(){
|
||||
return this.func_publish( this )
|
||||
}
|
||||
|
||||
async install(id){
|
||||
return this.func_install( this, id )
|
||||
}
|
||||
|
||||
async wUpload(from, to){
|
||||
const totalSize = fs.statSync(from).size;
|
||||
const rs = fs.createReadStream( from );
|
||||
let wSize = 0;
|
||||
let rSize = 0;
|
||||
rs.on("data", (r)=>{
|
||||
rSize += r.length;
|
||||
// console.log("r", rSize * 100 / totalSize)
|
||||
})
|
||||
const ws = this.client.createWriteStream(to)
|
||||
ws.on("data", (r)=>{
|
||||
wSize += r.length;
|
||||
// console.log("w", wSize * 100 / totalSize)
|
||||
})
|
||||
return pipeline( rs, ws);
|
||||
}
|
||||
|
||||
async wDownload(from, to){
|
||||
$logger.info("download", from, to )
|
||||
const stat = await this.client.stat(from);
|
||||
const totalSize = stat.size;
|
||||
let wSize = 0;
|
||||
let rSize = 0;
|
||||
|
||||
const rs = this.client.createReadStream(from);
|
||||
rs.on("data", (r)=>{
|
||||
rSize += r.length;
|
||||
// console.log("r", rSize * 100 / totalSize)
|
||||
})
|
||||
|
||||
const ws = fs.createWriteStream(to);
|
||||
ws.on("data", (r)=>{
|
||||
wSize += r.length;
|
||||
// console.log("w", wSize * 100 / totalSize)
|
||||
})
|
||||
return pipeline(
|
||||
rs, ws
|
||||
)
|
||||
}
|
||||
|
||||
async wMkdir(folder){
|
||||
|
||||
const folderfather = path.dirname( folder );
|
||||
if ( ! await this.client.exists( folderfather ) ) {
|
||||
// await remote.client.createDirectory( folderfather )
|
||||
await this.wMkdir( folderfather )
|
||||
}
|
||||
|
||||
if ( await this.client.exists( folder ) ) {
|
||||
return
|
||||
} else {
|
||||
await this.client.createDirectory( folder )
|
||||
}
|
||||
}
|
||||
|
||||
async wGetModuleInfo(id){
|
||||
let meta = await this.client.getFileContents("/modules/" + id + "/meta.json", { format: "text" });
|
||||
let metaJson = JSON5.parse( meta );
|
||||
return metaJson
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
const os = require('os');
|
||||
const fs = require("fs");
|
||||
const osutil = require("../util/osutil")
|
||||
|
||||
function matchDistName(cur, dists){
|
||||
const list = []
|
||||
for (let dist of dists) {
|
||||
if ( cur.curOS === dist.os && cur.curPlatform === dist.platform) {
|
||||
list.push( dist )
|
||||
}
|
||||
else if ( cur.curOS === dist.os && "cross" === dist.platform) {
|
||||
list.unshift( dist )
|
||||
}
|
||||
else if ( "cross" === dist.os && cur.curPlatform === dist.platform) {
|
||||
list.unshift( dist )
|
||||
}
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
|
||||
module.exports = async function install(remote, id){
|
||||
const cur = osutil.cur();
|
||||
|
||||
if ( ! id ) {
|
||||
id = "kit"
|
||||
}
|
||||
|
||||
// 获取本地版本
|
||||
const localInfo = osutil.choise([
|
||||
require("../windows/local").getModuleInfo,
|
||||
require("../linux/local").getModuleInfo,
|
||||
])( id )
|
||||
|
||||
$logger.info("local version", localInfo.version)
|
||||
|
||||
// 确认远程版本文件是否存在
|
||||
const remoteInfo = await remote.wGetModuleInfo(id)
|
||||
$logger.info("remote latest version", remoteInfo.latest.version)
|
||||
|
||||
const dists = matchDistName(cur, remoteInfo.latest.dist)
|
||||
const dist = dists.pop()
|
||||
|
||||
await remote.wDownload(
|
||||
"/modules/" + id + "/" + remoteInfo.latest.version + "/" + cur.curOS + "/" + cur.curPlatform + "/" + dist.filename,
|
||||
localInfo.homeDir + "/" + dist.filename,
|
||||
)
|
||||
|
||||
fs.writeFileSync( localInfo.homeDir + "/version", remoteInfo.latest.version );
|
||||
|
||||
$logger.info("当前版本", remoteInfo.latest.version )
|
||||
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
const path = require("path")
|
||||
const fs = require("fs")
|
||||
const JSON5 = require('json5')
|
||||
const { pipeline } = require('node:stream/promises');
|
||||
const objutil = require("../util/objutil")
|
||||
module.exports = async function publish(remote, meta){
|
||||
|
||||
let curPath = process.cwd();
|
||||
const metaFilePath = path.resolve( curPath, "meta.json" );
|
||||
if ( ! fs.existsSync( metaFilePath ) ) {
|
||||
$logger.error("当前路径不包含 meta.json")
|
||||
return
|
||||
}
|
||||
|
||||
const metaFile = fs.readFileSync(metaFilePath);
|
||||
|
||||
const localMeta = JSON5.parse( metaFile );
|
||||
|
||||
// 更新版本
|
||||
const date = new Date();
|
||||
localMeta.version = `${localMeta.version}.${date.getFullYear()}${(date.getMonth() + 1).toString().padStart(2, '0')}${date.getDate().toString().padStart(2, '0')}${date.getHours().toString().padStart(2, '0')}${date.getMinutes().toString().padStart(2, '0')}${date.getSeconds().toString().padStart(2, '0')}`;
|
||||
|
||||
|
||||
// 确认目录
|
||||
// const directoryItems = await remote.getDirectoryContents("/modules");
|
||||
// const modulesFolder = remote.getFileInfoByName(directoryItems, localMeta.id)
|
||||
if ( ! await remote.client.exists("/modules/" + localMeta.id) ) {
|
||||
// 创建文件夹
|
||||
await remote.client.createDirectory("/modules/" + localMeta.id);
|
||||
}
|
||||
|
||||
// 先更新文件
|
||||
for (let dist of localMeta.dist ) {
|
||||
|
||||
const folder = "/modules/" + localMeta.id + "/" + localMeta.version + "/" + dist.os + "/" + dist.platform
|
||||
await remote.wMkdir( folder );
|
||||
|
||||
$logger.info("upload dist", dist.path, fs.existsSync(dist.path))
|
||||
|
||||
await remote.wUpload( dist.path , folder + "/" + dist.filename );
|
||||
|
||||
}
|
||||
|
||||
// remote meta
|
||||
let remoteMeta = {
|
||||
"versions" : []
|
||||
}
|
||||
try {
|
||||
const remoteMetaStr = await remote.client.getFileContents("/modules/" + localMeta.id + "/meta.json", { format: "text" });
|
||||
remoteMeta = JSON5.parse( remoteMetaStr )
|
||||
} catch (e) {
|
||||
|
||||
}
|
||||
|
||||
remoteMeta.id = localMeta.id;
|
||||
remoteMeta.name = localMeta.name;
|
||||
remoteMeta.desc = localMeta.desc;
|
||||
remoteMeta.type = localMeta.type;
|
||||
remoteMeta.vcs = localMeta.vcs;
|
||||
// 废弃
|
||||
// remoteMeta.platform = "cross" === localMeta.platform ? ["X86_64", "ARM64"] : localMeta.platform;
|
||||
// remoteMeta.os = "cross" === localMeta.os ? ["Windows", "Linux", "Alpine"] : localMeta.os;
|
||||
const dist = objutil.copy(localMeta.dist)
|
||||
for (let d of dist) {
|
||||
delete dist.path
|
||||
}
|
||||
remoteMeta.latest = {
|
||||
version : localMeta.version,
|
||||
dist
|
||||
}
|
||||
remoteMeta.versions.push(remoteMeta.latest)
|
||||
if ( remoteMeta.versions.length >= 20 ) {
|
||||
remoteMeta.versions = remoteMeta.versions.slice(0, 20);
|
||||
}
|
||||
|
||||
await remote.client.putFileContents("/modules/" + localMeta.id + "/meta.json", JSON5.stringify(remoteMeta, null, 4) , { overwrite: true });
|
||||
|
||||
$logger.info("发布成功")
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
*
|
||||
* child_process
|
||||
* - exec 适合短时间命令,获取完整输出
|
||||
* - execFile 适合实时交互
|
||||
* - spawn 适合长时间命令
|
||||
*
|
||||
* shelljs - https://www.npmjs.com/package/shelljs
|
||||
* execa - https://www.npmjs.com/package/execa
|
||||
* ssh2 - https://www.npmjs.com/package/ssh2
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
|
||||
const { execSync } = require('child_process');
|
||||
|
||||
|
||||
|
||||
|
||||
module.exports = {
|
||||
execSync(cmd){
|
||||
$logger.debug(`execSync ${cmd}`)
|
||||
const output = execSync(cmd);
|
||||
return output.toString()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
var codePoint2utf8 = function (code) {
|
||||
var bin = parseInt(code).toString(2)
|
||||
var ln = 0;
|
||||
var mx = 0;
|
||||
if (bin.length <= 7) {
|
||||
ln = 1;
|
||||
mx = 7;
|
||||
} else if (bin.length > 7 && bin.length <= 11) {
|
||||
ln = 2;
|
||||
mx = 11;
|
||||
} else if (bin.length > 11 && bin.length <= 16) {
|
||||
ln = 3;
|
||||
mx = 16;
|
||||
} else if (bin.length > 16 && bin.length <= 21) {
|
||||
ln = 4;
|
||||
mx = 21;
|
||||
} else if (bin.length > 21 && bin.length <= 26) {
|
||||
ln = 5;
|
||||
mx = 26;
|
||||
} else if (bin.length > 26 && bin.length <= 31) {
|
||||
ln = 6;
|
||||
mx = 31;
|
||||
};
|
||||
var longbin = ("0".repeat(mx) + bin).slice(-mx)
|
||||
var result = '';
|
||||
for (var i = 0; i < ln; i++) {
|
||||
if (ln != 1) {
|
||||
if (i == 0) {
|
||||
result += parseInt("1".repeat(ln) + "0" + longbin.slice(0,7-ln),2).toString(16);
|
||||
longbin = longbin.slice(7-ln);
|
||||
} else {
|
||||
result += parseInt("10" + longbin.slice(0,6),2).toString(16);
|
||||
longbin = longbin.slice(6);
|
||||
};
|
||||
} else {
|
||||
result += ("00" + parseInt(longbin,2).toString(16)).slice(-2);
|
||||
};
|
||||
};
|
||||
return result;
|
||||
};
|
||||
|
||||
var stringToHex = function (inputstring) {
|
||||
var result = '';
|
||||
for (var i = 0; i < inputstring.length; i++) {
|
||||
result += codePoint2utf8(inputstring.codePointAt(i))
|
||||
};
|
||||
return result;
|
||||
};
|
||||
|
||||
var hexToString = function (inputstring) {
|
||||
try {
|
||||
var result = decodeURIComponent(inputstring.toLowerCase().replace(/\s+/g, '').replace(/[0-9a-f]{2}/g, '%$&'));
|
||||
} catch(e) {
|
||||
throw "Not valid UTF-8 hex code!";
|
||||
};
|
||||
return result;
|
||||
};
|
||||
|
||||
|
||||
function stringToByte(str) {
|
||||
var bytes = new Array();
|
||||
var len, c;
|
||||
len = str.length;
|
||||
for(var i = 0; i < len; i++) {
|
||||
c = str.charCodeAt(i);
|
||||
if(c >= 0x010000 && c <= 0x10FFFF) {
|
||||
bytes.push(((c >> 18) & 0x07) | 0xF0);
|
||||
bytes.push(((c >> 12) & 0x3F) | 0x80);
|
||||
bytes.push(((c >> 6) & 0x3F) | 0x80);
|
||||
bytes.push((c & 0x3F) | 0x80);
|
||||
} else if(c >= 0x000800 && c <= 0x00FFFF) {
|
||||
bytes.push(((c >> 12) & 0x0F) | 0xE0);
|
||||
bytes.push(((c >> 6) & 0x3F) | 0x80);
|
||||
bytes.push((c & 0x3F) | 0x80);
|
||||
} else if(c >= 0x000080 && c <= 0x0007FF) {
|
||||
bytes.push(((c >> 6) & 0x1F) | 0xC0);
|
||||
bytes.push((c & 0x3F) | 0x80);
|
||||
} else {
|
||||
bytes.push(c & 0xFF);
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
|
||||
|
||||
}
|
||||
// utf8
|
||||
function byteToString(arr) {
|
||||
if(typeof arr === 'string') {
|
||||
return arr;
|
||||
}
|
||||
var str = '',
|
||||
_arr = arr;
|
||||
for(var i = 0; i < _arr.length; i++) {
|
||||
var one = _arr[i].toString(2),
|
||||
v = one.match(/^1+?(?=0)/);
|
||||
if(v && one.length == 8) {
|
||||
var bytesLength = v[0].length;
|
||||
var store = _arr[i].toString(2).slice(7 - bytesLength);
|
||||
for(var st = 1; st < bytesLength; st++) {
|
||||
store += _arr[st + i].toString(2).slice(2);
|
||||
}
|
||||
str += String.fromCharCode(parseInt(store, 2));
|
||||
i += bytesLength - 1;
|
||||
} else {
|
||||
str += String.fromCharCode(_arr[i]);
|
||||
}
|
||||
}
|
||||
return str;
|
||||
}
|
||||
/**
|
||||
* Convert the given string to byte array
|
||||
*
|
||||
* @param {string} str the string to be converted to byte array
|
||||
* @returns {number[]}
|
||||
*/
|
||||
var str2bytes = function (str) {
|
||||
var i = 0;
|
||||
var ch = null;
|
||||
var hex = null;
|
||||
var encoded = encodeURIComponent(str);
|
||||
var length = encoded.length;
|
||||
var bytes = [];
|
||||
|
||||
while (i < length) {
|
||||
ch = encoded.charAt(i++);
|
||||
if (ch === '%') {
|
||||
hex = encoded.charAt(i++)
|
||||
hex += encoded.charAt(i++);
|
||||
bytes.push(parseInt(hex, 16));
|
||||
} else {
|
||||
bytes.push(ch.charCodeAt(0));
|
||||
}
|
||||
}
|
||||
|
||||
return bytes;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert the given byte array to string
|
||||
*
|
||||
* @param {number[]} bytes The byte array to be converted to string
|
||||
* @returns {string}
|
||||
*/
|
||||
var bytes2str = function (bytes) {
|
||||
var i = 0;
|
||||
var hex = null;
|
||||
var byte = 0;
|
||||
var hexArray = [];
|
||||
var length = bytes.length;
|
||||
|
||||
while (i < length) {
|
||||
byte = bytes[i++];
|
||||
hex = byte.toString(16);
|
||||
hex = hex.length < 2 ? ('%0' + hex) : ('%' + hex);
|
||||
hexArray.push(hex);
|
||||
}
|
||||
|
||||
return decodeURIComponent(hexArray.join(''));
|
||||
};
|
||||
function base64ArrayBuffer(arrayBuffer) {
|
||||
var base64 = ''
|
||||
var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
|
||||
|
||||
var bytes = new Uint8Array(arrayBuffer)
|
||||
var byteLength = bytes.byteLength
|
||||
var byteRemainder = byteLength % 3
|
||||
var mainLength = byteLength - byteRemainder
|
||||
|
||||
var a, b, c, d
|
||||
var chunk
|
||||
|
||||
// Main loop deals with bytes in chunks of 3
|
||||
for (var i = 0; i < mainLength; i = i + 3) {
|
||||
// Combine the three bytes into a single integer
|
||||
chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
|
||||
|
||||
// Use bitmasks to extract 6-bit segments from the triplet
|
||||
a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
|
||||
b = (chunk & 258048) >> 12 // 258048 = (2^6 - 1) << 12
|
||||
c = (chunk & 4032) >> 6 // 4032 = (2^6 - 1) << 6
|
||||
d = chunk & 63 // 63 = 2^6 - 1
|
||||
|
||||
// Convert the raw binary segments to the appropriate ASCII encoding
|
||||
base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
|
||||
}
|
||||
|
||||
// Deal with the remaining bytes and padding
|
||||
if (byteRemainder == 1) {
|
||||
chunk = bytes[mainLength]
|
||||
|
||||
a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2
|
||||
|
||||
// Set the 4 least significant bits to zero
|
||||
b = (chunk & 3) << 4 // 3 = 2^2 - 1
|
||||
|
||||
base64 += encodings[a] + encodings[b] + '=='
|
||||
} else if (byteRemainder == 2) {
|
||||
chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]
|
||||
|
||||
a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
|
||||
b = (chunk & 1008) >> 4 // 1008 = (2^6 - 1) << 4
|
||||
|
||||
// Set the 2 least significant bits to zero
|
||||
c = (chunk & 15) << 2 // 15 = 2^4 - 1
|
||||
|
||||
base64 += encodings[a] + encodings[b] + encodings[c] + '='
|
||||
}
|
||||
|
||||
return base64
|
||||
}
|
||||
|
||||
(function() {
|
||||
var base64EncodeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
|
||||
base64DecodeChars = new Array(( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), 62, ( - 1), ( - 1), ( - 1), 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, ( - 1), ( - 1), ( - 1), ( - 1), ( - 1));
|
||||
this.base64encode = function(e) {
|
||||
var r, a, c, h, o, t;
|
||||
for (c = e.length, a = 0, r = ''; a < c;) {
|
||||
if (h = 255 & e.charCodeAt(a++), a == c) {
|
||||
r += base64EncodeChars.charAt(h >> 2),
|
||||
r += base64EncodeChars.charAt((3 & h) << 4),
|
||||
r += '==';
|
||||
break
|
||||
}
|
||||
if (o = e.charCodeAt(a++), a == c) {
|
||||
r += base64EncodeChars.charAt(h >> 2),
|
||||
r += base64EncodeChars.charAt((3 & h) << 4 | (240 & o) >> 4),
|
||||
r += base64EncodeChars.charAt((15 & o) << 2),
|
||||
r += '=';
|
||||
break
|
||||
}
|
||||
t = e.charCodeAt(a++),
|
||||
r += base64EncodeChars.charAt(h >> 2),
|
||||
r += base64EncodeChars.charAt((3 & h) << 4 | (240 & o) >> 4),
|
||||
r += base64EncodeChars.charAt((15 & o) << 2 | (192 & t) >> 6),
|
||||
r += base64EncodeChars.charAt(63 & t)
|
||||
}
|
||||
return r
|
||||
}
|
||||
this.base64decode = function(e) {
|
||||
var r, a, c, h, o, t, d;
|
||||
for (t = e.length, o = 0, d = ''; o < t;) {
|
||||
do r = base64DecodeChars[255 & e.charCodeAt(o++)];
|
||||
while (o < t && r == -1);
|
||||
if (r == -1) break;
|
||||
do a = base64DecodeChars[255 & e.charCodeAt(o++)];
|
||||
while (o < t && a == -1);
|
||||
if (a == -1) break;
|
||||
d += String.fromCharCode(r << 2 | (48 & a) >> 4);
|
||||
do {
|
||||
if (c = 255 & e.charCodeAt(o++), 61 == c) return d;
|
||||
c = base64DecodeChars[c]
|
||||
} while ( o < t && c == - 1 );
|
||||
if (c == -1) break;
|
||||
d += String.fromCharCode((15 & a) << 4 | (60 & c) >> 2);
|
||||
do {
|
||||
if (h = 255 & e.charCodeAt(o++), 61 == h) return d;
|
||||
h = base64DecodeChars[h]
|
||||
} while ( o < t && h == - 1 );
|
||||
if (h == -1) break;
|
||||
d += String.fromCharCode((3 & c) << 6 | h)
|
||||
}
|
||||
return d
|
||||
}
|
||||
this.HexToBase64 = function(str) {
|
||||
return base64encode(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
|
||||
}
|
||||
this.Base64Tohex = function(str) {
|
||||
for (var i = 0,
|
||||
bin = base64decode(str.replace(/[ \r\n]+$/, "")), hex = []; i < bin.length; ++i) {
|
||||
var tmp = bin.charCodeAt(i).toString(16);
|
||||
if (tmp.length === 1) tmp = "0" + tmp;
|
||||
hex[hex.length] = tmp;
|
||||
}
|
||||
return hex.join("");
|
||||
},
|
||||
this.toBytes = function(str) {
|
||||
for (var bytes = [], c = 0; c < str.length; c += 2)
|
||||
bytes.push(parseInt(str.substr(c, 2), 16));
|
||||
return bytes;
|
||||
}
|
||||
|
||||
}) ();
|
||||
//hexToBase64 Base64Tohex base64decode base64encode
|
||||
|
||||
var bytesToString = function(bytes){
|
||||
return hexToString(bytesToHex(bytes));
|
||||
}
|
||||
|
||||
|
||||
var bytesToBase64 = function(bytes){
|
||||
return base64ArrayBuffer(bytes);
|
||||
}
|
||||
|
||||
// Convert a byte array to a hex string
|
||||
var bytesToHex = function(bytes) {
|
||||
for (var hex = [], i = 0; i < bytes.length; i++) {
|
||||
hex.push((bytes[i] >>> 4).toString(16));
|
||||
hex.push((bytes[i] & 0xF).toString(16));
|
||||
}
|
||||
return hex.join("");
|
||||
}
|
||||
|
||||
|
||||
var stringToBase64 = function(str){
|
||||
return base64encode(str);
|
||||
}
|
||||
|
||||
var stringToBytes = function(str){
|
||||
return hexToBytes(stringToHex(str));
|
||||
}
|
||||
|
||||
// Convert a ASCII string to a hex string
|
||||
var stringToHex = function(str) {
|
||||
return str.split("").map(function(c) {
|
||||
return ("0" + c.charCodeAt(0).toString(16)).slice(-2);
|
||||
}).join("");
|
||||
}
|
||||
|
||||
var hexToBytes= function(hex) {
|
||||
for (var bytes = [], c = 0; c < hex.length; c += 2)
|
||||
bytes.push(parseInt(hex.substr(c, 2), 16));
|
||||
return bytes;
|
||||
}
|
||||
|
||||
// Convert a hex string to a ASCII string
|
||||
var hexToString = function(hexStr) {
|
||||
var hex = hexStr.toString();//force conversion
|
||||
var str = '';
|
||||
for (var i = 0; i < hex.length; i += 2)
|
||||
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
|
||||
return str;
|
||||
}
|
||||
|
||||
var hexToBase64 = function(hexStr){
|
||||
return HexToBase64(hexStr);
|
||||
}
|
||||
|
||||
var base64ToString = function(base64str){
|
||||
return base64decode(base64str);
|
||||
}
|
||||
|
||||
|
||||
const Base64 = {
|
||||
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
|
||||
encode: function(e) {
|
||||
var t = "";
|
||||
var n, r, i, s, o, u, a;
|
||||
var f = 0;
|
||||
e = Base64._utf8_encode(e);
|
||||
while (f < e.length) {
|
||||
n = e.charCodeAt(f++);
|
||||
r = e.charCodeAt(f++);
|
||||
i = e.charCodeAt(f++);
|
||||
s = n >> 2;
|
||||
o = (n & 3) << 4 | r >> 4;
|
||||
u = (r & 15) << 2 | i >> 6;
|
||||
a = i & 63;
|
||||
if (isNaN(r)) {
|
||||
u = a = 64
|
||||
} else if (isNaN(i)) {
|
||||
a = 64
|
||||
}
|
||||
t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
|
||||
}
|
||||
return t
|
||||
},
|
||||
decode: function(e) {
|
||||
var t = "";
|
||||
var n, r, i;
|
||||
var s, o, u, a;
|
||||
var f = 0;
|
||||
e = e.replace(/[^A-Za-z0-9+/=]/g, "");
|
||||
while (f < e.length) {
|
||||
s = this._keyStr.indexOf(e.charAt(f++));
|
||||
o = this._keyStr.indexOf(e.charAt(f++));
|
||||
u = this._keyStr.indexOf(e.charAt(f++));
|
||||
a = this._keyStr.indexOf(e.charAt(f++));
|
||||
n = s << 2 | o >> 4;
|
||||
r = (o & 15) << 4 | u >> 2;
|
||||
i = (u & 3) << 6 | a;
|
||||
t = t + String.fromCharCode(n);
|
||||
if (u != 64) {
|
||||
t = t + String.fromCharCode(r)
|
||||
}
|
||||
if (a != 64) {
|
||||
t = t + String.fromCharCode(i)
|
||||
}
|
||||
}
|
||||
t = Base64._utf8_decode(t);
|
||||
return t
|
||||
},
|
||||
_utf8_encode: function(e) {
|
||||
e = e.replace(/rn/g, "n");
|
||||
var t = "";
|
||||
for (var n = 0; n < e.length; n++) {
|
||||
var r = e.charCodeAt(n);
|
||||
if (r < 128) {
|
||||
t += String.fromCharCode(r)
|
||||
} else if (r > 127 && r < 2048) {
|
||||
t += String.fromCharCode(r >> 6 | 192);
|
||||
t += String.fromCharCode(r & 63 | 128)
|
||||
} else {
|
||||
t += String.fromCharCode(r >> 12 | 224);
|
||||
t += String.fromCharCode(r >> 6 & 63 | 128);
|
||||
t += String.fromCharCode(r & 63 | 128)
|
||||
}
|
||||
}
|
||||
return t
|
||||
},
|
||||
_utf8_decode: function(e) {
|
||||
var t = "";
|
||||
var n = 0;
|
||||
var r = 0;
|
||||
var c1 =0;
|
||||
var c2 =0;
|
||||
var c3 =0;
|
||||
while (n < e.length) {
|
||||
r = e.charCodeAt(n);
|
||||
if (r < 128) {
|
||||
t += String.fromCharCode(r);
|
||||
n++
|
||||
} else if (r > 191 && r < 224) {
|
||||
c2 = e.charCodeAt(n + 1);
|
||||
t += String.fromCharCode((r & 31) << 6 | c2 & 63);
|
||||
n += 2
|
||||
} else {
|
||||
c2 = e.charCodeAt(n + 1);
|
||||
c3 = e.charCodeAt(n + 2);
|
||||
t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
|
||||
n += 3
|
||||
}
|
||||
}
|
||||
return t
|
||||
}
|
||||
}
|
||||
|
||||
function encodeUtf8(text) {
|
||||
const code = encodeURIComponent(text);
|
||||
const bytes = [];
|
||||
for (var i = 0; i < code.length; i++) {
|
||||
const c = code.charAt(i);
|
||||
if (c === '%') {
|
||||
const hex = code.charAt(i + 1) + code.charAt(i + 2);
|
||||
const hexVal = parseInt(hex, 16);
|
||||
bytes.push(hexVal);
|
||||
i += 2;
|
||||
} else bytes.push(c.charCodeAt(0));
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function decodeUtf8(bytes) {
|
||||
var encoded = "";
|
||||
for (var i = 0; i < bytes.length; i++) {
|
||||
encoded += '%' + bytes[i].toString(16);
|
||||
}
|
||||
return decodeURIComponent(encoded);
|
||||
}
|
||||
function strToBytesUTF8(str) {
|
||||
let utf8 = [];
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
let charcode = str.charCodeAt(i);
|
||||
if (charcode < 0x80) utf8.push(charcode);
|
||||
else if (charcode < 0x800) {
|
||||
utf8.push(0xc0 | (charcode >> 6),
|
||||
0x80 | (charcode & 0x3f));
|
||||
}
|
||||
else if (charcode < 0xd800 || charcode >= 0xe000) {
|
||||
utf8.push(0xe0 | (charcode >> 12),
|
||||
0x80 | ((charcode>>6) & 0x3f),
|
||||
0x80 | (charcode & 0x3f));
|
||||
}
|
||||
// surrogate pair
|
||||
else {
|
||||
i++;
|
||||
// UTF-16 encodes 0x10000-0x10FFFF by
|
||||
// subtracting 0x10000 and splitting the
|
||||
// 20 bits of 0x0-0xFFFFF into two halves
|
||||
charcode = 0x10000 + (((charcode & 0x3ff)<<10)
|
||||
| (str.charCodeAt(i) & 0x3ff));
|
||||
utf8.push(0xf0 | (charcode >>18),
|
||||
0x80 | ((charcode>>12) & 0x3f),
|
||||
0x80 | ((charcode>>6) & 0x3f),
|
||||
0x80 | (charcode & 0x3f));
|
||||
}
|
||||
}
|
||||
return utf8;
|
||||
}
|
||||
|
||||
function utf8ToBase64(str){
|
||||
var ret11 = strToBytesUTF8( str )
|
||||
return bytesToBase64( ret11 )
|
||||
}
|
||||
|
||||
function base64ToUtf8( str ){
|
||||
var hex = base64ToHex( str );
|
||||
var ret = hexToBytes( hex )
|
||||
// var ret = base64ToBytes( str )
|
||||
return decodeUtf8(ret);
|
||||
}
|
||||
|
||||
var base64ToHex = function(base64str){
|
||||
return Base64Tohex(base64str);
|
||||
}
|
||||
|
||||
var base64ToBytes = function(base64str){
|
||||
return toBytes(base64str);
|
||||
//null
|
||||
}
|
||||
var utf8ToHex = function (str) {
|
||||
var ret11 = strToBytesUTF8( str )
|
||||
return bytesToHex( ret11 )
|
||||
}
|
||||
|
||||
var hexToUtf8 = function (hex) {
|
||||
var ret = hexToBytes( hex )
|
||||
// var ret = base64ToBytes( str )
|
||||
return decodeUtf8(ret);
|
||||
}
|
||||
|
||||
if ( module ) {
|
||||
|
||||
module.exports = {
|
||||
|
||||
stringToByte,
|
||||
byteToString,
|
||||
str2bytes,
|
||||
bytes2str,
|
||||
base64ArrayBuffer,
|
||||
bytesToString,
|
||||
bytesToBase64,
|
||||
bytesToHex,
|
||||
stringToBase64,
|
||||
stringToBytes,
|
||||
stringToHex,
|
||||
hexToBytes,
|
||||
hexToString,
|
||||
hexToBase64,
|
||||
base64ToString,
|
||||
base64ToHex,
|
||||
base64ToBytes,
|
||||
Base64,
|
||||
encodeUtf8,
|
||||
decodeUtf8,
|
||||
strToBytesUTF8,
|
||||
utf8ToBase64,
|
||||
base64ToUtf8,
|
||||
utf8ToHex,
|
||||
hexToUtf8
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
const JSON5 = require('json5')
|
||||
module.exports = {
|
||||
copy(obj) {
|
||||
return JSON5.parse( JSON5.stringify( obj ) )
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
const os = require('os');
|
||||
const fs = require("fs");
|
||||
const Windows = 0;
|
||||
const Linux = 1;
|
||||
|
||||
module.exports = {
|
||||
|
||||
Windows, Linux,
|
||||
|
||||
/**
|
||||
* 根据 os 不同,载入不同的方法
|
||||
*/
|
||||
choise : function ( cbs ) {
|
||||
if (os.type() == 'Windows_NT') {
|
||||
// windows平台
|
||||
return cbs && cbs[ Windows ]
|
||||
}
|
||||
else if (os.type() == 'Linux') {
|
||||
// Linux平台
|
||||
return cbs && cbs[ Linux ]
|
||||
}
|
||||
else {
|
||||
throw { message : "不支持的 OS" }
|
||||
}
|
||||
},
|
||||
|
||||
cur : function () {
|
||||
let isLinux = false;
|
||||
// 操作系统不同,安装方式不同
|
||||
let curOS = os.type()
|
||||
if ( curOS === "Windows_NT" ) {
|
||||
curOS = "Windows"
|
||||
}
|
||||
else if ( curOS === "Linux" ) {
|
||||
isLinux = true;
|
||||
const fs = require('fs');
|
||||
if( fs.existsSync('/etc/alpine-release') ){
|
||||
curOS = "Alpine"
|
||||
}
|
||||
}
|
||||
|
||||
let curPlatform = os.arch()
|
||||
if ( curPlatform === "x64" ) {
|
||||
curPlatform = "X86_64"
|
||||
} else if ( curPlatform.startsWith("arm") ) {
|
||||
curPlatform = "ARM64"
|
||||
}
|
||||
|
||||
return { isLinux, curOS, curPlatform }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
|
||||
const fs = require("fs")
|
||||
const os = require("os")
|
||||
const path = require("path");
|
||||
|
||||
// 废弃,权限问题难以处理
|
||||
// const KIT_HOME = "C:\\Program Files\\kit"
|
||||
// const HOME = "C:\\Program Files\\kit\\.kit"
|
||||
const KIT_HOME = path.resolve(os.homedir(), "AppData", "Local", "kit")
|
||||
const HOME = path.resolve(os.homedir(), "AppData", "Local", "kit", ".kit")
|
||||
|
||||
function getModuleInfo(id){
|
||||
let homeDir = path.resolve(HOME, "modules", id)
|
||||
if ( "kit" === id ) {
|
||||
homeDir = KIT_HOME;
|
||||
}
|
||||
|
||||
if ( ! fs.existsSync( homeDir ) ) {
|
||||
fs.mkdirSync( homeDir, { recursive : true } )
|
||||
return {
|
||||
HOME, KIT_HOME, exist : false, homeDir
|
||||
}
|
||||
}
|
||||
|
||||
let versionFile = path.resolve(homeDir, "version")
|
||||
if ( ! fs.existsSync( versionFile ) ) {
|
||||
return {
|
||||
HOME, KIT_HOME, exist : true, homeDir
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
HOME, KIT_HOME, exist : true, version : fs.readFileSync(versionFile, "UTF-8"), homeDir
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = { getModuleInfo }
|
||||
@@ -0,0 +1,40 @@
|
||||
|
||||
|
||||
async function killport(port) {
|
||||
$logger.info(`kill process on port ${port}`);
|
||||
const util = require('util');
|
||||
const exec = util.promisify(require('child_process').exec);
|
||||
|
||||
try {
|
||||
// 查 PID
|
||||
let { stdout : stdout1 } = await exec(`netstat -ano | findstr "LISTENING" | findstr /C:":${port} "`)
|
||||
|
||||
const output = stdout1.split('\n');
|
||||
const outputLines = output[0].trim().split(' ')
|
||||
const pid = outputLines[outputLines.length - 1];
|
||||
$logger.debug(`绑定端口号 ${port} 的进程 PID=${pid}`)
|
||||
|
||||
|
||||
// 查进程信息
|
||||
let { stdout : stdout2 } = await exec(`tasklist /FI "PID eq ${pid}" /V /FO CSV`);
|
||||
const tasklistOutput = stdout2.trim();
|
||||
const processInfo = tasklistOutput.split('\n')[1].split('","');
|
||||
const processName = processInfo[0].slice(1) ;
|
||||
|
||||
$logger.info(`绑定端口号=${port}; 进程 PID=${pid}; 程序=${processName};`);
|
||||
|
||||
// Kill 进程
|
||||
await exec(`taskkill /PID ${pid} /F`)
|
||||
|
||||
} catch (e) {
|
||||
if ( 1 === e.code ) {
|
||||
$logger.error("此端口未被使用,或清理进程失败。")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
module.exports = {
|
||||
killport
|
||||
}
|
||||
Reference in New Issue
Block a user