Init: Create & Init ms Project...
Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
4
packages/common/.gitignore
vendored
Normal file
4
packages/common/.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
/node_modules
|
||||
/dist
|
||||
/package-lock.json
|
||||
/yarn.lock
|
22
packages/common/.npmignore
Normal file
22
packages/common/.npmignore
Normal file
@ -0,0 +1,22 @@
|
||||
src
|
||||
test
|
||||
typings
|
||||
bundled
|
||||
build
|
||||
coverage
|
||||
docs
|
||||
wiki
|
||||
gulpfile.js
|
||||
bower.json
|
||||
karma.conf.js
|
||||
tsconfig.json
|
||||
typings.json
|
||||
CONTRIBUTING.md
|
||||
ISSUE_TEMPLATE.md
|
||||
PULL_REQUEST_TEMPLATE.md
|
||||
tslint.json
|
||||
wallaby.js
|
||||
.travis.yml
|
||||
.gitignore
|
||||
.vscode
|
||||
type_definitions
|
32
packages/common/package.json
Normal file
32
packages/common/package.json
Normal file
@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "@ms/common",
|
||||
"version": "0.0.0",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"publishConfig": {
|
||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "npx tsc --watch",
|
||||
"build": "yarn clean && npx tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.0",
|
||||
"typescript": "^3.6.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ms/nashorn": "^0.0.0"
|
||||
}
|
||||
}
|
155
packages/common/src/fs.ts
Normal file
155
packages/common/src/fs.ts
Normal file
@ -0,0 +1,155 @@
|
||||
import '@ms/nashorn'
|
||||
|
||||
/*global Java, base, module, exports, require, __FILE__*/
|
||||
const Path = Java.type("java.nio.file.Path");
|
||||
const JavaString = Java.type("java.lang.String");
|
||||
const File = Java.type("java.io.File");
|
||||
const Files = Java.type("java.nio.file.Files");
|
||||
const Collector = Java.type("java.util.stream.Collector")
|
||||
const separatorChar = File.separatorChar;
|
||||
const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
|
||||
|
||||
/**
|
||||
* 用文件分割符合并路径
|
||||
*/
|
||||
export function concat() {
|
||||
return Array.prototype.join.call(arguments, separatorChar);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得文件
|
||||
* @constructor(file)
|
||||
* @constructor(dir,file)
|
||||
* @returns {*}
|
||||
*/
|
||||
export function file(...opts: any[]): any {
|
||||
if (!arguments[0]) {
|
||||
console.warn("文件名称不得为 undefined 或者 null !");
|
||||
}
|
||||
switch (arguments.length) {
|
||||
case 1:
|
||||
var f = arguments[0];
|
||||
if (f instanceof File) {
|
||||
return f;
|
||||
}
|
||||
if (typeof f === "string") {
|
||||
return new File(f);
|
||||
}
|
||||
if (f instanceof Path) {
|
||||
return f.toFile();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
return new File(file(arguments[0]), arguments[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建目录
|
||||
* @param path
|
||||
*/
|
||||
export function mkdirs(path) {
|
||||
// noinspection JSUnresolvedVariable
|
||||
file(path).parentFile.mkdirs();
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建文件
|
||||
* @param file
|
||||
*/
|
||||
export function create(path) {
|
||||
var f = file(path);
|
||||
if (!f.exists()) {
|
||||
mkdirs(f);
|
||||
f.createNewFile();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得文件规范路径
|
||||
* @param file
|
||||
* @returns {*}
|
||||
*/
|
||||
export function path(f) {
|
||||
return file(f).canonicalPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制文件
|
||||
* @param inputStream 输入流
|
||||
* @param target 目标文件
|
||||
* @param override 是否覆盖
|
||||
*/
|
||||
export function copy(inputStream, target, override) {
|
||||
Files.copy(inputStream, target.toPath(), StandardCopyOption[override ? 'REPLACE_EXISTING' : 'ATOMIC_MOVE']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取文件
|
||||
* @param path 文件路径
|
||||
*/
|
||||
export function read(path) {
|
||||
var file = file(path);
|
||||
if (!file.exists()) {
|
||||
console.warn('读取文件', file, '错误 文件不存在!');
|
||||
return;
|
||||
}
|
||||
// noinspection JSPrimitiveTypeWrapperUsage
|
||||
return new JavaString(Files.readAllBytes(file.toPath()), "UTF-8");
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存内容文件
|
||||
* @param path 路径
|
||||
* @param content 内容
|
||||
* @param override 是否覆盖
|
||||
*/
|
||||
export function save(path, content, override) {
|
||||
var file = file(path);
|
||||
if (file.parentFile) {
|
||||
file.parentFile.mkdirs();
|
||||
}
|
||||
Files.write(file.toPath(), new JavaString(content).getBytes("UTF-8"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 列出目录文件
|
||||
* @param path
|
||||
*/
|
||||
export function list(path) {
|
||||
var dir = file(path);
|
||||
// noinspection JSValidateTypes
|
||||
if (dir.isDirectory()) {
|
||||
return Files.list(dir.toPath());
|
||||
}
|
||||
console.debug('路径', path, '不是一个目录 返回空数组!');
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 移动文件
|
||||
* @param src 原始目录
|
||||
* @param des 目标目录
|
||||
* @param override 是否覆盖
|
||||
*/
|
||||
export function move(src, des, override) {
|
||||
Files.move(file(src).toPath(), file(des).toPath(),
|
||||
override ? StandardCopyOption['REPLACE_EXISTING'] : StandardCopyOption['ATOMIC_MOVE'])
|
||||
}
|
||||
|
||||
export function del(file) {
|
||||
file = file(file);
|
||||
if (!file.exists()) {
|
||||
return;
|
||||
}
|
||||
if (file.isDirectory()) {
|
||||
Files.list(file.toPath()).collect(Collector.toList()).forEach(function(f) {
|
||||
del(f);
|
||||
})
|
||||
}
|
||||
Files.delete(file.toPath());
|
||||
}
|
||||
|
||||
export function exists(f) {
|
||||
return file(f).exists()
|
||||
}
|
155
packages/common/src/http.ts
Normal file
155
packages/common/src/http.ts
Normal file
@ -0,0 +1,155 @@
|
||||
'use strict';
|
||||
/**
|
||||
* HTTP 网络类
|
||||
* Created by 蒋天蓓 on 2017/2/9 0009.
|
||||
*/
|
||||
|
||||
/*global Java, base, module, exports, require, __FILE__*/
|
||||
|
||||
var URL = Java.type("java.net.URL");
|
||||
var UUID = Java.type("java.util.UUID");
|
||||
var System = Java.type("java.lang.System");
|
||||
var Files = Java.type("java.nio.file.Files");
|
||||
var Paths = Java.type("java.nio.file.Paths");
|
||||
var JavaString = Java.type("java.lang.String");
|
||||
var SecureRandom = Java.type("java.security.SecureRandom");
|
||||
|
||||
var SSLContext = Java.type("javax.net.ssl.SSLContext");
|
||||
var HttpsURLConnection = Java.type("javax.net.ssl.HttpsURLConnection");
|
||||
|
||||
var HostnameVerifier = Java.type("javax.net.ssl.HostnameVerifier");
|
||||
var X509TrustManager = Java.type("javax.net.ssl.X509TrustManager");
|
||||
|
||||
// noinspection JSUnusedGlobalSymbols,JSUnusedLocalSymbols
|
||||
var TrustAnyHostnameVerifier = new HostnameVerifier({
|
||||
verify: function(hostname, session) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
var SSLSocketFactory = function initSSLSocketFactory() {
|
||||
var sslContext = SSLContext.getInstance("TLS");
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
sslContext.init(null, [new X509TrustManager({
|
||||
getAcceptedIssuers: function() {
|
||||
return null;
|
||||
},
|
||||
checkClientTrusted: function(chain, authType) {
|
||||
},
|
||||
checkServerTrusted: function(chain, authType) {
|
||||
}
|
||||
})], new SecureRandom());
|
||||
return sslContext.getSocketFactory();
|
||||
}();
|
||||
|
||||
var config = {
|
||||
Charset: 'UTF-8',
|
||||
ConnectTimeout: 10000,
|
||||
ReadTimeout: 10000,
|
||||
Debug: false
|
||||
};
|
||||
|
||||
function open(url, method, header) {
|
||||
// conn.setRequestProperty
|
||||
var conn = new URL(url).openConnection();
|
||||
if (conn instanceof HttpsURLConnection) {
|
||||
conn.setHostnameVerifier(TrustAnyHostnameVerifier);
|
||||
conn.setSSLSocketFactory(SSLSocketFactory);
|
||||
}
|
||||
conn.setRequestMethod(method);
|
||||
conn.setDoOutput(true);
|
||||
conn.setDoInput(true);
|
||||
conn.setConnectTimeout(config.ConnectTimeout);
|
||||
conn.setReadTimeout(config.ReadTimeout);
|
||||
if (header) {
|
||||
for (var key in header) {
|
||||
// noinspection JSUnfilteredForInLoop
|
||||
conn.setRequestProperty(key, header[key]);
|
||||
}
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
|
||||
function buildUrl(url, params) {
|
||||
if (params && Object.keys(params).length > 0) {
|
||||
var queryStart = url.indexOf('?');
|
||||
if (queryStart === -1) {
|
||||
url += '?';
|
||||
}
|
||||
return url += object2URLSearchParams(params);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
function request(config) {
|
||||
var conn = open(buildUrl(config.url, config.query), config.method, config.header);
|
||||
try {
|
||||
conn.connect();
|
||||
var data = config.data;
|
||||
if (data) {
|
||||
var out = conn.getOutputStream();
|
||||
if (typeof data === "object") {
|
||||
var type = config.header['Content-Type'];
|
||||
switch (type) {
|
||||
case "application/x-www-form-urlencoded":
|
||||
data = object2URLSearchParams(data);
|
||||
break;
|
||||
default:
|
||||
data = JSON.stringify(data)
|
||||
}
|
||||
}
|
||||
out.write(new JavaString(data).getBytes(config.Charset));
|
||||
out.flush();
|
||||
out.close();
|
||||
}
|
||||
return response(conn);
|
||||
} finally {
|
||||
conn.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
function response(conn) {
|
||||
var temp = Paths.get(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
|
||||
Files.copy(conn.getInputStream(), temp);
|
||||
var result = new JavaString(Files.readAllBytes(temp), config.Charset);
|
||||
var tempFile = temp.toFile();
|
||||
tempFile.delete() || tempFile.deleteOnExit();
|
||||
return result;
|
||||
}
|
||||
|
||||
function object2URLSearchParams(params) {
|
||||
var temp: string[] = [];
|
||||
for (var key in params) {
|
||||
temp.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
|
||||
}
|
||||
return temp.join('&')
|
||||
}
|
||||
|
||||
var http = {
|
||||
config: config,
|
||||
request: request
|
||||
};
|
||||
|
||||
['GET', 'DELETE', 'HEAD', 'OPTIONS'].forEach(function(method) {
|
||||
http[method.toLowerCase()] = function __likeGet__(url, data, config = {}) {
|
||||
return this.request({
|
||||
...config,
|
||||
url: url,
|
||||
method: method,
|
||||
query: data
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
['POST', 'PUT', 'PATCH'].forEach(function(method) {
|
||||
http[method.toLowerCase()] = function __likePost__(url, data, config) {
|
||||
return this.request({
|
||||
...config,
|
||||
url: url,
|
||||
method: method,
|
||||
data: data
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export = http;
|
191
packages/common/src/reflect.ts
Normal file
191
packages/common/src/reflect.ts
Normal file
@ -0,0 +1,191 @@
|
||||
import '@ms/core'
|
||||
/**
|
||||
* 反射工具类
|
||||
* Created by 蒋天蓓 on 2017/2/9 0009.
|
||||
*/
|
||||
var JavaClass = Java.type('java.lang.Class');
|
||||
var JavaObject = Java.type('java.lang.Object')
|
||||
var NoSuchFieldException = Java.type('java.lang.NoSuchFieldException');
|
||||
var methodCache = [];
|
||||
|
||||
class Reflect {
|
||||
private obj: any;
|
||||
private class: any
|
||||
|
||||
constructor(obj: any) {
|
||||
if (obj instanceof JavaClass) {
|
||||
this.obj = null;
|
||||
this.class = obj;
|
||||
} else {
|
||||
this.obj = obj;
|
||||
this.class = obj.class;
|
||||
}
|
||||
}
|
||||
|
||||
method(...args: any[]) {
|
||||
return declaredMethod(this.class, args[0], types(args.slice(1)));
|
||||
}
|
||||
|
||||
methods() {
|
||||
return Java.from(declaredMethods(this.class));
|
||||
}
|
||||
|
||||
field(name) {
|
||||
try {
|
||||
// Try getting a public field
|
||||
var field = this.class.field(name);
|
||||
return on(field.get(this.obj));
|
||||
} catch (ex) {
|
||||
// Try again, getting a non-public field
|
||||
return on(accessible(declaredField(this.class, name)).get(this.obj));
|
||||
}
|
||||
};
|
||||
|
||||
fields(declared) {
|
||||
return Java.from(declared ? this.class.declaredFields : this.class.fields);
|
||||
}
|
||||
|
||||
values(declared) {
|
||||
var cache = {};
|
||||
var feds = declared ? this.class.declaredFields : this.class.fields;
|
||||
Java.from(feds).forEach(function(fed) {
|
||||
cache[fed.name] = this.field(fed.name).get();
|
||||
}.bind(this))
|
||||
return cache;
|
||||
}
|
||||
|
||||
call(...args) {
|
||||
var params = args.slice(1);
|
||||
var method = declaredMethod(this.class, args[0], types(params));
|
||||
return on(method.invoke(this.get(), params));
|
||||
};
|
||||
|
||||
get(...args) {
|
||||
return args.length === 1 ? this.field(args[0]) : this.obj;
|
||||
};
|
||||
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
set(name, value) {
|
||||
accessible(declaredField(this.class, name)).set(this.obj, value);
|
||||
return this;
|
||||
};
|
||||
|
||||
create(...args) {
|
||||
return on(declaredConstructor(this.class, args).newInstance(args));
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an array of types for an array of objects
|
||||
*/
|
||||
function types(values, def?) {
|
||||
if (values === null) {
|
||||
return [];
|
||||
}
|
||||
var result = [];
|
||||
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class));
|
||||
return result;
|
||||
}
|
||||
|
||||
function accessible(accessible) {
|
||||
if (accessible === null) {
|
||||
return null;
|
||||
}
|
||||
if (!accessible.isAccessible()) {
|
||||
accessible.setAccessible(true);
|
||||
}
|
||||
return accessible;
|
||||
}
|
||||
|
||||
function declaredConstructor(clazz, param) {
|
||||
var constructor;
|
||||
try {
|
||||
constructor = clazz.getDeclaredConstructor(types(param));
|
||||
} catch (ex) {
|
||||
try {
|
||||
constructor = clazz.getDeclaredConstructor(types(param, true));
|
||||
} catch (ex) {
|
||||
constructor = clazz.getDeclaredConstructors()[0];
|
||||
}
|
||||
}
|
||||
return accessible(constructor);
|
||||
}
|
||||
|
||||
function declaredField(clazz, name) {
|
||||
var field = null;
|
||||
// noinspection JSUnresolvedVariable
|
||||
while (clazz !== JavaObject.class) {
|
||||
try {
|
||||
field = clazz.getDeclaredField(name);
|
||||
if (field !== null) {
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
clazz = clazz.getSuperclass();
|
||||
}
|
||||
}
|
||||
if (field === null) {
|
||||
throw new NoSuchFieldException(name + " is not found in " + clazz.name);
|
||||
}
|
||||
return field;
|
||||
}
|
||||
|
||||
function declaredMethod(clazz, name, clazzs) {
|
||||
var key = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
|
||||
if (!methodCache[key]) {
|
||||
try {
|
||||
methodCache[key] = clazz.getMethod(name, clazzs);
|
||||
} catch (ex) {
|
||||
methodCache[key] = clazz.getDeclaredMethod(name, clazzs);
|
||||
}
|
||||
}
|
||||
return methodCache[key];
|
||||
}
|
||||
|
||||
function declaredMethods(clazz) {
|
||||
return clazz.declaredMethods;
|
||||
}
|
||||
|
||||
var classMethodsCache = [];
|
||||
|
||||
function mapToObject(javaObj) {
|
||||
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
||||
var target = {};
|
||||
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t));
|
||||
return target;
|
||||
}
|
||||
|
||||
function getJavaObjectMethods(javaObj) {
|
||||
var className = javaObj.class.name;
|
||||
if (!classMethodsCache[className]) {
|
||||
var names = [];
|
||||
var methods = javaObj.class.methods;
|
||||
for (var i in methods) {
|
||||
names.push(methods[i].name);
|
||||
}
|
||||
classMethodsCache[className] = names;
|
||||
}
|
||||
return classMethodsCache[className];
|
||||
}
|
||||
|
||||
function mapMethod(target, source, name) {
|
||||
target[name] = function __SimpleDynamicMethod__(...args) {
|
||||
if (args.length > 0) {
|
||||
return source[name](args);
|
||||
} else {
|
||||
return source[name]();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function on(obj) {
|
||||
if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
|
||||
return new Reflect(obj);
|
||||
}
|
||||
|
||||
export = {
|
||||
on,
|
||||
accessible,
|
||||
declaredMethods,
|
||||
mapToObject
|
||||
};
|
29
packages/common/src/template.ts
Normal file
29
packages/common/src/template.ts
Normal file
@ -0,0 +1,29 @@
|
||||
function Template(tpl: string) {
|
||||
var match: RegExpExecArray;
|
||||
var code = ['var r=[];'];
|
||||
var re = /\{\{\s*([a-zA-Z\.\_0-9()]+)\s*\}\}/m;
|
||||
function addLine(text: string) {
|
||||
code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
|
||||
};
|
||||
while (match = re.exec(tpl)) {
|
||||
if (match.index > 0) {
|
||||
addLine(tpl.slice(0, match.index));
|
||||
}
|
||||
code.push('r.push(this.' + match[1] + ');');
|
||||
tpl = tpl.substring(match.index + match[0].length);
|
||||
}
|
||||
addLine(tpl);
|
||||
code.push('return r.join(\'\');');
|
||||
// 创建函数:
|
||||
var fn = new Function(code.join('\n'));
|
||||
// 用render()调用函数并绑定this参数:
|
||||
this.render = function(model) {
|
||||
return fn.apply(model);
|
||||
};
|
||||
}
|
||||
|
||||
export = {
|
||||
create: function(tpl: string) {
|
||||
return new Template(tpl);
|
||||
}
|
||||
}
|
23
packages/common/src/tgz.ts
Normal file
23
packages/common/src/tgz.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import '@ms/nashorn'
|
||||
|
||||
let Files = Java.type("java.nio.file.Files");
|
||||
let Paths = Java.type("java.nio.file.Paths");
|
||||
let StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
|
||||
|
||||
let TarInputStream = Java.type("org.kamranzafar.jtar.TarInputStream");
|
||||
let GZIPInputStream = Java.type("java.util.zip.GZIPInputStream");
|
||||
let BufferedInputStream = Java.type("java.io.BufferedInputStream");
|
||||
|
||||
function decompression(input: any, target: string) {
|
||||
let tis = new TarInputStream(new BufferedInputStream(new GZIPInputStream(input)));
|
||||
let entry: any;
|
||||
while ((entry = tis.getNextEntry()) != null) {
|
||||
let targetPath = Paths.get(target + "/" + entry.getName().substring("package/".length));
|
||||
targetPath.toFile().getParentFile().mkdirs();
|
||||
Files.copy(tis, targetPath, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
|
||||
export = {
|
||||
decompression
|
||||
}
|
8
packages/common/tsconfig.json
Normal file
8
packages/common/tsconfig.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist",
|
||||
"declaration": true
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user