Compare commits
196 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7cf9718a9a | |||
| 9693dc235f | |||
| 40e9d1db6e | |||
| d50506ab9d | |||
| c34d3027e4 | |||
| edf8410cd1 | |||
| b0b4bbcc2b | |||
| e68689c560 | |||
| 58353cb5b8 | |||
| 8c6b75ff10 | |||
| d53287fc51 | |||
| 13a3611ebd | |||
| 6d90980726 | |||
| 42de3700ba | |||
| 5991662764 | |||
| 1c98c19e37 | |||
| c596280d8d | |||
| 77301e0130 | |||
| 90878fc7df | |||
| a0a4c13e7b | |||
| 0e92a9c795 | |||
| 0c69462bb4 | |||
| 78a5ed31b3 | |||
| f4e9b2627d | |||
| 9dd7abe6fd | |||
| 12743bbbe0 | |||
| d9a2ea9c78 | |||
| c505cda10b | |||
| 100ccbcde3 | |||
| c6575ed481 | |||
| 83359d8cb9 | |||
| cca4979f16 | |||
| 251c9366f5 | |||
| 8f01dcc8e8 | |||
| c25a616dba | |||
| aa9169b043 | |||
| d87e152f3b | |||
| 2fcadeda4e | |||
| b7927830ae | |||
| 2dbd2182c2 | |||
| 01df79eaf1 | |||
| 16fe9ba9bd | |||
| 950ce69b83 | |||
| fa8e44d838 | |||
| b7af785273 | |||
| 6c9f7bbcf6 | |||
| c4c4c7f301 | |||
| 6538c4b7bb | |||
| a4e6d1660d | |||
| 511b042eba | |||
| 6f0b5a5572 | |||
| e9ac46487c | |||
| 9371823d30 | |||
| c86f0d9ec1 | |||
| c2d94ef104 | |||
| 6ada3e41d0 | |||
| 8c12319dc9 | |||
| 395d2d8816 | |||
| 6f628a3d7e | |||
| 2232e82c36 | |||
| 291b5010e7 | |||
| 3595294444 | |||
| e38358ef98 | |||
| 4c418c33c0 | |||
| 65d112be09 | |||
| 15a75dffe2 | |||
| 7b8e693a03 | |||
| 5426023adb | |||
| 73b91c417e | |||
| 2693a22bf0 | |||
| 2322de1e40 | |||
| 2320736a92 | |||
| e8d5d10d44 | |||
| a9996ba297 | |||
| 68380ddbba | |||
| 0baf8f3cab | |||
| a2bce715f3 | |||
| 3c55df03d8 | |||
| f6526e79fc | |||
| f4c2294c06 | |||
| cf9508ba31 | |||
| e0f4c5e77d | |||
| e4a87095ce | |||
| 950575edbc | |||
| c2a71b9a7a | |||
| 068ac7b76e | |||
| 05cbd85828 | |||
| ea28d20aa1 | |||
| d3f33f50e0 | |||
| d004ba17e6 | |||
| 7a25dd8b3b | |||
| dedc8393da | |||
| 8d344492d9 | |||
| 81a76af7be | |||
| b458da7a6e | |||
| 45cb6fa667 | |||
| 9c4543df30 | |||
| 512bdb22c5 | |||
| f6e39c131c | |||
| 73d4dad7f6 | |||
| de4a22362f | |||
| 5fde2e5554 | |||
| 6a6765e5c3 | |||
| 4a1f25ee6a | |||
| 5999567ee3 | |||
| fad4e27a7f | |||
| b477938e4f | |||
| 7cbd91826a | |||
| 6797761a2f | |||
| be114e6d1b | |||
| 3e40934339 | |||
| 3e6c7b2d8c | |||
| 6c0bb75561 | |||
| a47896a97f | |||
| 1d97bbc9ce | |||
| b1f1f9837e | |||
| 99dee28fd4 | |||
| c7f66d8252 | |||
| 8c4f266356 | |||
| 39e899211b | |||
| da72a0dac6 | |||
| 9984787202 | |||
| 4493d35786 | |||
| e1aad59eeb | |||
| 849393492f | |||
| 1ff33702d8 | |||
| e68005fd6f | |||
| 17269b50f4 | |||
| 363d0c164a | |||
| 13a0b62103 | |||
| cb4e152800 | |||
| fb83acfcc8 | |||
| 7263fbb437 | |||
| 23868a58b9 | |||
| effa7f70ec | |||
| eef0baa740 | |||
| 4d0c0122c7 | |||
| aa581afbe5 | |||
| 1425c473fd | |||
| 53e4f6c658 | |||
| 73db4a9169 | |||
| a2efd878db | |||
| 4e6cda0545 | |||
| 859a3a9171 | |||
| 96481032c5 | |||
| f950c3dae8 | |||
| 9248294cb3 | |||
| 53873d7b63 | |||
| be59ae480b | |||
| 9fa3ed704a | |||
| a76858d626 | |||
| 55a6b33110 | |||
| b87b94aade | |||
| 4110ed2c20 | |||
| 3cbc101eff | |||
| 221b821085 | |||
| 7331cfaa55 | |||
| 40d020ef67 | |||
| eea2a225e8 | |||
| 48f7f0fdbb | |||
| 99ed76f9bb | |||
| 7f21fa67ee | |||
| 8584709828 | |||
| d1f58e7482 | |||
| 1bd35aef6d | |||
| fdf1088564 | |||
| 7bb4d1f6a3 | |||
| b8c3d0d19d | |||
| a616a07553 | |||
| 781524f83e | |||
| c7a812c003 | |||
| 325f2c8cf9 | |||
| 562e2d0017 | |||
| b7871e8d33 | |||
| 060cffd8e7 | |||
| 4b1fb07cc9 | |||
| 0931d69188 | |||
| 7d33368ebd | |||
| c95fc5fcff | |||
| a7479f60c8 | |||
| ac75356778 | |||
| 7f32382dbc | |||
| b3c2def36d | |||
| 1ea93dfb9f | |||
| e5ffa70ed9 | |||
| 2a60b36e23 | |||
| c4c2c0ab0f | |||
| bf5628a646 | |||
| 13e9f0a5af | |||
| cdd5f2d250 | |||
| dfd7182008 | |||
| 533859808f | |||
| 15cea1dfc8 | |||
| dfa43d58f0 | |||
| 2bf239d8ea | |||
| cbe87cc378 |
@@ -1,12 +0,0 @@
|
|||||||
# http://editorconfig.org
|
|
||||||
root = true
|
|
||||||
|
|
||||||
[*]
|
|
||||||
indent_style = space
|
|
||||||
indent_size = 4
|
|
||||||
charset = utf-8
|
|
||||||
trim_trailing_whitespace = true
|
|
||||||
insert_final_newline = true
|
|
||||||
|
|
||||||
[*.md]
|
|
||||||
trim_trailing_whitespace = false
|
|
||||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -1,4 +1,8 @@
|
|||||||
.yarn*
|
|
||||||
.vscode
|
.vscode
|
||||||
|
.theia
|
||||||
node_modules
|
node_modules
|
||||||
dist
|
dist
|
||||||
|
package-lock.json
|
||||||
|
yarn.lock
|
||||||
|
packages/nashorn/docs
|
||||||
|
!packages/types/dist
|
||||||
|
|||||||
10
.gitpod.Dockerfile
vendored
10
.gitpod.Dockerfile
vendored
@@ -1,10 +0,0 @@
|
|||||||
FROM gitpod/workspace-full
|
|
||||||
|
|
||||||
USER gitpod
|
|
||||||
|
|
||||||
# Install custom tools, runtime, etc. using apt-get
|
|
||||||
# For example, the command below would install "bastet" - a command line tetris clone:
|
|
||||||
#
|
|
||||||
# RUN sudo apt-get -q update && # sudo apt-get install -yq bastet && # sudo rm -rf /var/lib/apt/lists/*
|
|
||||||
#
|
|
||||||
# More information: https://www.gitpod.io/docs/config-docker/
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
tasks:
|
|
||||||
- init: yarn && yarn bs && yarn build
|
|
||||||
command: yarn watch
|
|
||||||
# image:
|
|
||||||
# file: .gitpod.Dockerfile
|
|
||||||
22
.npmignore
Normal file
22
.npmignore
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
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
|
||||||
|
.theia
|
||||||
|
type_definitions
|
||||||
47
README.MD
47
README.MD
@@ -8,28 +8,27 @@
|
|||||||
|
|
||||||
```txt
|
```txt
|
||||||
└─packages
|
└─packages
|
||||||
├─api 全平台兼容的接口
|
├─api 全平台兼容的接口
|
||||||
├─core 核心代码 用于引导加载
|
├─core 核心代码 用于引导加载
|
||||||
├─common 公共类库代码 例如 http reflect 模块
|
├─common 公共类库代码 例如 http reflect 模块
|
||||||
├─compile 编译器相关功能
|
├─client NodeJS的Minecraft客户端 用于调试插件
|
||||||
├─client NodeJS 的 Minecraft 客户端 已迁移至 ms-client
|
├─container IOC容器 用于注入具体实现
|
||||||
├─container IOC容器 用于注入具体实现
|
├─ployfill Nashorn 的一些自定义增强
|
||||||
├─database 数据库相关功能
|
├─nashorn Nashorn 的类型定义
|
||||||
├─protocol 协议处理相关功能
|
├─bungee BungeeCordAPI内部实现
|
||||||
├─service 服务相关功能
|
├─bukkit BukkitAPI内部实现
|
||||||
├─i18n 多语言环境相关支持
|
├─sponge SpongeAPI内部实现
|
||||||
├─polyfill Nashorn 的一些自定义增强
|
├─nukkit NukkitAPI内部实现
|
||||||
├─nashorn Nashorn 的类型定义
|
├─plugin 插件管理器
|
||||||
├─nodejs NodeJS 的部分 Java 实现
|
├─websocket Netty的WebSocket注入
|
||||||
├─bungee BungeeCordAPI 内部实现
|
├─type Java的类型定义
|
||||||
├─bukkit BukkitAPI 内部实现
|
| ├─bungee BungeeCord类型定义
|
||||||
├─sponge SpongeAPI 内部实现
|
| ├─bukkit Bukkit类型定义
|
||||||
├─nukkit NukkitAPI 内部实现
|
| ├─sponge Sponge类型定义
|
||||||
├─molang MoLang 解析库
|
| └─nukkit Nukkit类型定义
|
||||||
├─qrcode 二维码相关类库
|
└─plugins 这里当然是插件啦
|
||||||
├─plugin 插件管理器
|
├─bungee 只兼容BungeeCord的插件
|
||||||
├─websocket WebSocket 相关实现
|
├─bukkit 只兼容Bukkit的插件
|
||||||
| ├─client 基于 Netty 的 WebSocket 客户端
|
├─sponge 只兼容Sponge的插件
|
||||||
| └─server 基于 Netty 的 WebSocket 服务端
|
└─nukkit 只兼容Nukkit的插件
|
||||||
└─type 类型定义 已迁移到 @javatypes
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -4,8 +4,3 @@
|
|||||||
- 更新日志 [](https://docs.yumc.pw/MiaoScript/CHANGELOG.html)
|
- 更新日志 [](https://docs.yumc.pw/MiaoScript/CHANGELOG.html)
|
||||||
- 安装文档 [](https://docs.yumc.pw/MiaoScript/1-user/1.1-check-env.html)
|
- 安装文档 [](https://docs.yumc.pw/MiaoScript/1-user/1.1-check-env.html)
|
||||||
- 开发文档 [](https://docs.yumc.pw/MiaoScript/2-develop/1.1-check-env.html)
|
- 开发文档 [](https://docs.yumc.pw/MiaoScript/2-develop/1.1-check-env.html)
|
||||||
- 兼容服务端 Spigot CatServer Sponge BungeeCord Nukkit(没错 他还兼容Nukkit)
|
|
||||||
|
|
||||||
### 腐竹版本(开发中)
|
|
||||||
|
|
||||||
- 先上几张图
|
|
||||||
|
|||||||
22
lerna.json
22
lerna.json
@@ -1,12 +1,16 @@
|
|||||||
{
|
{
|
||||||
"version": "0.28.0-beta.11",
|
"version": "0.6.1",
|
||||||
"npmClient": "pnpm",
|
"useWorkspaces": true,
|
||||||
"command": {
|
"npmClient": "yarn",
|
||||||
"run": {
|
"packages": [
|
||||||
"stream": true
|
"packages/*"
|
||||||
|
],
|
||||||
|
"command": {
|
||||||
|
"run": {
|
||||||
|
"stream": true
|
||||||
|
},
|
||||||
|
"publish": {
|
||||||
|
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
31
package.json
31
package.json
@@ -6,30 +6,19 @@
|
|||||||
"author": "MiaoWoo <admin@yumc.pw>",
|
"author": "MiaoWoo <admin@yumc.pw>",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"bs": "pnpm install",
|
"bs": "lerna bootstrap",
|
||||||
"clean": "lerna run clean",
|
"clean": "lerna run clean",
|
||||||
"watch": "lerna run watch --parallel",
|
"watch": "lerna run watch --parallel",
|
||||||
"build": "lerna run build",
|
"build": "lerna run build --scope=\"@ccms/!(plugins)\"",
|
||||||
"ug": "pnpm up -r -i",
|
"build:plugins": "lerna run build --scope=\"@ccms/plugins\"",
|
||||||
"np": "./script/push.sh",
|
"publish": "yarn lerna exec \"npm publish --access=public\" --scope=\"@ccms/!(plugins|client|types)\"",
|
||||||
"lsp": "npm login -scope=@ccms",
|
"ug": "yarn upgrade-interactive --latest",
|
||||||
"lp": "lerna publish --force-publish",
|
"lp": "lerna publish"
|
||||||
"lpb": "lerna publish prerelease --preid beta --dist-tag beta --force-publish",
|
|
||||||
"lpc": "lerna publish --canary --preid beta --pre-dist-tag beta --force-publish",
|
|
||||||
"lpf": "lerna publish from-package --dist-tag beta --yes",
|
|
||||||
"sync": "./script/sync.sh",
|
|
||||||
"postpublish": "pnpm sync"
|
|
||||||
},
|
},
|
||||||
|
"workspaces": [
|
||||||
|
"packages/*"
|
||||||
|
],
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "workspace:*",
|
"lerna": "^3.20.2"
|
||||||
"@javatypes/jdk": "^0.0.3",
|
|
||||||
"@lerna-lite/cli": "^2.6.0",
|
|
||||||
"@lerna-lite/publish": "^2.6.0",
|
|
||||||
"@lerna-lite/run": "^2.6.0",
|
|
||||||
"@types/node": "^20.8.8",
|
|
||||||
"reflect-metadata": "^0.1.13",
|
|
||||||
"rimraf": "^5.0.5",
|
|
||||||
"tslib": "^2.6.2",
|
|
||||||
"typescript": "^5.2.2"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/api",
|
"name": "@ccms/api",
|
||||||
"version": "0.28.0-beta.11",
|
"version": "0.6.1",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -12,26 +12,22 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"files": [
|
|
||||||
"dist/**/*.js",
|
|
||||||
"dist/**/*.ts",
|
|
||||||
"dist/**/*.map"
|
|
||||||
],
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "pnpm clean && tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/common": "workspace:*",
|
"@ccms/container": "^0.6.0",
|
||||||
"@ccms/container": "workspace:*",
|
"@ccms/ployfill": "^0.6.1",
|
||||||
"@ccms/i18n": "workspace:*",
|
"base64-js": "^1.3.1",
|
||||||
"@ccms/polyfill": "workspace:*",
|
|
||||||
"base64-js": "^1.5.1",
|
|
||||||
"source-map-builder": "^0.0.7"
|
"source-map-builder": "^0.0.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/base64-js": "^1.5.0"
|
"@types/base64-js": "^1.2.5",
|
||||||
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^3.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { injectable } from "@ccms/container"
|
import { injectable } from "@ccms/container";
|
||||||
|
|
||||||
export namespace channel {
|
export namespace channel {
|
||||||
/**
|
/**
|
||||||
@@ -17,32 +17,32 @@ export namespace channel {
|
|||||||
* @param exec 执行器
|
* @param exec 执行器
|
||||||
*/
|
*/
|
||||||
listen(plugin: any, channel: string, exec: ChannelListener) {
|
listen(plugin: any, channel: string, exec: ChannelListener) {
|
||||||
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!')
|
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!');
|
||||||
let name = plugin.description.name
|
let name = plugin.description.name;
|
||||||
let listener = this.register(channel, exec)
|
let listener = this.register(channel, exec)
|
||||||
if (!this.listenerMap[name]) this.listenerMap[name] = []
|
if (!this.listenerMap[name]) this.listenerMap[name] = [];
|
||||||
let offExec = () => {
|
let offExec = () => {
|
||||||
this.unregister(channel, listener)
|
this.unregister(channel, listener);
|
||||||
console.debug(`[${name}] unregister channel ${channel}`)
|
console.debug(`[${name}] unregister channel ${channel}`);
|
||||||
}
|
};
|
||||||
var off = {
|
var off = {
|
||||||
channel,
|
channel,
|
||||||
listener,
|
listener,
|
||||||
off: offExec
|
off: offExec
|
||||||
}
|
};
|
||||||
this.listenerMap[name].push(off)
|
this.listenerMap[name].push(off);
|
||||||
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`)
|
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`);
|
||||||
return off
|
return off;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 关闭插件注册的通道
|
* 关闭插件注册的通道
|
||||||
* @param plugin 插件
|
* @param plugin 插件
|
||||||
*/
|
*/
|
||||||
disable(plugin: any) {
|
disable(plugin: any) {
|
||||||
var channelCache = this.listenerMap[plugin.description.name]
|
var channelCache = this.listenerMap[plugin.description.name];
|
||||||
if (channelCache) {
|
if (channelCache) {
|
||||||
channelCache.forEach(t => t.off())
|
channelCache.forEach(t => t.off());
|
||||||
delete this.listenerMap[plugin.description.name]
|
delete this.listenerMap[plugin.description.name];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
import { injectable } from '@ccms/container'
|
|
||||||
|
|
||||||
export namespace chat {
|
|
||||||
@injectable()
|
|
||||||
export abstract class Chat {
|
|
||||||
/**
|
|
||||||
* sendJsonChat
|
|
||||||
* @param sender reciver
|
|
||||||
* @param json json
|
|
||||||
* @param type chat Type 0: chat 1: system 2: actionBar
|
|
||||||
*/
|
|
||||||
sendJson(sender: any, json: string | object, type = 0) {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
sendMessage(sender: any, message: string) {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
sendActionBar(sender: any, message: string) {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
clearActionBar(sender: any) {
|
|
||||||
this.sendActionBar(sender, '')
|
|
||||||
}
|
|
||||||
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
clearTitle(sender: any) {
|
|
||||||
this.sendTitle(sender, '', '', 0, 0, 0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,125 +1,77 @@
|
|||||||
import i18n from '@ccms/i18n'
|
import i18n from '@ccms/i18n'
|
||||||
import { injectable } from "@ccms/container"
|
import { injectable } from "@ccms/container";
|
||||||
import { plugin } from './plugin'
|
|
||||||
|
|
||||||
export namespace command {
|
export namespace command {
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class Command {
|
export abstract class Command {
|
||||||
/**
|
|
||||||
* first time script engine need optimize jit code
|
|
||||||
* so ignore first slow exec notify
|
|
||||||
*/
|
|
||||||
private cacheSlowKeys = {};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 注册插件命令
|
* 注册插件命令
|
||||||
* @param plugin 插件
|
* @param plugin 插件
|
||||||
* @param name 命令
|
* @param name 命令
|
||||||
* @param exec 执行器
|
* @param exec 执行器
|
||||||
*/
|
*/
|
||||||
on(plugin: plugin.Plugin, name: string, exec: { cmd: Function, tab?: Function }) {
|
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
|
||||||
var cmd = this.create(plugin, name)
|
var cmd = this.create(plugin, name);
|
||||||
if (!cmd) { throw Error(`Plugin ${plugin.description.name} can't create Command ${name}!`) }
|
|
||||||
console.debug(i18n.translate("ms.api.command.register", { plugin: plugin.description.name, name, cmd }))
|
console.debug(i18n.translate("ms.api.command.register", { plugin: plugin.description.name, name, cmd }))
|
||||||
if (exec.cmd && typeof exec.cmd === "function") {
|
if (exec.cmd && typeof exec.cmd === "function") {
|
||||||
this.onCommand(plugin, cmd, exec.cmd)
|
this.onCommand(plugin, cmd, exec.cmd);
|
||||||
} else {
|
} else {
|
||||||
throw Error(i18n.translate("ms.api.command.register.input.error", { exec: exec.cmd }))
|
throw Error(i18n.translate("ms.api.command.register.input.error", { exec: exec.cmd }))
|
||||||
}
|
}
|
||||||
if (exec.tab && typeof exec.tab === "function") {
|
if (exec.tab && typeof exec.tab === "function") {
|
||||||
this.onTabComplete(plugin, cmd, exec.tab)
|
this.onTabComplete(plugin, cmd, exec.tab);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
public tabComplete(sender: any, input: string, index?: number): string[] {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
/**
|
/**
|
||||||
* 取消命令注册
|
* 取消命令注册
|
||||||
* @param plugin 插件
|
* @param plugin 插件
|
||||||
* @param name 命令
|
* @param name 命令
|
||||||
*/
|
*/
|
||||||
off(plugin: plugin.Plugin, name: string) {
|
off(plugin: any, name: string) {
|
||||||
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
|
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
|
||||||
this.remove(plugin, name)
|
this.remove(plugin, name);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected abstract create(plugin: plugin.Plugin, command: string): any
|
protected abstract create(plugin: any, command: string);
|
||||||
protected abstract remove(plugin: plugin.Plugin, command: string): void
|
protected abstract remove(plugin: any, command: string);
|
||||||
protected abstract onCommand(plugin: plugin.Plugin, command: any, executor: Function)
|
protected abstract onCommand(plugin: any, command: any, executor: Function);
|
||||||
protected abstract onTabComplete(plugin: plugin.Plugin, command: any, tabCompleter: Function)
|
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
|
||||||
protected setExecutor(plugin: plugin.Plugin, command: any, executor: Function) {
|
protected setExecutor(plugin: any, command: any, executor: Function) {
|
||||||
return (sender: any, _: any, command: string, args: string[]) => {
|
return (sender: any, _: any, command: string, args: string[]) => {
|
||||||
try {
|
try {
|
||||||
let time = Date.now()
|
return executor(sender, command, Java.from(args));
|
||||||
let result = executor(sender, command, Java.from(args))
|
} catch (ex) {
|
||||||
this.checkSlow(Date.now() - time,
|
console.i18n("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
||||||
"ms.api.command.execute.slow",
|
console.ex(ex);
|
||||||
plugin, command, sender, args)
|
if (sender.name != 'CONSOLE') {
|
||||||
return result
|
console.sender(sender, [i18n.translate("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
|
||||||
} catch (ex: any) {
|
}
|
||||||
this.printError(ex, "ms.api.command.execute.error",
|
return true;
|
||||||
plugin, command, sender, args)
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
protected setTabCompleter(plugin: plugin.Plugin, command: any, tabCompleter: Function) {
|
protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
|
||||||
return (sender: any, _: any, command: string, args: string[]) => {
|
return (sender: any, _: any, command: string, args: string[]) => {
|
||||||
try {
|
try {
|
||||||
let time = Date.now()
|
var token = args[args.length - 1];
|
||||||
var token = args[args.length - 1]
|
var complete = tabCompleter(sender, command, Java.from(args)) || [];
|
||||||
var complete = tabCompleter(sender, command, Java.from(args)) || []
|
return this.copyPartialMatches(complete, token);
|
||||||
let result = this.copyPartialMatches(complete, token)
|
} catch (ex) {
|
||||||
this.checkSlow(Date.now() - time,
|
console.i18n("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
||||||
"ms.api.command.tab.completer.slow",
|
console.ex(ex);
|
||||||
plugin, command, sender, args)
|
console.sender(sender, [i18n.translate("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)]);
|
||||||
return result
|
return [];
|
||||||
} catch (ex: any) {
|
|
||||||
this.printError(ex, "ms.api.command.tab.completer.error",
|
|
||||||
plugin, command, sender, args)
|
|
||||||
return []
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected copyPartialMatches(complete: string[], token: string, array: string[] = []): string[] {
|
protected copyPartialMatches(complete: string[], token: string, array: string[] = []): string[] {
|
||||||
if (!token) { return complete }
|
if (!token) { return complete }
|
||||||
complete.forEach(function (e) {
|
complete.forEach(function (e) {
|
||||||
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
|
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
|
||||||
array.push(e)
|
array.push(e)
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
return array
|
return array
|
||||||
}
|
}
|
||||||
|
|
||||||
private checkSlow(cost: number, key: string, plugin: plugin.Plugin, command: string, sender: any, args: any[]) {
|
|
||||||
if (cost > global.ScriptSlowExecuteTime) {
|
|
||||||
let completerKey = `${plugin.description.name}-${key}-${command}-${sender.name}`
|
|
||||||
if (!this.cacheSlowKeys[completerKey]) {
|
|
||||||
return this.cacheSlowKeys[completerKey] = cost
|
|
||||||
}
|
|
||||||
console.i18n(key, {
|
|
||||||
player: sender.name,
|
|
||||||
plugin: plugin.description.name,
|
|
||||||
command,
|
|
||||||
args: Java.from(args).join(' '),
|
|
||||||
cost
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
private printError(error: Error, key: string, plugin: plugin.Plugin, command: string, sender: any, args: any[]) {
|
|
||||||
let message = i18n.translate(key, {
|
|
||||||
player: sender.name,
|
|
||||||
plugin: plugin.description.name,
|
|
||||||
command,
|
|
||||||
args: Java.from(args).join(' '),
|
|
||||||
error
|
|
||||||
})
|
|
||||||
console.console(message)
|
|
||||||
console.ex(error)
|
|
||||||
if (sender.name != 'CONSOLE') {
|
|
||||||
console.sender(sender, [message, ...console.stack(error)])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ import i18m from '@ccms/i18n'
|
|||||||
import { SourceMapBuilder } from 'source-map-builder'
|
import { SourceMapBuilder } from 'source-map-builder'
|
||||||
import * as base64 from 'base64-js'
|
import * as base64 from 'base64-js'
|
||||||
|
|
||||||
const Arrays = Java.type('java.util.Arrays')
|
const Arrays = Java.type('java.util.Arrays');
|
||||||
const Level = Java.type('java.util.logging.Level')
|
const Level = Java.type('java.util.logging.Level');
|
||||||
const Paths = Java.type('java.nio.file.Paths')
|
const Paths = Java.type('java.nio.file.Paths');
|
||||||
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.internal.dynalink.', 'jdk.nashorn.', 'org.openjdk.nashorn', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
|
const ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.'];
|
||||||
|
|
||||||
enum LogLevel {
|
enum LogLevel {
|
||||||
ALL,
|
ALL,
|
||||||
@@ -18,122 +18,20 @@ enum LogLevel {
|
|||||||
OFF
|
OFF
|
||||||
}
|
}
|
||||||
|
|
||||||
const sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
|
||||||
const sourceFileMaps: { [key: string]: string } = {}
|
|
||||||
|
|
||||||
global.setGlobal('MiaoScriptSourceMaps', sourceMaps)
|
|
||||||
global.setGlobal('MiaoScriptSourceFileMaps', sourceFileMaps)
|
|
||||||
|
|
||||||
export namespace jsconsole {
|
|
||||||
export function readSourceMap(fileName: string, lineNumber: any) {
|
|
||||||
if (lineNumber == 1) return { fileName, lineNumber }
|
|
||||||
try {
|
|
||||||
if (fileName.endsWith('js') || fileName.endsWith('ms')) {
|
|
||||||
if (sourceMaps[fileName] === undefined) {
|
|
||||||
sourceMaps[fileName] = null
|
|
||||||
let sourceLine = base.read(fileName).split('\n')
|
|
||||||
let lastLine = sourceLine[sourceLine.length - 1] || sourceLine[sourceLine.length - 2]
|
|
||||||
// lastLine is similar //# sourceMappingURL=data:application/json;base64,
|
|
||||||
if (lastLine.startsWith('//# sourceMappingURL=')) {
|
|
||||||
let sourceContent = null
|
|
||||||
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
|
|
||||||
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
|
||||||
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
|
||||||
} else if (sourceMappingURL.startsWith('http://') || sourceMappingURL.startsWith('https://')) {
|
|
||||||
// TODO
|
|
||||||
} else {
|
|
||||||
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
|
|
||||||
if (file.exists()) {
|
|
||||||
sourceContent = base.read(file)
|
|
||||||
sourceFileMaps[fileName] = file.getCanonicalPath()
|
|
||||||
} else if (global.debug) {
|
|
||||||
console.debug('readSourceMap can\'t found', fileName, 'source map file', sourceMappingURL)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (sourceContent) {
|
|
||||||
sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (sourceMaps[fileName]) {
|
|
||||||
let sourceMapping = sourceMaps[fileName].getSource(lineNumber, 25, true, true)
|
|
||||||
if (sourceMapping) {
|
|
||||||
fileName = Paths.get(fileName, '..', sourceMapping.sourcePath).toFile().getCanonicalPath()
|
|
||||||
lineNumber = sourceMapping.mapping.sourceLine
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
|
|
||||||
if (global.debug) {
|
|
||||||
console.ex(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { fileName, lineNumber }
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getStackTrace(ex: Error, color: boolean = true): string[] {
|
|
||||||
if (!ex) return []
|
|
||||||
let stack = ex.getStackTrace()
|
|
||||||
let cache = [(color ? '§c' : '') + ex]
|
|
||||||
//@ts-ignore
|
|
||||||
if (stack.class) {
|
|
||||||
stack = Arrays.asList(stack)
|
|
||||||
}
|
|
||||||
stack.forEach(trace => {
|
|
||||||
if (!trace.fileName || trace.fileName.startsWith('jar:file:') || trace.fileName.startsWith('file:')) { return }
|
|
||||||
if (trace.className.startsWith('<')) {
|
|
||||||
let { fileName, lineNumber } = readSourceMap(trace.fileName, trace.lineNumber)
|
|
||||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
|
||||||
if (color) {
|
|
||||||
cache.push(` §e->§c ${fileName}:${lineNumber}(${trace.lineNumber}) => §4${trace.methodName}`)
|
|
||||||
} else {
|
|
||||||
cache.push(` -> ${fileName}:${lineNumber}(${trace.lineNumber}) => ${trace.methodName}`)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let className = trace.className
|
|
||||||
var fileName = trace.fileName as string
|
|
||||||
var lineNumber = trace.lineNumber
|
|
||||||
if (className.startsWith('jdk.nashorn.internal.scripts') || className.startsWith('org.openjdk.nashorn.internal.scripts')) {
|
|
||||||
className = className.substr(className.lastIndexOf('$') + 1)
|
|
||||||
var { fileName, lineNumber } = readSourceMap(fileName, lineNumber)
|
|
||||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
|
||||||
} else {
|
|
||||||
if (!global.debug) {
|
|
||||||
for (let prefix in ignoreLogPrefix) {
|
|
||||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (className.startsWith('jdk.nashorn.internal.') || className.startsWith('org.openjdk.nashorn.internal.')) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (color) {
|
|
||||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
|
|
||||||
} else {
|
|
||||||
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return cache
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class MiaoScriptConsole implements Console {
|
export class MiaoScriptConsole implements Console {
|
||||||
Console: any
|
Console: NodeJS.ConsoleConstructor;
|
||||||
memory: any
|
|
||||||
|
|
||||||
private _name: string = ''
|
private sourceMaps: { [key: string]: SourceMapBuilder } = {};
|
||||||
private _level: LogLevel = LogLevel.INFO
|
private sourceFileMaps: { [key: string]: string } = {};
|
||||||
|
private _name: string = '';
|
||||||
|
private _level: LogLevel = LogLevel.INFO;
|
||||||
|
|
||||||
protected logger: any
|
protected logger: any;
|
||||||
|
protected prefix: string = '§6[§bMiaoScript§6]§r ';
|
||||||
public prefix: string = '§6[§bMiaoScript§6]§r '
|
|
||||||
|
|
||||||
constructor(name?: string) {
|
constructor(name?: string) {
|
||||||
this.name = name
|
this.name = name;
|
||||||
this.logger = global.logger
|
this.logger = global.logger;
|
||||||
if (global.debug) {
|
if (global.debug) {
|
||||||
this._level = LogLevel.DEBUG
|
this._level = LogLevel.DEBUG
|
||||||
}
|
}
|
||||||
@@ -143,36 +41,36 @@ export class MiaoScriptConsole implements Console {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get name() {
|
get name() {
|
||||||
return this._name
|
return this._name;
|
||||||
}
|
}
|
||||||
|
|
||||||
set name(name: string) {
|
set name(name: string) {
|
||||||
if (name) {
|
if (name) {
|
||||||
this._name = `[${name}] `
|
this._name = `[${name}] `;
|
||||||
this.prefix = `§6[§cMS§6][§b${name}§6]§r `
|
// noinspection JSUnusedGlobalSymbols
|
||||||
|
this.prefix = `§6[§cMS§6][§b${name}§6]§r `;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
log(...args: any[]): void {
|
log(...args: any[]): void {
|
||||||
this.logger.info(this.name + args.join(' '))
|
this.logger.info(this.name + args.join(' '));
|
||||||
}
|
}
|
||||||
info(...args: any[]) {
|
info(...args: any[]) {
|
||||||
this.logger.info(this.name + args.join(' '))
|
this.logger.info(this.name + args.join(' '));
|
||||||
}
|
}
|
||||||
warn(...args: any[]) {
|
warn(...args: any[]) {
|
||||||
this.logger.warning(this.name + args.join(' '))
|
this.logger.warning(this.name + args.join(' '));
|
||||||
}
|
}
|
||||||
error(...args: any[]) {
|
error(...args: any[]) {
|
||||||
this.logger.log(Level.SEVERE, this.name + args.join(' '))
|
this.logger.log(Level.SEVERE, this.name + args.join(' '));
|
||||||
}
|
}
|
||||||
debug(...args: any[]) {
|
debug(...args: any[]) {
|
||||||
if (global.debug) {
|
if (global.debug) {
|
||||||
this.logger.info(this.name + '[DEBUG] ' + args.join(' '))
|
this.logger.info(this.name + '[DEBUG] ' + args.join(' '));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
trace(...args: any[]): void {
|
trace(...args: any[]): void {
|
||||||
if (this._level <= LogLevel.TRACE) {
|
if (this._level <= LogLevel.TRACE) {
|
||||||
this.logger.info(this.name + '[TRACE] ' + args.join(' '))
|
this.logger.info(this.name + '[TRACE] ' + args.join(' '));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
sender(...args) {
|
sender(...args) {
|
||||||
@@ -192,67 +90,130 @@ export class MiaoScriptConsole implements Console {
|
|||||||
ex(ex: Error) {
|
ex(ex: Error) {
|
||||||
this.stack(ex).forEach(line => this.console(line))
|
this.stack(ex).forEach(line => this.console(line))
|
||||||
}
|
}
|
||||||
stack(ex: Error, color: boolean = true): string[] {
|
readSourceMap(fileName: string, lineNumber: number) {
|
||||||
return jsconsole.getStackTrace(ex, color)
|
try {
|
||||||
|
if (fileName.endsWith('js')) {
|
||||||
|
if (this.sourceMaps[fileName] === undefined) {
|
||||||
|
this.sourceMaps[fileName] = null
|
||||||
|
let sourceLine = base.read(fileName).split('\n');
|
||||||
|
let lastLine = sourceLine[sourceLine.length - 1]
|
||||||
|
if (lastLine.startsWith('//# sourceMappingURL=')) {
|
||||||
|
let sourceContent = null;
|
||||||
|
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1];
|
||||||
|
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
||||||
|
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
||||||
|
} else if (sourceMappingURL.startsWith('http')) {
|
||||||
|
// TODO
|
||||||
|
} else {
|
||||||
|
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile();
|
||||||
|
if (file.exists()) { sourceContent = base.read(file) }
|
||||||
|
}
|
||||||
|
if (sourceContent) {
|
||||||
|
this.sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
||||||
|
this.sourceFileMaps[fileName] = Paths.get(fileName, '..', this.sourceMaps[fileName].sources[0]).toFile().getCanonicalPath();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (this.sourceMaps[fileName]) {
|
||||||
|
let sourceMapping = this.sourceMaps[fileName].getSource(lineNumber, 25, true, true);
|
||||||
|
fileName = this.sourceFileMaps[fileName]
|
||||||
|
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
fileName,
|
||||||
|
lineNumber
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stack(ex: Error): string[] {
|
||||||
|
let stack = ex.getStackTrace();
|
||||||
|
let cache = ['§c' + ex];
|
||||||
|
//@ts-ignore
|
||||||
|
if (stack.class) {
|
||||||
|
stack = Arrays.asList(stack)
|
||||||
|
}
|
||||||
|
stack.forEach(trace => {
|
||||||
|
if (trace.className.startsWith('<')) {
|
||||||
|
let { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||||
|
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||||
|
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${lineNumber}`)
|
||||||
|
} else {
|
||||||
|
let className = trace.className;
|
||||||
|
var fileName = trace.fileName as string;
|
||||||
|
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
||||||
|
className = className.substr(className.lastIndexOf('$') + 1)
|
||||||
|
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||||
|
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||||
|
} else {
|
||||||
|
for (let prefix in ignoreLogPrefix) {
|
||||||
|
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return cache;
|
||||||
}
|
}
|
||||||
assert(value: any, message?: string, ...optionalParams: any[]): void {
|
assert(value: any, message?: string, ...optionalParams: any[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
clear(): void {
|
clear(): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
count(label?: string): void {
|
count(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
countReset(label?: string): void {
|
countReset(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
dir(obj: any, options?: any): void {
|
dir(obj: any, options?: NodeJS.InspectOptions): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
dirxml(...data: any[]): void {
|
dirxml(...data: any[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
|
||||||
exception(message?: string, ...optionalParams: any[]): void {
|
|
||||||
throw new Error('Method not implemented.')
|
|
||||||
}
|
}
|
||||||
group(...label: any[]): void {
|
group(...label: any[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
groupCollapsed(...label: any[]): void {
|
groupCollapsed(...label: any[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
groupEnd(): void {
|
groupEnd(): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
table(tabularData: any, properties?: string[]): void {
|
table(tabularData: any, properties?: string[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
time(label?: string): void {
|
time(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
timeEnd(label?: string): void {
|
timeEnd(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
timeLog(label?: string, ...data: any[]): void {
|
timeLog(label?: string, ...data: any[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
markTimeline(label?: string): void {
|
markTimeline(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
profile(label?: string): void {
|
profile(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
profileEnd(label?: string): void {
|
profileEnd(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
timeStamp(label?: string): void {
|
timeStamp(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
timeline(label?: string): void {
|
timeline(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
timelineEnd(label?: string): void {
|
timelineEnd(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,38 +1,16 @@
|
|||||||
export namespace constants {
|
export namespace constants {
|
||||||
export namespace ServiceIdentifier {
|
|
||||||
/**
|
|
||||||
* Runtime Server NettyPipeline
|
|
||||||
*/
|
|
||||||
export const NettyPipeline = Symbol("NettyPipeline")
|
|
||||||
/**
|
|
||||||
* Runtime Server RootLogger
|
|
||||||
*/
|
|
||||||
export const RootLogger = Symbol("RootLogger")
|
|
||||||
}
|
|
||||||
export namespace Reflect {
|
export namespace Reflect {
|
||||||
export const Method = {
|
export const Method = {
|
||||||
getServerConnection: [
|
getServerConnection: [/*spigot 1.8.8*/'aq',/*spigot 1.12.2*/ 'an', /*spigot 1.14.4+*/'getServerConnection', /*catserver 1.12.2*/'func_147137_ag']
|
||||||
/*spigot 1.8.8*/'aq',
|
|
||||||
/*spigot 1.12.2*/ 'an',
|
|
||||||
/*spigot 1.14.4+*/'getServerConnection',
|
|
||||||
/*spigot 1.19+*/'ad',
|
|
||||||
/*catserver 1.12.2*/'func_147137_ag'
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
export const Field = {
|
export const Field = {
|
||||||
listeningChannels: [
|
listeningChannels: [/*spigot 1.8.8-1.12.2*/'g', /*spigot 1.14.4*/'f', /*spigot 1.15.2+*/'listeningChannels', /*catserver 1.12.2*/'field_151274_e']
|
||||||
/*spigot 1.8.8-1.12.2*/'g',
|
|
||||||
/*spigot 1.14.4*/'f',
|
|
||||||
/*spigot 1.15.2+*/'listeningChannels',
|
|
||||||
/*catserver 1.12.2*/'field_151274_e'
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export enum ServerType {
|
export enum ServerType {
|
||||||
Bukkit = 'bukkit',
|
Bukkit = 'bukkit',
|
||||||
Sponge = 'sponge',
|
Sponge = 'sponge',
|
||||||
Nukkit = 'nukkit',
|
Nukkit = 'nukkit',
|
||||||
Bungee = 'bungee',
|
Bungee = 'bungee'
|
||||||
Spring = 'spring'
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
import { injectable } from "@ccms/container"
|
|
||||||
|
|
||||||
export namespace database {
|
|
||||||
export const DataSource = Symbol("DataSource")
|
|
||||||
/**
|
|
||||||
* 数据库配置
|
|
||||||
*/
|
|
||||||
export interface DataBaseConfig {
|
|
||||||
/**
|
|
||||||
* 数据库类型
|
|
||||||
*/
|
|
||||||
type: 'h2' | 'mysql' | 'mongodb' | 'sqlite' | 'postgres' | 'redis'
|
|
||||||
/**
|
|
||||||
* 数据库连接串
|
|
||||||
*/
|
|
||||||
url: string | javax.sql.DataSource
|
|
||||||
/**
|
|
||||||
* 数据库驱动
|
|
||||||
*/
|
|
||||||
driverClassName?: string
|
|
||||||
/**
|
|
||||||
* 用户名
|
|
||||||
*/
|
|
||||||
username?: string
|
|
||||||
/**
|
|
||||||
* 密码
|
|
||||||
*/
|
|
||||||
password?: string
|
|
||||||
/**
|
|
||||||
* 链接属性
|
|
||||||
*/
|
|
||||||
properties?: { [key: string]: any }
|
|
||||||
/**
|
|
||||||
* 调试模式
|
|
||||||
*/
|
|
||||||
debug?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
@injectable()
|
|
||||||
export abstract class DataBaseManager {
|
|
||||||
abstract setMainDatabase(mainDatabase: DataBase): void
|
|
||||||
abstract getMainDatabase(): DataBase
|
|
||||||
abstract createDatabase(name: string, config: DataBaseConfig): DataBase
|
|
||||||
abstract removeDatabase(name: string): boolean
|
|
||||||
abstract getDatabase(name: string): DataBase
|
|
||||||
abstract startWebManager(...args: string[])
|
|
||||||
abstract stopWebManager()
|
|
||||||
abstract shutdown()
|
|
||||||
}
|
|
||||||
@injectable()
|
|
||||||
export abstract class DataBase {
|
|
||||||
abstract query<T>(sql: string, ...args: any[]): Array<T>
|
|
||||||
abstract update(sql: string, ...args: any[]): number
|
|
||||||
abstract execute(sql: string): void
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
import i18n from '@ccms/i18n'
|
import i18n from '@ccms/i18n'
|
||||||
import { injectable, unmanaged } from '@ccms/container'
|
import { injectable, unmanaged } from '@ccms/container'
|
||||||
|
|
||||||
const Thread = Java.type('java.lang.Thread')
|
const Thread = Java.type('java.lang.Thread');
|
||||||
|
|
||||||
export namespace event {
|
export namespace event {
|
||||||
/**
|
/**
|
||||||
@@ -21,17 +21,13 @@ export namespace event {
|
|||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class Event {
|
export abstract class Event {
|
||||||
// export EventPriority to blockly
|
|
||||||
public EventPriority = EventPriority;
|
|
||||||
|
|
||||||
private mapEvent = [];
|
private mapEvent = [];
|
||||||
private pluginEventMap = [];
|
private listenerMap = [];
|
||||||
private cacheSlowEventKey = {};
|
|
||||||
|
|
||||||
protected baseEventDir = '';
|
protected baseEventDir = '';
|
||||||
|
|
||||||
constructor(@unmanaged() baseEventDir: string) {
|
constructor(@unmanaged() baseEventDir: string) {
|
||||||
this.baseEventDir = baseEventDir
|
this.baseEventDir = baseEventDir;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -40,134 +36,115 @@ export namespace event {
|
|||||||
* org.spongepowered.api.event.game.GameRegistryEvent.Register => gameregistryevent$register
|
* org.spongepowered.api.event.game.GameRegistryEvent.Register => gameregistryevent$register
|
||||||
*/
|
*/
|
||||||
mapEventName() {
|
mapEventName() {
|
||||||
if (this.baseEventDir === "") { throw new Error(i18n.translate('ms.api.event.empty.event.dir')) }
|
if (this.baseEventDir === "") { throw new Error(i18n.translate('ms.api.event.empty.event.dir')); }
|
||||||
let count = 0
|
let count = 0;
|
||||||
let jar = this.getJarFile(this.baseEventDir)
|
let jar = this.getJarFile(this.baseEventDir);
|
||||||
let entries = jar.entries()
|
let entries = jar.entries();
|
||||||
while (entries.hasMoreElements()) {
|
while (entries.hasMoreElements()) {
|
||||||
let entry = entries.nextElement()
|
let entry = entries.nextElement();
|
||||||
let name = entry.name
|
let name = entry.name;
|
||||||
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
|
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
|
||||||
// replace name to qualifiedName
|
// replace name to qualifiedName
|
||||||
let qualifiedName = name.replaceAll('/', '.')
|
let qualifiedName = name.replaceAll('/', '.');
|
||||||
try {
|
try {
|
||||||
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6))
|
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6));
|
||||||
if (this.isValidEvent(clazz)) {
|
if (this.isValidEvent(clazz)) {
|
||||||
let simpleName = this.class2Name(clazz).toLowerCase()
|
let simpleName = this.class2Name(clazz).toLowerCase();
|
||||||
console.trace(i18n.translate("ms.api.event.mapping", { canonicalName: clazz.canonicalName, simpleName }))
|
console.trace(i18n.translate("ms.api.event.mapping", { canonicalName: clazz.canonicalName, simpleName }));
|
||||||
this.mapEvent[simpleName] = clazz
|
this.mapEvent[simpleName] = clazz;
|
||||||
count++
|
count++;
|
||||||
}
|
}
|
||||||
} catch (ex: any) {
|
} catch (ex) {
|
||||||
//ignore already loaded class
|
//ignore already loaded class
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return count
|
return count;
|
||||||
}
|
}
|
||||||
|
|
||||||
getJarFile(resource: string, loader?: any) {
|
getJarFile(resource: string, loader?: any) {
|
||||||
let dirs = (loader || Thread.currentThread().getContextClassLoader()).getResources(resource)
|
let dirs = (loader || Thread.currentThread().getContextClassLoader()).getResources(resource);
|
||||||
if (dirs.hasMoreElements()) {
|
if (dirs.hasMoreElements()) {
|
||||||
let url = dirs.nextElement()
|
let url = dirs.nextElement();
|
||||||
if (url.protocol === "jar") { return url.openConnection().jarFile }
|
if (url.protocol === "jar") { return url.openConnection().jarFile; }
|
||||||
}
|
}
|
||||||
throw new Error(i18n.translate("ms.api.event.resource.not.found", { resource }))
|
throw new Error(i18n.translate("ms.api.event.resource.not.found", { resource }))
|
||||||
}
|
}
|
||||||
|
|
||||||
class2Name(clazz: any) {
|
class2Name(clazz: any) {
|
||||||
return clazz.simpleName
|
return clazz.simpleName;
|
||||||
}
|
}
|
||||||
|
|
||||||
name2Class(name: any, event: string) {
|
name2Class(name: any, event: string) {
|
||||||
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event']
|
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
|
||||||
if (!eventCls) {
|
if (!eventCls) {
|
||||||
try {
|
try {
|
||||||
eventCls = base.getClass(event)
|
eventCls = base.getClass(eventCls);
|
||||||
this.mapEvent[event] = eventCls
|
this.mapEvent[event] = eventCls;
|
||||||
} catch (ex: any) {
|
} catch (ex) {
|
||||||
console.i18n("ms.api.event.not.found", { name, event })
|
console.i18n("ms.api.event.not.found", { name, event })
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return eventCls
|
return eventCls;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
execute(name, exec, eventCls) {
|
||||||
* 创建命令执行器
|
|
||||||
* @param name 插件名称
|
|
||||||
* @param exec 执行方法
|
|
||||||
* @param eventCls 事件类
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
createExecute(name, exec, eventCls) {
|
|
||||||
return (...args: any[]) => {
|
return (...args: any[]) => {
|
||||||
let event = args[args.length - 1]
|
|
||||||
try {
|
try {
|
||||||
if (!eventCls.isAssignableFrom(event.getClass())) { return }
|
let event = args[args.length - 1];
|
||||||
let time = Date.now(); exec(event); let cost = Date.now() - time
|
if (eventCls.isAssignableFrom(event.getClass())) {
|
||||||
if (cost > global.ScriptSlowExecuteTime && !event.async) {
|
let time = Date.now()
|
||||||
let eventKey = `${name}-${this.class2Name(eventCls)}`
|
exec(event);
|
||||||
if (!this.cacheSlowEventKey[eventKey]) { return this.cacheSlowEventKey[eventKey] = cost }
|
let cost = Date.now() - time;
|
||||||
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
|
if (cost > 20) {
|
||||||
|
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (ex: any) {
|
} catch (ex) {
|
||||||
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
|
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
|
||||||
console.ex(ex)
|
console.ex(ex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 添加事件监听
|
* 添加事件监听
|
||||||
* @param plugin {any} 插件
|
* @param plugin {any}
|
||||||
* @param event {string} 事件名称
|
* @param event {string}
|
||||||
* @param exec {function} 事件执行器
|
* @param exec {function}
|
||||||
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR] 优先级
|
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
|
||||||
* @param ignoreCancel 是否忽略已取消事件
|
* @param ignoreCancel
|
||||||
*/
|
*/
|
||||||
listen(plugin: any, event: string, exec: (event: any) => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
|
listen(plugin: any, event: string, exec: (event: any) => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
|
||||||
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"))
|
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"));
|
||||||
var name = plugin.description.name
|
var name = plugin.description.name;
|
||||||
var eventCls = this.name2Class(name, event)
|
var eventCls = this.name2Class(name, event);
|
||||||
if (!eventCls) { return () => { console.warn('event ' + event + ' not found ignore off listener.') } }
|
if (!eventCls) { return; }
|
||||||
if (typeof priority === 'boolean') {
|
if (typeof priority === 'boolean') {
|
||||||
ignoreCancel = priority
|
ignoreCancel = priority;
|
||||||
priority = EventPriority.NORMAL
|
priority = EventPriority.NORMAL;
|
||||||
}
|
}
|
||||||
priority = priority || EventPriority.NORMAL
|
priority = priority || EventPriority.NORMAL;
|
||||||
ignoreCancel = ignoreCancel || false
|
ignoreCancel = ignoreCancel || false;
|
||||||
// @ts-ignore
|
|
||||||
let executor = exec.name || exec.executor || '[anonymous]'
|
|
||||||
// noinspection JSUnusedGlobalSymbols
|
// noinspection JSUnusedGlobalSymbols
|
||||||
let listener = this.register(
|
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel);
|
||||||
eventCls,
|
var listenerMap = this.listenerMap;
|
||||||
this.createExecute(name, exec, eventCls),
|
|
||||||
priority,
|
|
||||||
ignoreCancel
|
|
||||||
)
|
|
||||||
// add to cache Be used for close plugin to close event
|
// add to cache Be used for close plugin to close event
|
||||||
if (!this.pluginEventMap[name]) this.pluginEventMap[name] = []
|
if (!listenerMap[name]) listenerMap[name] = [];
|
||||||
let off = () => {
|
var offExec = () => {
|
||||||
if (off['offed']) return
|
this.unregister(eventCls, listener);
|
||||||
off['offed'] = true
|
console.debug(i18n.translate("ms.api.event.unregister", { name, event: this.class2Name(eventCls) }));
|
||||||
this.unregister(eventCls, listener)
|
};
|
||||||
console.debug(i18n.translate("ms.api.event.unregister", {
|
var off = {
|
||||||
name,
|
event: eventCls,
|
||||||
event: this.class2Name(eventCls),
|
listener: listener,
|
||||||
exec: executor
|
off: offExec
|
||||||
}))
|
};
|
||||||
}
|
listenerMap[name].push(off);
|
||||||
this.pluginEventMap[name].push(off)
|
|
||||||
// noinspection JSUnresolvedVariable
|
// noinspection JSUnresolvedVariable
|
||||||
console.debug(i18n.translate("ms.api.event.register", {
|
console.debug(i18n.translate("ms.api.event.register", { name, event: this.class2Name(eventCls) }));
|
||||||
name,
|
return off;
|
||||||
event: this.class2Name(eventCls),
|
|
||||||
exec: executor,
|
|
||||||
priority,
|
|
||||||
ignore: ignoreCancel
|
|
||||||
}))
|
|
||||||
return off
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -175,10 +152,10 @@ export namespace event {
|
|||||||
* @param plugin 插件
|
* @param plugin 插件
|
||||||
*/
|
*/
|
||||||
disable(plugin: any) {
|
disable(plugin: any) {
|
||||||
var eventCache = this.pluginEventMap[plugin.description.name]
|
var eventCache = this.listenerMap[plugin.description.name];
|
||||||
if (eventCache) {
|
if (eventCache) {
|
||||||
eventCache.forEach((off: () => any) => off())
|
eventCache.forEach(t => t.off());
|
||||||
delete this.pluginEventMap[plugin.description.name]
|
delete this.listenerMap[plugin.description.name];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,7 +163,7 @@ export namespace event {
|
|||||||
* 判断
|
* 判断
|
||||||
* @param clazz 事件类
|
* @param clazz 事件类
|
||||||
*/
|
*/
|
||||||
abstract isValidEvent(clazz: any): boolean
|
abstract isValidEvent(clazz: any): boolean;
|
||||||
/**
|
/**
|
||||||
* 注册事件
|
* 注册事件
|
||||||
* @param eventCls 事件类
|
* @param eventCls 事件类
|
||||||
@@ -194,12 +171,12 @@ export namespace event {
|
|||||||
* @param priority 优先级
|
* @param priority 优先级
|
||||||
* @param ignoreCancel 是否忽略已取消的事件
|
* @param ignoreCancel 是否忽略已取消的事件
|
||||||
*/
|
*/
|
||||||
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any
|
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any;
|
||||||
/**
|
/**
|
||||||
* 取消监听事件
|
* 取消监听事件
|
||||||
* @param event 事件
|
* @param event 事件
|
||||||
* @param listener 监听器
|
* @param listener 监听器
|
||||||
*/
|
*/
|
||||||
abstract unregister(event: any, listener: any): void
|
abstract unregister(event: any, listener: any): void;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,8 @@
|
|||||||
import "@ccms/nashorn"
|
import "@ccms/nashorn"
|
||||||
|
|
||||||
export * from './chat'
|
|
||||||
export * from './task'
|
export * from './task'
|
||||||
export * from './item'
|
|
||||||
export * from './event'
|
export * from './event'
|
||||||
export * from './proxy'
|
|
||||||
export * from './plugin'
|
|
||||||
export * from './server'
|
|
||||||
export * from './console'
|
export * from './console'
|
||||||
export { jsconsole as console } from './console'
|
|
||||||
export * from './channel'
|
export * from './channel'
|
||||||
export * from './command'
|
export * from './command'
|
||||||
export * from './database'
|
|
||||||
export * from './particle'
|
|
||||||
export * from './constants'
|
export * from './constants'
|
||||||
|
export * from './interfaces'
|
||||||
|
|||||||
2
packages/api/src/interfaces/index.ts
Normal file
2
packages/api/src/interfaces/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export * from './plugin'
|
||||||
|
export * from './server'
|
||||||
74
packages/api/src/interfaces/plugin.ts
Normal file
74
packages/api/src/interfaces/plugin.ts
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
export namespace plugin {
|
||||||
|
/**
|
||||||
|
* MiaoScript Plugin
|
||||||
|
*/
|
||||||
|
export const Plugin = Symbol("Plugin");
|
||||||
|
/**
|
||||||
|
* MiaoScript Plugin Folder
|
||||||
|
*/
|
||||||
|
export const PluginFolder = Symbol("PluginFolder");
|
||||||
|
/**
|
||||||
|
* Runtime Plugin Instance
|
||||||
|
*/
|
||||||
|
export const PluginInstance = Symbol("PluginInstance");
|
||||||
|
/**
|
||||||
|
* MiaoScript Plugin Manager Symbol
|
||||||
|
*/
|
||||||
|
export const PluginManager = Symbol("PluginManager");
|
||||||
|
/**
|
||||||
|
* MiaoScript Plugin Manager Interface
|
||||||
|
*/
|
||||||
|
export interface PluginManager {
|
||||||
|
scan(folder: string): void;
|
||||||
|
build(): void;
|
||||||
|
loadFromFile(file: string): Plugin;
|
||||||
|
load(...args: any[]): void;
|
||||||
|
enable(...args: any[]): void;
|
||||||
|
disable(...args: any[]): void;
|
||||||
|
reload(...args: any[]): void;
|
||||||
|
getPlugins(): Map<string, any>;
|
||||||
|
}
|
||||||
|
export interface Plugin {
|
||||||
|
description: PluginMetadata;
|
||||||
|
logger: Console;
|
||||||
|
load(): void;
|
||||||
|
enable(): void;
|
||||||
|
disable(): void;
|
||||||
|
}
|
||||||
|
interface BaseMetadata {
|
||||||
|
/**
|
||||||
|
* 名称 为空则为对象名称
|
||||||
|
*/
|
||||||
|
name?: string;
|
||||||
|
/**
|
||||||
|
* 支持的服务器列表 为空则代表所有
|
||||||
|
*/
|
||||||
|
servers?: string[];
|
||||||
|
}
|
||||||
|
export interface PluginMetadata extends BaseMetadata {
|
||||||
|
/**
|
||||||
|
* 插件名称
|
||||||
|
*/
|
||||||
|
name: string;
|
||||||
|
/**
|
||||||
|
* 前缀
|
||||||
|
*/
|
||||||
|
prefix?: string;
|
||||||
|
/**
|
||||||
|
* 插件版本
|
||||||
|
*/
|
||||||
|
version: string;
|
||||||
|
/**
|
||||||
|
* 插件版本
|
||||||
|
*/
|
||||||
|
author: string | string[];
|
||||||
|
/**
|
||||||
|
* 插件源文件 必须指定为 __filename
|
||||||
|
*/
|
||||||
|
source: string;
|
||||||
|
/**
|
||||||
|
* 插件本体
|
||||||
|
*/
|
||||||
|
target?: any;
|
||||||
|
}
|
||||||
|
}
|
||||||
36
packages/api/src/interfaces/server/index.ts
Normal file
36
packages/api/src/interfaces/server/index.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { NativePluginManager } from './native_plugin'
|
||||||
|
|
||||||
|
export namespace server {
|
||||||
|
/**
|
||||||
|
* Runtime ServerType
|
||||||
|
*/
|
||||||
|
export const ServerType = Symbol("ServerType");
|
||||||
|
/**
|
||||||
|
* Runtime Console
|
||||||
|
*/
|
||||||
|
export const Console = Symbol("Console");
|
||||||
|
/**
|
||||||
|
* MiaoScript Server
|
||||||
|
*/
|
||||||
|
export const Server = Symbol("Server");
|
||||||
|
/**
|
||||||
|
* Runtime Server Instance
|
||||||
|
*/
|
||||||
|
export const ServerInstance = Symbol("ServerInstance");
|
||||||
|
/**
|
||||||
|
* MiaoScript Server
|
||||||
|
*/
|
||||||
|
export interface Server {
|
||||||
|
getVersion(): string;
|
||||||
|
getPlayer(name: string): any;
|
||||||
|
getOnlinePlayers(): any[];
|
||||||
|
getConsoleSender(): any;
|
||||||
|
getService(service: string): any;
|
||||||
|
dispatchCommand(sender: string | any, command: string): boolean;
|
||||||
|
dispatchConsoleCommand(command: string): boolean;
|
||||||
|
getPluginsFolder(): string;
|
||||||
|
getNativePluginManager(): NativePluginManager;
|
||||||
|
getNettyPipeline(): any;
|
||||||
|
sendJson(sender: string | any, json: object | string): void;
|
||||||
|
}
|
||||||
|
}
|
||||||
6
packages/api/src/interfaces/server/native_plugin.ts
Normal file
6
packages/api/src/interfaces/server/native_plugin.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export interface NativePluginManager {
|
||||||
|
load(name: string): boolean;
|
||||||
|
unload(name: string): boolean;
|
||||||
|
reload(name: string): boolean;
|
||||||
|
delete(name: string): boolean;
|
||||||
|
}
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
import { injectable } from '@ccms/container'
|
|
||||||
|
|
||||||
export namespace item {
|
|
||||||
@injectable()
|
|
||||||
export abstract class Item {
|
|
||||||
abstract builder(): ItemBuilder
|
|
||||||
abstract toJson(item: any): string
|
|
||||||
abstract fromJson(json: string): any
|
|
||||||
}
|
|
||||||
export interface ItemBuilder {
|
|
||||||
from(item: any): ItemBuilder
|
|
||||||
create(type: string | number): ItemBuilder
|
|
||||||
name(name: string): ItemBuilder
|
|
||||||
lore(...lores: string[]): ItemBuilder
|
|
||||||
amount(amount: number): ItemBuilder
|
|
||||||
durability(durability: number): ItemBuilder
|
|
||||||
clone(): any
|
|
||||||
build(): any
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,507 +0,0 @@
|
|||||||
import { Autowired, injectable } from '@ccms/container'
|
|
||||||
|
|
||||||
import { task, plugin } from './index'
|
|
||||||
|
|
||||||
const UUID = Java.type('java.util.UUID')
|
|
||||||
const Math = Java.type('java.lang.Math')
|
|
||||||
|
|
||||||
export namespace particle {
|
|
||||||
@injectable()
|
|
||||||
export abstract class ParticleSpawner {
|
|
||||||
abstract spawn(location: any, particle: Particle)
|
|
||||||
abstract spawnToPlayer(player: any, location: any, particle: Particle)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 表示一个特效对象
|
|
||||||
*
|
|
||||||
* @author Zoyn
|
|
||||||
*/
|
|
||||||
export abstract class Particle {
|
|
||||||
private spawner: ParticleSpawner
|
|
||||||
private readonly uuid: string
|
|
||||||
|
|
||||||
private particle: any /* Particle */
|
|
||||||
private count: number = 1;
|
|
||||||
private offsetX: number = 0;
|
|
||||||
private offsetY: number = 0;
|
|
||||||
private offsetZ: number = 0;
|
|
||||||
private extra: number = 0;
|
|
||||||
private data: Object = null;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Only Show To Player
|
|
||||||
*/
|
|
||||||
private player: any
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
this.uuid = UUID.randomUUID().toString()
|
|
||||||
}
|
|
||||||
abstract show(location: any)
|
|
||||||
|
|
||||||
getUUID() {
|
|
||||||
return this.uuid
|
|
||||||
}
|
|
||||||
|
|
||||||
getSpawner() {
|
|
||||||
return this.spawner
|
|
||||||
}
|
|
||||||
|
|
||||||
setSpawner(spawner: ParticleSpawner) {
|
|
||||||
this.spawner = spawner
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
getParticle() {
|
|
||||||
return this.particle
|
|
||||||
}
|
|
||||||
|
|
||||||
setParticle(particle: any, data: any = null) {
|
|
||||||
this.particle = particle
|
|
||||||
this.data = data
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
getCount() {
|
|
||||||
return this.count
|
|
||||||
}
|
|
||||||
|
|
||||||
setCount(count: number) {
|
|
||||||
this.count = count
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
getOffsetX() {
|
|
||||||
return this.offsetX
|
|
||||||
}
|
|
||||||
|
|
||||||
setOffsetX(offsetX: number) {
|
|
||||||
this.offsetX = offsetX
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
getOffsetY() {
|
|
||||||
return this.offsetY
|
|
||||||
}
|
|
||||||
|
|
||||||
setOffsetY(offsetY: number) {
|
|
||||||
this.offsetY = offsetY
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
getOffsetZ() {
|
|
||||||
return this.offsetZ
|
|
||||||
}
|
|
||||||
|
|
||||||
setOffsetZ(offsetZ: number) {
|
|
||||||
this.offsetZ = offsetZ
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
getExtra() {
|
|
||||||
return this.extra
|
|
||||||
}
|
|
||||||
|
|
||||||
setExtra(extra: number) {
|
|
||||||
this.extra = extra
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
getData() {
|
|
||||||
return this.data
|
|
||||||
}
|
|
||||||
|
|
||||||
setData(data) {
|
|
||||||
this.data = data
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
getPlayer() {
|
|
||||||
return this.player
|
|
||||||
}
|
|
||||||
|
|
||||||
setPlayer(player) {
|
|
||||||
this.player = player
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 通过给定一个坐标就可以使用已经指定的参数来播放粒子
|
|
||||||
*
|
|
||||||
* @param location 坐标
|
|
||||||
*/
|
|
||||||
spawn(location: any) {
|
|
||||||
if (!this.spawner) throw new Error(`particle ${this.uuid} not set spawner can't spawn!`)
|
|
||||||
if (this.player) {
|
|
||||||
this.spawner.spawnToPlayer(this.player, location, this)
|
|
||||||
} else {
|
|
||||||
this.spawner.spawn(location, this)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 表示一条线
|
|
||||||
*
|
|
||||||
* @author Zoyn
|
|
||||||
*/
|
|
||||||
export class Line extends Particle {
|
|
||||||
private vector: any
|
|
||||||
private start: any
|
|
||||||
private end: any
|
|
||||||
/**
|
|
||||||
* 步长
|
|
||||||
*/
|
|
||||||
private step: number
|
|
||||||
/**
|
|
||||||
* 向量长度
|
|
||||||
*/
|
|
||||||
private length: number
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 构造一条线
|
|
||||||
*
|
|
||||||
* @param start 线的起点
|
|
||||||
* @param end 线的终点
|
|
||||||
*/
|
|
||||||
constructor(start: any, end: any)
|
|
||||||
/**
|
|
||||||
* 构造一条线
|
|
||||||
*
|
|
||||||
* @param start 线的起点
|
|
||||||
* @param end 线的终点
|
|
||||||
* @param step 每个粒子之间的间隔 (也即步长)
|
|
||||||
*/
|
|
||||||
constructor(start: any, end: any, step: number = 0.1) {
|
|
||||||
super()
|
|
||||||
this.start = start
|
|
||||||
this.end = end
|
|
||||||
this.step = step
|
|
||||||
// 对向量进行重置
|
|
||||||
this.resetVector()
|
|
||||||
}
|
|
||||||
|
|
||||||
show() {
|
|
||||||
for (let i = 0; i < this.length; i += this.step) {
|
|
||||||
this.spawn(this.start.clone().add(this.vector.clone().multiply(i)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取线的起始坐标
|
|
||||||
*
|
|
||||||
* @return {@link Location}
|
|
||||||
*/
|
|
||||||
getStart() {
|
|
||||||
return this.start
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 利用给定的坐标设置线的起始坐标
|
|
||||||
*
|
|
||||||
* @param start 起始坐标
|
|
||||||
* @return {@link Line}
|
|
||||||
*/
|
|
||||||
setStart(start) {
|
|
||||||
this.start = start
|
|
||||||
this.resetVector()
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取线的终点坐标
|
|
||||||
*
|
|
||||||
* @return {@link Location}
|
|
||||||
*/
|
|
||||||
getEnd() {
|
|
||||||
return this.end
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 利用给定的坐标设置线的终点坐标
|
|
||||||
*
|
|
||||||
* @param end 终点
|
|
||||||
* @return {@link Line}
|
|
||||||
*/
|
|
||||||
setEnd(end) {
|
|
||||||
this.end = end
|
|
||||||
this.resetVector()
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取每个粒子之间的间隔
|
|
||||||
*
|
|
||||||
* @return 也就是循环的步长
|
|
||||||
*/
|
|
||||||
getStep() {
|
|
||||||
return this.step
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 设置每个粒子之间的间隔
|
|
||||||
*
|
|
||||||
* @param step 间隔
|
|
||||||
* @return {@link Line}
|
|
||||||
*/
|
|
||||||
setStep(step) {
|
|
||||||
this.step = step
|
|
||||||
this.resetVector()
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 手动重设线的向量
|
|
||||||
*/
|
|
||||||
resetVector() {
|
|
||||||
this.vector = this.end.clone().subtract(this.start).toVector()
|
|
||||||
this.length = this.vector.length()
|
|
||||||
this.vector.normalize()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* 表示一个弧
|
|
||||||
*
|
|
||||||
* @author Zoyn
|
|
||||||
*/
|
|
||||||
export class Arc extends Particle {
|
|
||||||
private angle: number
|
|
||||||
private radius: number
|
|
||||||
private step: number
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 构造一个弧
|
|
||||||
*
|
|
||||||
* @param origin 弧所在的圆的圆点
|
|
||||||
* @param angle 弧所占的角度
|
|
||||||
* @param radius 弧所在的圆的半径
|
|
||||||
* @param step 每个粒子的间隔(也即步长)
|
|
||||||
*/
|
|
||||||
constructor(angle: number = 30, radius: number = 1, step: number = 1) {
|
|
||||||
super()
|
|
||||||
this.angle = angle
|
|
||||||
this.radius = radius
|
|
||||||
this.step = step
|
|
||||||
}
|
|
||||||
|
|
||||||
show(location: any) {
|
|
||||||
for (let i = 0; i < this.angle; i += this.step) {
|
|
||||||
let radians: number = Math.toRadians(i)
|
|
||||||
let x: number = this.radius * Math.cos(radians)
|
|
||||||
let z: number = this.radius * Math.sin(radians)
|
|
||||||
|
|
||||||
super.spawn(location.clone().add(x, 0, z))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
getAngle(): number {
|
|
||||||
return this.angle
|
|
||||||
}
|
|
||||||
|
|
||||||
setAngle(angle: number): Arc {
|
|
||||||
this.angle = angle
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
getRadius(): number {
|
|
||||||
return this.radius
|
|
||||||
}
|
|
||||||
|
|
||||||
setRadius(radius: number): Arc {
|
|
||||||
this.radius = radius
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
getStep(): number {
|
|
||||||
return this.step
|
|
||||||
}
|
|
||||||
|
|
||||||
setStep(step: number): Arc {
|
|
||||||
this.step = step
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* 表示一个圆
|
|
||||||
*
|
|
||||||
* @author Zoyn
|
|
||||||
*/
|
|
||||||
export class Circle extends Arc {
|
|
||||||
constructor(radius: number)
|
|
||||||
constructor(radius: number, step: number)
|
|
||||||
/**
|
|
||||||
* 构造一个圆
|
|
||||||
*
|
|
||||||
* @param origin 圆的圆点
|
|
||||||
* @param radius 圆的半径
|
|
||||||
* @param step 每个粒子的间隔(也即步长)
|
|
||||||
* @param period 特效周期(如果需要可以使用)
|
|
||||||
*/
|
|
||||||
constructor(radius: number = 1, step: number = 1) {
|
|
||||||
// Circle只需要控制这个fullArc就可以满足所有的要求
|
|
||||||
super(360, radius, step)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
|
||||||
|
|
||||||
@injectable()
|
|
||||||
export abstract class ParticleManager {
|
|
||||||
@Autowired()
|
|
||||||
private taskManager: task.TaskManager
|
|
||||||
@Autowired()
|
|
||||||
private particleSpawner: particle.ParticleSpawner
|
|
||||||
|
|
||||||
protected taskId: java.util.concurrent.atomic.AtomicInteger
|
|
||||||
protected cacheTasks = new Map<string, ParticleTask>()
|
|
||||||
protected pluginCacheTasks = new Map<string, Map<number, ParticleTask>>()
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
this.taskId = new AtomicInteger(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获得自增的任务ID
|
|
||||||
*/
|
|
||||||
public nextId() {
|
|
||||||
return this.taskId.incrementAndGet()
|
|
||||||
}
|
|
||||||
|
|
||||||
public getTaskManager() {
|
|
||||||
return this.taskManager
|
|
||||||
}
|
|
||||||
|
|
||||||
public getParticleSpawner() {
|
|
||||||
return this.particleSpawner
|
|
||||||
}
|
|
||||||
|
|
||||||
public create(particle: Particle, plugin?: plugin.Plugin) {
|
|
||||||
let uuid = particle.getUUID()
|
|
||||||
if (this.cacheTasks.has(uuid)) {
|
|
||||||
return this.cacheTasks.get(uuid)
|
|
||||||
}
|
|
||||||
let task = this.create0(plugin, particle)
|
|
||||||
this.cacheTasks.set(uuid, task)
|
|
||||||
if (plugin) {
|
|
||||||
if (!this.pluginCacheTasks.has(plugin.description.name)) {
|
|
||||||
this.pluginCacheTasks.set(plugin.description.name, new Map())
|
|
||||||
}
|
|
||||||
this.pluginCacheTasks.get(plugin.description.name).set(task.getTaskId(), task)
|
|
||||||
}
|
|
||||||
return task
|
|
||||||
}
|
|
||||||
|
|
||||||
public cancel(particle: Particle) {
|
|
||||||
let uuid = particle.getUUID()
|
|
||||||
if (this.cacheTasks.has(uuid)) {
|
|
||||||
this.cacheTasks.get(uuid).cancel()
|
|
||||||
this.cacheTasks.delete(uuid)
|
|
||||||
} else {
|
|
||||||
throw new Error(`particle ${uuid} not found!`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
disable(plugin: plugin.Plugin) {
|
|
||||||
if (this.pluginCacheTasks.has(plugin.description.name)) {
|
|
||||||
this.pluginCacheTasks
|
|
||||||
.get(plugin.description.name)
|
|
||||||
.forEach((task) => task.cancel())
|
|
||||||
this.pluginCacheTasks.delete(plugin.description.name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
protected create0(owner: plugin.Plugin, particle: Particle): ParticleTask {
|
|
||||||
particle.setSpawner(this.getParticleSpawner())
|
|
||||||
return new ParticleTask(owner, particle, this)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ParticleTask {
|
|
||||||
private particle: Particle
|
|
||||||
private isAsync: boolean = false
|
|
||||||
private interval: number = 0
|
|
||||||
private _location: any
|
|
||||||
private _follow: any
|
|
||||||
|
|
||||||
private owner: plugin.Plugin
|
|
||||||
private taskId: number
|
|
||||||
private task: task.Task
|
|
||||||
private taskManager: task.TaskManager
|
|
||||||
protected particleManager: ParticleManager
|
|
||||||
|
|
||||||
constructor(owner: plugin.Plugin, particle: Particle, particleManager: ParticleManager) {
|
|
||||||
this.owner = owner
|
|
||||||
this.taskId = particleManager.nextId()
|
|
||||||
this.particle = particle
|
|
||||||
this.taskManager = particleManager.getTaskManager()
|
|
||||||
this.particleManager = particleManager
|
|
||||||
}
|
|
||||||
|
|
||||||
getOwner() {
|
|
||||||
return this.task.getOwner()
|
|
||||||
}
|
|
||||||
|
|
||||||
getTaskId() {
|
|
||||||
return this.taskId
|
|
||||||
}
|
|
||||||
|
|
||||||
getParticle() {
|
|
||||||
return this.particle
|
|
||||||
}
|
|
||||||
|
|
||||||
async(isAsync: boolean = true) {
|
|
||||||
this.isAsync = isAsync
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
timer(tick: number) {
|
|
||||||
this.interval = tick
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
follow(entity: { getLocation: () => any }) {
|
|
||||||
this._follow = entity
|
|
||||||
this._location = undefined
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
location(location: any) {
|
|
||||||
this._location = location
|
|
||||||
this._follow = undefined
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
submit() {
|
|
||||||
this.cancel()
|
|
||||||
if (this._follow && !this.interval) throw new Error(`enable follow entity but interval is ${this.interval}!`)
|
|
||||||
this.taskManager.create(() => {
|
|
||||||
this.task = this.taskManager
|
|
||||||
.create(() => {
|
|
||||||
try {
|
|
||||||
if (this._follow) {
|
|
||||||
if (!this._follow.isOnline()) return this.cancel()
|
|
||||||
this.particle.show(this._follow.getLocation().clone().add(0, 1, 0))
|
|
||||||
} else if (this._location) {
|
|
||||||
this.particle.show(this._location)
|
|
||||||
} else {
|
|
||||||
console.warn(`ParticleTask ${this.taskId} particle ${this.particle.getUUID()} cancel because entity and location both undefined!`)
|
|
||||||
this.task.cancel()
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
console.error(`§6插件 §a${this.owner.description.name} §c播放粒子发送异常 §4粒子播放任务已终止!`)
|
|
||||||
console.ex(error)
|
|
||||||
this.cancel()
|
|
||||||
}
|
|
||||||
}, this.owner)
|
|
||||||
.async(this.isAsync)
|
|
||||||
.timer(this.interval)
|
|
||||||
.submit()
|
|
||||||
}, this.owner).later(2).submit()
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
cancel() {
|
|
||||||
if (this.task != null) {
|
|
||||||
this.task.cancel()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
import { injectable } from '@ccms/container'
|
|
||||||
|
|
||||||
export namespace plugin {
|
|
||||||
/**
|
|
||||||
* MiaoScript Plugin
|
|
||||||
*/
|
|
||||||
export const Plugin = Symbol("Plugin")
|
|
||||||
/**
|
|
||||||
* MiaoScript Plugin Folder
|
|
||||||
*/
|
|
||||||
export const PluginFolder = Symbol("PluginFolder")
|
|
||||||
/**
|
|
||||||
* Runtime Plugin Instance
|
|
||||||
*/
|
|
||||||
export const PluginInstance = Symbol("PluginInstance")
|
|
||||||
/**
|
|
||||||
* MiaoScript Plugin Manager Interface
|
|
||||||
*/
|
|
||||||
@injectable()
|
|
||||||
export abstract class PluginManager {
|
|
||||||
abstract scan(folder: string): void
|
|
||||||
abstract loadFromFile(file: string, ext?: any): Plugin
|
|
||||||
abstract require(loadMetadata: PluginLoadMetadata): PluginMetadata
|
|
||||||
abstract build(metadata: PluginMetadata): Plugin
|
|
||||||
abstract rebuild(plugin: plugin.Plugin): void
|
|
||||||
abstract load(plugin: plugin.Plugin): void
|
|
||||||
abstract enable(plugin: plugin.Plugin): void
|
|
||||||
abstract disable(plugin: plugin.Plugin): void
|
|
||||||
abstract reload(plugin: plugin.Plugin): void
|
|
||||||
abstract has(name: string): boolean
|
|
||||||
abstract get(name: string): plugin.Plugin
|
|
||||||
abstract getPlugin(name: string): plugin.Plugin
|
|
||||||
abstract getPlugins(): Map<string, plugin.Plugin>
|
|
||||||
abstract buildPlugins(): void
|
|
||||||
abstract rebuildPlugins(): void
|
|
||||||
abstract loadPlugins(): void
|
|
||||||
abstract enablePlugins(): void
|
|
||||||
abstract disablePlugins(): void
|
|
||||||
}
|
|
||||||
export const PluginScanner = Symbol("PluginScanner")
|
|
||||||
/**
|
|
||||||
* 插件加载元信息
|
|
||||||
*/
|
|
||||||
export interface PluginLoadMetadata {
|
|
||||||
/**
|
|
||||||
* 插件加载类型
|
|
||||||
*/
|
|
||||||
type: string
|
|
||||||
/**
|
|
||||||
* 插件文件(java.io.File)
|
|
||||||
*/
|
|
||||||
file?: any
|
|
||||||
/**
|
|
||||||
* 插件规范路径 canonicalPath
|
|
||||||
*/
|
|
||||||
path?: string
|
|
||||||
/**
|
|
||||||
* 插件实例
|
|
||||||
*/
|
|
||||||
instance?: any
|
|
||||||
/**
|
|
||||||
* 插件元信息
|
|
||||||
*/
|
|
||||||
metadata?: PluginMetadata
|
|
||||||
/**
|
|
||||||
* 插件扫描器
|
|
||||||
*/
|
|
||||||
scanner: PluginScanner
|
|
||||||
/**
|
|
||||||
* 插件加载器
|
|
||||||
*/
|
|
||||||
loader?: PluginLoader
|
|
||||||
/**
|
|
||||||
* 是否已加载
|
|
||||||
*/
|
|
||||||
loaded?: boolean
|
|
||||||
[key: string]: any
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* 插件扫描器
|
|
||||||
*/
|
|
||||||
export interface PluginScanner {
|
|
||||||
/**
|
|
||||||
* 扫描器类型
|
|
||||||
*/
|
|
||||||
type: string
|
|
||||||
/**
|
|
||||||
* 扫描插件目录 返回插件加载元信息列表
|
|
||||||
* @param target 扫描目标
|
|
||||||
*/
|
|
||||||
scan(target: any): PluginLoadMetadata[]
|
|
||||||
/**
|
|
||||||
* 读取插件 返回插件加载元信息
|
|
||||||
* @param target
|
|
||||||
*/
|
|
||||||
read(target: any): PluginLoadMetadata
|
|
||||||
/**
|
|
||||||
* 加载扫描到的目标
|
|
||||||
* @param target 加载目标
|
|
||||||
*/
|
|
||||||
load(target: PluginLoadMetadata): PluginLoadMetadata
|
|
||||||
}
|
|
||||||
export const PluginLoader = Symbol("PluginLoader")
|
|
||||||
/**
|
|
||||||
* 插件加载器
|
|
||||||
*/
|
|
||||||
export interface PluginLoader {
|
|
||||||
/**
|
|
||||||
* 加载器类型
|
|
||||||
*/
|
|
||||||
type: string
|
|
||||||
/**
|
|
||||||
* 加载插件 获取元数据
|
|
||||||
* @param target 加载目标
|
|
||||||
* @param result 扫描器加载的结果
|
|
||||||
*/
|
|
||||||
require(loadMetadata: PluginLoadMetadata): PluginLoadMetadata
|
|
||||||
/**
|
|
||||||
* 构建插件
|
|
||||||
* @param metadata 插件元信息
|
|
||||||
*/
|
|
||||||
build(metadata: PluginMetadata): Plugin
|
|
||||||
/**
|
|
||||||
* Load 阶段
|
|
||||||
* @param plugin 插件
|
|
||||||
*/
|
|
||||||
load?(plugin: Plugin): void
|
|
||||||
/**
|
|
||||||
* Enable 阶段
|
|
||||||
* @param plugin 插件
|
|
||||||
*/
|
|
||||||
enable?(plugin: Plugin): void
|
|
||||||
/**
|
|
||||||
* Disable 阶段
|
|
||||||
* @param plugin 插件
|
|
||||||
*/
|
|
||||||
disable?(plugin: Plugin): void
|
|
||||||
}
|
|
||||||
export interface Plugin {
|
|
||||||
description: PluginMetadata
|
|
||||||
logger: Console
|
|
||||||
load(): void
|
|
||||||
enable(): void
|
|
||||||
disable(): void
|
|
||||||
}
|
|
||||||
export interface BaseMetadata {
|
|
||||||
/**
|
|
||||||
* 名称 为空则为对象名称
|
|
||||||
*/
|
|
||||||
name?: string
|
|
||||||
/**
|
|
||||||
* 支持的服务器列表 为空则代表所有
|
|
||||||
*/
|
|
||||||
servers?: string[]
|
|
||||||
}
|
|
||||||
export interface PluginMetadata extends BaseMetadata {
|
|
||||||
/**
|
|
||||||
* 插件名称 不填默认为类名
|
|
||||||
*/
|
|
||||||
name: string
|
|
||||||
/**
|
|
||||||
* 插件中文名称
|
|
||||||
*/
|
|
||||||
cname?: string
|
|
||||||
/**
|
|
||||||
* 付费插件ID
|
|
||||||
*/
|
|
||||||
pid?: number
|
|
||||||
/**
|
|
||||||
* 付费插件等级 付费插件自动注入
|
|
||||||
*/
|
|
||||||
level?: number
|
|
||||||
/**
|
|
||||||
* 前缀
|
|
||||||
*/
|
|
||||||
prefix?: string
|
|
||||||
/**
|
|
||||||
* 插件版本 不填默认为 1.0.0
|
|
||||||
*/
|
|
||||||
version?: string
|
|
||||||
/**
|
|
||||||
* 插件作者 不填默认为 Unknow
|
|
||||||
*/
|
|
||||||
author?: string | string[]
|
|
||||||
/**
|
|
||||||
* 脚本依赖
|
|
||||||
*/
|
|
||||||
depends?: string[]
|
|
||||||
/**
|
|
||||||
* 插件依赖
|
|
||||||
*/
|
|
||||||
nativeDepends?: string[]
|
|
||||||
/**
|
|
||||||
* 插件源文件 必须指定为 __filename
|
|
||||||
*/
|
|
||||||
source: string
|
|
||||||
/**
|
|
||||||
* 插件类型 默认为 ioc 执行 MiaoScript 加载逻辑
|
|
||||||
*/
|
|
||||||
type?: string
|
|
||||||
/**
|
|
||||||
* 插件加载信息
|
|
||||||
*/
|
|
||||||
loadMetadata?: PluginLoadMetadata
|
|
||||||
/**
|
|
||||||
* 插件本体
|
|
||||||
*/
|
|
||||||
target?: any
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,161 +0,0 @@
|
|||||||
import { provideSingleton, Autowired, optional } from '@ccms/container'
|
|
||||||
import { channel } from './channel'
|
|
||||||
|
|
||||||
export namespace proxy {
|
|
||||||
const ByteArrayOutputStream = Java.type('java.io.ByteArrayOutputStream')
|
|
||||||
const DataOutputStream = Java.type('java.io.DataOutputStream')
|
|
||||||
namespace bungeecord {
|
|
||||||
const CHANNEL_NAME = "BungeeCord"
|
|
||||||
export class SubChannelBuilder {
|
|
||||||
private channel: channel.Channel
|
|
||||||
private player: any
|
|
||||||
private params: string[]
|
|
||||||
constructor(channel: channel.Channel, player: any) {
|
|
||||||
this.channel = channel
|
|
||||||
this.player = player
|
|
||||||
this.params = []
|
|
||||||
}
|
|
||||||
connect(server: string) {
|
|
||||||
this.params.push("Connect")
|
|
||||||
this.params.push(server)
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
connectOther(player: string, server: string) {
|
|
||||||
this.params.push("ConnectOther")
|
|
||||||
this.params.push(player)
|
|
||||||
this.params.push(server)
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
ip() {
|
|
||||||
this.params.push("IP")
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
ipOther(player: string) {
|
|
||||||
this.params.push("IPOther")
|
|
||||||
this.params.push(player)
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
playerCount(server: string | "ALL") {
|
|
||||||
this.params.push("PlayerCount")
|
|
||||||
this.params.push(server)
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Get a list of players connected on a certain server, or on ALL the servers.
|
|
||||||
* @param server count server
|
|
||||||
* Response:
|
|
||||||
* String server = in.readUTF(); // The name of the server you got the player list of, as given in args.
|
|
||||||
* String[] playerList = in.readUTF().split(", ");
|
|
||||||
*/
|
|
||||||
playerList(server: string | "ALL") {
|
|
||||||
this.params.push("PlayerList")
|
|
||||||
this.params.push(server)
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Get a list of server name strings, as defined in BungeeCord's config.yml
|
|
||||||
* Response:
|
|
||||||
* String[] serverList = in.readUTF().split(", ");
|
|
||||||
*/
|
|
||||||
getServers() {
|
|
||||||
this.params.push("GetServers")
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Get this server's name, as defined in BungeeCord's config.yml
|
|
||||||
*/
|
|
||||||
getServer() {
|
|
||||||
this.params.push("GetServer")
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
broadcast(message: string) {
|
|
||||||
this.message("ALL", message)
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Send a message (as in, a chat message) to the specified player.
|
|
||||||
* @param player who reciver message
|
|
||||||
* @param message message content
|
|
||||||
*/
|
|
||||||
message(player: string | "ALL", message: string) {
|
|
||||||
this.params.push("Message")
|
|
||||||
this.params.push(player)
|
|
||||||
this.params.push(message)
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Send a raw message (as in, a chat message) to the specified player. The advantage of this method over Message is that you can include click events and hover events.
|
|
||||||
* @param player who reciver message
|
|
||||||
* @param message message content
|
|
||||||
*/
|
|
||||||
messageRaw(player: string | "ALL", json: string) {
|
|
||||||
this.params.push("MessageRaw")
|
|
||||||
this.params.push(player)
|
|
||||||
this.params.push(json)
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
forwardAll(channel: string, data: any) {
|
|
||||||
return this.forward("ALL", channel, data)
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
|
||||||
* Remember, the sending and receiving server(s) need to have a player online.
|
|
||||||
* @param server reciver
|
|
||||||
* @param channel channelName
|
|
||||||
* @param data data
|
|
||||||
*/
|
|
||||||
forward(server: string | "ALL", channel: string, data: any) {
|
|
||||||
this.params.push("Forward")
|
|
||||||
this.params.push(server)
|
|
||||||
this.params.push(channel)
|
|
||||||
this.params.push(typeof data === "string" ? data : JSON.stringify(data))
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Send a custom plugin message to said server. This is one of the most useful channels ever.
|
|
||||||
* Remember, the sending and receiving server(s) need to have a player online.
|
|
||||||
* @param server reciver
|
|
||||||
* @param channel channelName
|
|
||||||
* @param data data
|
|
||||||
*/
|
|
||||||
forwardToPlayer(server: string | "ALL", channel: string, data: any) {
|
|
||||||
this.params.push("Forward")
|
|
||||||
this.params.push(server)
|
|
||||||
this.params.push(channel)
|
|
||||||
this.params.push(typeof data === "string" ? data : JSON.stringify(data))
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
generic(...args: string[]) {
|
|
||||||
args && this.params.concat(...args)
|
|
||||||
return this.finalSend()
|
|
||||||
}
|
|
||||||
private send(...middlewares: ((out: java.io.DataOutputStream) => void)[]) {
|
|
||||||
let byteArray = new ByteArrayOutputStream()
|
|
||||||
let out = new DataOutputStream(byteArray)
|
|
||||||
this.params.forEach(utf => out.writeUTF(utf))
|
|
||||||
for (let middleware of middlewares) {
|
|
||||||
middleware(out)
|
|
||||||
}
|
|
||||||
return this.channel.send(this.player, CHANNEL_NAME, byteArray.toByteArray())
|
|
||||||
}
|
|
||||||
private finalSend() {
|
|
||||||
return {
|
|
||||||
send: this.send.bind(this)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@provideSingleton(BungeeCord)
|
|
||||||
export class BungeeCord {
|
|
||||||
@optional()
|
|
||||||
@Autowired()
|
|
||||||
private channel: channel.Channel
|
|
||||||
/**
|
|
||||||
* 获得代理
|
|
||||||
* @param player 玩家
|
|
||||||
*/
|
|
||||||
for(player: any): bungeecord.SubChannelBuilder {
|
|
||||||
return new bungeecord.SubChannelBuilder(this.channel, player)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,229 +0,0 @@
|
|||||||
import * as reflect from '@ccms/common/dist/reflect'
|
|
||||||
import { injectable, Autowired, ContainerInstance, Container, postConstruct } from '@ccms/container'
|
|
||||||
|
|
||||||
import { constants } from './constants'
|
|
||||||
|
|
||||||
export namespace server {
|
|
||||||
/**
|
|
||||||
* Runtime ServerType
|
|
||||||
*/
|
|
||||||
export const ServerType = Symbol("ServerType")
|
|
||||||
/**
|
|
||||||
* Runtime Console
|
|
||||||
*/
|
|
||||||
export const Console = Symbol("Console")
|
|
||||||
/**
|
|
||||||
* Runtime Server Instance
|
|
||||||
*/
|
|
||||||
export const ServerInstance = Symbol("ServerInstance")
|
|
||||||
export interface NativePlugin {
|
|
||||||
name: string
|
|
||||||
version: string
|
|
||||||
authors?: string | string[]
|
|
||||||
enable: boolean
|
|
||||||
depends?: string[]
|
|
||||||
softDepends?: string[]
|
|
||||||
/**
|
|
||||||
* 插件本体
|
|
||||||
*/
|
|
||||||
origin: any
|
|
||||||
[key: string]: any
|
|
||||||
}
|
|
||||||
|
|
||||||
@injectable()
|
|
||||||
export abstract class NativePluginManager {
|
|
||||||
list(): NativePlugin[] {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
has(name: string): boolean {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
get(name: string): NativePlugin {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
enable(name: string): NativePlugin {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
disable(name: string): NativePlugin {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
reload(name: string): NativePlugin {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
delete(name: string): boolean {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* MiaoScript Server
|
|
||||||
*/
|
|
||||||
@injectable()
|
|
||||||
export abstract class Server {
|
|
||||||
getVersion(): string {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getPlayer(name: string): any {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getOnlinePlayers(): any[] {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getConsoleSender(): any {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getService(service: string): any {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
broadcast(message: string, permission: string) {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
broadcastMessage(message: string) {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
dispatchCommand(sender: string | any, command: string): boolean {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
dispatchConsoleCommand(command: string): boolean {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getPluginsFolder(): string {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getDedicatedServer?(): any {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getNettyPipeline(): any {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getRootLogger(): any {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@injectable()
|
|
||||||
export class ServerChecker {
|
|
||||||
@Autowired(ServerType)
|
|
||||||
private serverType: string
|
|
||||||
|
|
||||||
check(servers: string[]) {
|
|
||||||
// Not set servers -> allow
|
|
||||||
if (!servers || !servers.length) return true
|
|
||||||
// include !type -> deny
|
|
||||||
let denyServers = servers.filter(svr => svr.startsWith("!"))
|
|
||||||
if (denyServers.length !== 0) {
|
|
||||||
return !denyServers.includes(`!${this.serverType}`)
|
|
||||||
} else {
|
|
||||||
// only include -> allow
|
|
||||||
return servers.includes(this.serverType)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@injectable()
|
|
||||||
export class NativePluginChecker {
|
|
||||||
@Autowired(NativePluginManager)
|
|
||||||
private nativePluginManager: NativePluginManager
|
|
||||||
|
|
||||||
check(plugins: string[]) {
|
|
||||||
// Not set plugins -> allow
|
|
||||||
if (!plugins || !plugins.length) return true
|
|
||||||
for (const plugin of plugins) {
|
|
||||||
if (!this.nativePluginManager.has(plugin)) { return false }
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@injectable()
|
|
||||||
export abstract class ReflectServer extends server.Server {
|
|
||||||
@Autowired(ContainerInstance)
|
|
||||||
private container: Container
|
|
||||||
|
|
||||||
protected pipeline: any
|
|
||||||
protected rootLogger: any
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
super()
|
|
||||||
}
|
|
||||||
|
|
||||||
@postConstruct()
|
|
||||||
protected reflect() {
|
|
||||||
try {
|
|
||||||
let consoleServer = this.getDedicatedServer()
|
|
||||||
this.reflectPipeline(consoleServer)
|
|
||||||
this.reflectRootLogger(consoleServer)
|
|
||||||
} catch (error: any) {
|
|
||||||
console.error('Error When Reflect MinecraftServer!', error)
|
|
||||||
console.ex(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
protected reflectPipeline(consoleServer: any) {
|
|
||||||
let connection: any
|
|
||||||
let promise: any
|
|
||||||
for (const method of constants.Reflect.Method.getServerConnection) {
|
|
||||||
try {
|
|
||||||
connection = reflect.on(consoleServer).call(method).get()
|
|
||||||
if (connection.class.name.indexOf('ServerConnection') !== -1
|
|
||||||
|| connection.class.name.indexOf('NetworkSystem') !== -1) { break }
|
|
||||||
connection = undefined
|
|
||||||
} catch (error: any) {
|
|
||||||
if (global.debug) {
|
|
||||||
console.ex(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
|
||||||
for (const field of constants.Reflect.Field.listeningChannels) {
|
|
||||||
try {
|
|
||||||
promise = reflect.on(connection).get(field).get().get(0)
|
|
||||||
if (promise.class.name.indexOf('Promise') !== -1) { break }
|
|
||||||
promise = undefined
|
|
||||||
} catch (error: any) {
|
|
||||||
if (global.debug) {
|
|
||||||
console.ex(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
|
||||||
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
|
||||||
this.container.bind(constants.ServiceIdentifier.NettyPipeline).toConstantValue(this.pipeline)
|
|
||||||
}
|
|
||||||
protected reflectRootLogger(consoleServer: any) {
|
|
||||||
try {
|
|
||||||
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get()
|
|
||||||
} catch (error: any) {
|
|
||||||
if (global.debug) {
|
|
||||||
console.ex(error)
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
this.rootLogger = reflect.on(consoleServer).get(0).get()
|
|
||||||
} catch (error: any) {
|
|
||||||
if (global.debug) {
|
|
||||||
console.ex(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (this.rootLogger.class.name.indexOf('slf4j') !== -1) {
|
|
||||||
try {
|
|
||||||
let LogManager = Java.type('org.apache.logging.log4j.LogManager')
|
|
||||||
this.rootLogger = LogManager.getLogger('ROOT')
|
|
||||||
} catch (error: any) {
|
|
||||||
if (global.debug) {
|
|
||||||
console.ex(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (this.rootLogger && this.rootLogger.class.name.indexOf('Logger') === -1) {
|
|
||||||
console.error('Error Logger Class: ' + this.rootLogger.class.name)
|
|
||||||
this.rootLogger = undefined
|
|
||||||
}
|
|
||||||
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
|
|
||||||
// get root logger
|
|
||||||
for (let index = 0; index < 5 && this.rootLogger.parent; index++) {
|
|
||||||
this.rootLogger = this.rootLogger.parent
|
|
||||||
}
|
|
||||||
this.container.bind(constants.ServiceIdentifier.RootLogger).toConstantValue(this.rootLogger)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,112 +1,34 @@
|
|||||||
import { EventEmitter } from 'events'
|
|
||||||
import { injectable } from '@ccms/container'
|
|
||||||
|
|
||||||
import { plugin } from './index'
|
|
||||||
|
|
||||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
|
||||||
|
|
||||||
export namespace task {
|
export namespace task {
|
||||||
@injectable()
|
export const TaskManager = Symbol('TaskManager')
|
||||||
export abstract class TaskManager {
|
export interface TaskManager {
|
||||||
protected taskId: java.util.concurrent.atomic.AtomicInteger
|
|
||||||
protected cacheTasks = new Map<number, task.Task>()
|
|
||||||
protected pluginCacheTasks = new Map<string, Map<number, task.Task>>()
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
this.taskId = new AtomicInteger(0)
|
|
||||||
process.on('core.disable', () => { this.disable() })
|
|
||||||
process.on('task.finish', (task: task.Task) => {
|
|
||||||
let taskId = task.getTaskId()
|
|
||||||
this.cacheTasks.delete(taskId)
|
|
||||||
let ownerName = task.getOwner()?.description.name
|
|
||||||
if (ownerName && this.pluginCacheTasks.has(ownerName)) {
|
|
||||||
this.pluginCacheTasks.get(ownerName)?.delete(taskId)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建任务
|
* 创建任务
|
||||||
* @param func 任务内容
|
* @param func 任务内容
|
||||||
*/
|
*/
|
||||||
create(func: Function, plugin?: plugin.Plugin): task.Task {
|
create(func: Function): task.Task;
|
||||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !') };
|
|
||||||
let task = this.create0(plugin, func, this.nextId())
|
|
||||||
this.cacheTasks.set(task.getTaskId(), task)
|
|
||||||
if (plugin) { return this.pluginCreate(plugin, task) }
|
|
||||||
return task
|
|
||||||
}
|
|
||||||
cancel(taskId: number) {
|
|
||||||
if (!this.cacheTasks.has(taskId)) { throw new Error(`Task ${taskId} not found!`) }
|
|
||||||
this.cacheTasks.get(taskId).cancel()
|
|
||||||
}
|
|
||||||
/**
|
/**
|
||||||
* 在主线程执行代码
|
* 在主线程执行代码
|
||||||
* @param func 执行内容
|
* @param func 执行内容
|
||||||
*/
|
*/
|
||||||
abstract callSyncMethod(func: Function): any
|
callSyncMethod(func: Function): any;
|
||||||
/**
|
/**
|
||||||
* 关闭任务管理器
|
* 关闭任务管理器
|
||||||
*/
|
*/
|
||||||
disable(plugin?: plugin.Plugin) {
|
disable();
|
||||||
if (plugin) { return this.pluginDisable(plugin) }
|
|
||||||
this.disable0()
|
|
||||||
}
|
|
||||||
|
|
||||||
protected pluginCreate(plugin: plugin.Plugin, task: task.Task) {
|
|
||||||
if (!this.pluginCacheTasks.has(plugin.description.name)) {
|
|
||||||
this.pluginCacheTasks.set(plugin.description.name, new Map())
|
|
||||||
}
|
|
||||||
this.pluginCacheTasks.get(plugin.description.name).set(task.getTaskId(), task)
|
|
||||||
return task
|
|
||||||
}
|
|
||||||
|
|
||||||
protected pluginDisable(plugin: plugin.Plugin) {
|
|
||||||
if (this.pluginCacheTasks.has(plugin.description.name)) {
|
|
||||||
this.pluginCacheTasks.get(plugin.description.name).forEach((task) => task.cancel())
|
|
||||||
this.pluginCacheTasks.delete(plugin.description.name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获得自增的任务ID
|
|
||||||
*/
|
|
||||||
protected nextId() {
|
|
||||||
return this.taskId.incrementAndGet()
|
|
||||||
}
|
|
||||||
protected abstract create0(owner: plugin.Plugin, func: Function, id: number): task.Task
|
|
||||||
protected abstract disable0()
|
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 任务抽象
|
* 任务抽象
|
||||||
*/
|
*/
|
||||||
export abstract class Task extends EventEmitter implements Cancelable {
|
export abstract class Task {
|
||||||
protected func: Function
|
protected plugin: any;
|
||||||
|
protected func: Function;
|
||||||
protected isAsync: boolean = false;
|
protected isAsync: boolean = false;
|
||||||
protected laterTime: number = 0;
|
protected laterTime: number = 0;
|
||||||
protected interval: number = 0;
|
protected interval: number = 0;
|
||||||
protected owner: plugin.Plugin
|
|
||||||
protected taskId: number
|
|
||||||
protected innerTask: any
|
|
||||||
|
|
||||||
private cancelled: boolean = false
|
constructor(plugin: any, func: Function) {
|
||||||
|
this.plugin = plugin;
|
||||||
constructor(owner: plugin.Plugin, func: Function, id: number) {
|
this.func = func;
|
||||||
super()
|
|
||||||
this.owner = owner
|
|
||||||
this.func = func
|
|
||||||
this.taskId = id
|
|
||||||
this.on('finish', () => {
|
|
||||||
process.emit('task.finish', this)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
getOwner() {
|
|
||||||
return this.owner
|
|
||||||
}
|
|
||||||
|
|
||||||
getTaskId() {
|
|
||||||
return this.taskId
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -114,8 +36,8 @@ export namespace task {
|
|||||||
* @param isAsync 是否异步
|
* @param isAsync 是否异步
|
||||||
*/
|
*/
|
||||||
async(isAsync: boolean = true): task.Task {
|
async(isAsync: boolean = true): task.Task {
|
||||||
this.isAsync = isAsync
|
this.isAsync = isAsync;
|
||||||
return this
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -123,8 +45,8 @@ export namespace task {
|
|||||||
* @param tick 延时 Tick
|
* @param tick 延时 Tick
|
||||||
*/
|
*/
|
||||||
later(tick: number): task.Task {
|
later(tick: number): task.Task {
|
||||||
this.laterTime = tick
|
this.laterTime = tick;
|
||||||
return this
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -132,69 +54,28 @@ export namespace task {
|
|||||||
* @param tick 循环时间 Tick
|
* @param tick 循环时间 Tick
|
||||||
*/
|
*/
|
||||||
timer(tick: number): task.Task {
|
timer(tick: number): task.Task {
|
||||||
this.interval = tick
|
this.interval = tick;
|
||||||
return this
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
protected run(): void {
|
||||||
* 取消任务
|
|
||||||
*/
|
|
||||||
cancel(): boolean {
|
|
||||||
let result = this.cancel0()
|
|
||||||
this.finish()
|
|
||||||
this.cancelled = true
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
protected run(...args: any[]): void {
|
|
||||||
try {
|
try {
|
||||||
this.emit('before', this)
|
this.func();
|
||||||
if (this.cancelled) { return }
|
} catch (ex) {
|
||||||
this.func(...args)
|
console.console('§4插件执行任务时发生错误', ex)
|
||||||
this.emit('after', this)
|
console.ex(ex);
|
||||||
} catch (error: any) {
|
|
||||||
try {
|
|
||||||
this.emit('error', error)
|
|
||||||
} catch (ignore) {
|
|
||||||
console.console('§4插件执行任务时发生错误', error)
|
|
||||||
console.ex(error)
|
|
||||||
this.cancel()
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
this.emit('finally', this)
|
|
||||||
if (!this.interval && !this.cancelled) { this.finish() }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected finish() {
|
|
||||||
this.emit('finish', this)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 提交任务
|
* 提交任务
|
||||||
* @param args 任务参数
|
|
||||||
*/
|
*/
|
||||||
submit(...args: any[]): task.Task {
|
abstract submit(): Cancelable;
|
||||||
this.innerTask = this.submit0(...args)
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 提交任务
|
|
||||||
* @param args 任务参数
|
|
||||||
*/
|
|
||||||
protected abstract submit0(...args: any[]): Cancelable
|
|
||||||
/**
|
|
||||||
* 取消任务
|
|
||||||
*/
|
|
||||||
protected cancel0(): boolean {
|
|
||||||
return this.innerTask?.cancel()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 返可取消的对象
|
* 返可取消的对象
|
||||||
*/
|
*/
|
||||||
export interface Cancelable {
|
export interface Cancelable {
|
||||||
cancel(): boolean
|
cancel(): boolean;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/bukkit",
|
"name": "@ccms/bukkit",
|
||||||
"version": "0.28.0-beta.11",
|
"version": "0.6.1",
|
||||||
"description": "MiaoScript bukkit package",
|
"description": "MiaoScript bukkit package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -12,23 +12,20 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"files": [
|
|
||||||
"dist/**/*.js",
|
|
||||||
"dist/**/*.ts",
|
|
||||||
"dist/**/*.map"
|
|
||||||
],
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "pnpm clean && tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@javatypes/spigot-api": "^0.0.3"
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "workspace:*",
|
"@ccms/api": "^0.6.1",
|
||||||
"@ccms/common": "workspace:*",
|
"@ccms/common": "^0.6.1",
|
||||||
"@ccms/container": "workspace:*"
|
"@ccms/container": "^0.6.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,54 +1,28 @@
|
|||||||
import { channel, plugin } from '@ccms/api'
|
import { channel, plugin } from '@ccms/api'
|
||||||
import { inject, provideSingleton } from '@ccms/container'
|
import { inject, provideSingleton } from '@ccms/container'
|
||||||
|
|
||||||
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
const Bukkit = org.bukkit.Bukkit
|
||||||
const PluginMessageListener = Java.type("org.bukkit.plugin.messaging.PluginMessageListener")
|
const PluginMessageListener = Java.type("org.bukkit.plugin.messaging.PluginMessageListener")
|
||||||
const Messenger = Bukkit.getMessenger()
|
const Messenger = Bukkit.getMessenger()
|
||||||
|
|
||||||
@provideSingleton(channel.Channel)
|
@provideSingleton(channel.Channel)
|
||||||
export class BukkitChannel extends channel.Channel {
|
export class BukkitChannel extends channel.Channel {
|
||||||
@inject(plugin.PluginInstance)
|
@inject(plugin.PluginInstance)
|
||||||
private pluginInstance: any
|
private pluginInstance: any;
|
||||||
private cacheChannel = new Map<string, any[]>()
|
|
||||||
/**
|
|
||||||
* 给玩家发送通道消息
|
|
||||||
* @param player 接受消息的玩家
|
|
||||||
* @param channel 通道
|
|
||||||
* @param data 数据
|
|
||||||
*/
|
|
||||||
send(player: any, channel: string, data: number[]) {
|
|
||||||
player.sendPluginMessage(this.pluginInstance, channel, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
send(player: any, channel: string, data: any) {
|
||||||
* 注册通道监听器
|
player.sendPluginMessage(this.pluginInstance, channel, data);
|
||||||
* @param channel 通道
|
}
|
||||||
* @param listener 监听器
|
|
||||||
*/
|
|
||||||
register(channel: string, listener: channel.ChannelListener) {
|
register(channel: string, listener: channel.ChannelListener) {
|
||||||
if (!this.cacheChannel.has(channel)) this.cacheChannel.set(channel, [])
|
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, new PluginMessageListener({
|
||||||
this.cacheChannel.get(channel).push(listener)
|
|
||||||
let pluginMessageListener = new PluginMessageListener({
|
|
||||||
onPluginMessageReceived: (/**String */ channel, /**Player */ player, /**byte[] */data) => {
|
onPluginMessageReceived: (/**String */ channel, /**Player */ player, /**byte[] */data) => {
|
||||||
try {
|
listener(data, { channel, player, data })
|
||||||
listener(data, { channel, player, data })
|
|
||||||
} catch (error: any) {
|
|
||||||
console.ex(error)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
}));
|
||||||
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, pluginMessageListener)
|
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel);
|
||||||
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel)
|
|
||||||
return pluginMessageListener
|
|
||||||
}
|
}
|
||||||
unregister(channel: string, listener: any) {
|
unregister(channel: string, listener: any) {
|
||||||
if (!this.cacheChannel.has(channel)) return
|
Messenger.unregisterIncomingPluginChannel(this.pluginInstance, channel)
|
||||||
let cacheListener = this.cacheChannel.get(channel)
|
Messenger.unregisterOutgoingPluginChannel(this.pluginInstance, channel)
|
||||||
cacheListener = cacheListener.filter(l => l != listener)
|
|
||||||
Messenger.unregisterIncomingPluginChannel(this.pluginInstance, channel, listener)
|
|
||||||
if (cacheListener.length == 0) {
|
|
||||||
this.cacheChannel.delete(channel)
|
|
||||||
Messenger.unregisterOutgoingPluginChannel(this.pluginInstance, channel)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
import { chat } from '@ccms/api'
|
|
||||||
import { provideSingleton } from '@ccms/container'
|
|
||||||
import bukkitChat from './internal/chat'
|
|
||||||
|
|
||||||
@provideSingleton(chat.Chat)
|
|
||||||
export class BukkitChat extends chat.Chat {
|
|
||||||
get handle(): any {
|
|
||||||
return bukkitChat
|
|
||||||
}
|
|
||||||
sendJson(sender: any, json: string | object, type = 0) {
|
|
||||||
bukkitChat.send(sender, typeof json === "string" ? json : JSON.stringify(json), type)
|
|
||||||
}
|
|
||||||
sendMessage(sender: any, message: string) {
|
|
||||||
this.sendJson(sender, { text: message }, 0)
|
|
||||||
}
|
|
||||||
sendActionBar(sender: any, message: string) {
|
|
||||||
this.sendJson(sender, { text: message }, 2)
|
|
||||||
}
|
|
||||||
sendTitle(sender: any, title: string, subtitle: string = '', fadeIn: number = 20, time: number = 100, fadeOut: number = 20) {
|
|
||||||
try {
|
|
||||||
sender.sendTitle(title, subtitle, fadeIn, time, fadeOut)
|
|
||||||
} catch (error: any) {
|
|
||||||
sender.sendTitle(title, subtitle)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,53 +1,47 @@
|
|||||||
import '@ccms/nashorn'
|
import '@ccms/nashorn'
|
||||||
|
|
||||||
import { command, plugin } from '@ccms/api'
|
import { command, plugin } from '@ccms/api'
|
||||||
import { provideSingleton, postConstruct, inject } from '@ccms/container'
|
|
||||||
import * as reflect from '@ccms/common/dist/reflect'
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
import { provideSingleton, postConstruct, inject } from '@ccms/container'
|
||||||
|
|
||||||
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
let Bukkit = org.bukkit.Bukkit;
|
||||||
const TabCompleter = Java.type('org.bukkit.command.TabCompleter')
|
let TabCompleter = Java.type('org.bukkit.command.TabCompleter');
|
||||||
const PluginCommand = Java.type('org.bukkit.command.PluginCommand')
|
let PluginCommand = Java.type('org.bukkit.command.PluginCommand');
|
||||||
const CommandExecutor = Java.type('org.bukkit.command.CommandExecutor')
|
let CommandExecutor = Java.type('org.bukkit.command.CommandExecutor');
|
||||||
|
|
||||||
@provideSingleton(command.Command)
|
@provideSingleton(command.Command)
|
||||||
export class BukkitCommand extends command.Command {
|
export class BukkitCommand extends command.Command {
|
||||||
@inject(plugin.PluginInstance)
|
@inject(plugin.PluginInstance)
|
||||||
private pluginInstance: any
|
private pluginInstance: any
|
||||||
private commandMap: any
|
private commandMap: any;
|
||||||
private knownCommands: any
|
|
||||||
|
|
||||||
@postConstruct()
|
@postConstruct()
|
||||||
init() {
|
init() {
|
||||||
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get()
|
this.commandMap = reflect.on(Bukkit.getPluginManager()).get('commandMap').get();
|
||||||
this.knownCommands = reflect.on(this.commandMap).get('knownCommands').get()
|
|
||||||
}
|
}
|
||||||
create(plugin: any, command: string) {
|
create(plugin: any, command: string) {
|
||||||
var cmd = this.commandMap.getCommand(command)
|
var cmd = this.commandMap.getCommand(command)
|
||||||
if (cmd instanceof PluginCommand) { return cmd };
|
if (cmd && cmd instanceof PluginCommand) { return cmd };
|
||||||
cmd = reflect.on(PluginCommand).create(command, this.pluginInstance).get()
|
cmd = reflect.on(PluginCommand).create(command, this.pluginInstance).get();
|
||||||
this.commandMap.register(plugin.description.name, cmd)
|
this.commandMap.register(plugin.description.name, cmd);
|
||||||
return cmd
|
return cmd;
|
||||||
}
|
}
|
||||||
remove(plugin: any, command: string) {
|
remove(plugin: any, command: string) {
|
||||||
var cmd = this.commandMap.getCommand(command)
|
var cmd = this.commandMap.getCommand(command)
|
||||||
if (cmd instanceof PluginCommand) {
|
if (cmd && cmd instanceof PluginCommand) {
|
||||||
cmd.unregister(this.commandMap)
|
cmd.unregister(this.commandMap);
|
||||||
this.knownCommands.remove(command)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tabComplete(sender: any, input: string, index?: number): string[] {
|
|
||||||
return Java.from(this.commandMap.tabComplete(sender, input))
|
|
||||||
}
|
|
||||||
onCommand(plugin: any, command: any, executor: Function) {
|
onCommand(plugin: any, command: any, executor: Function) {
|
||||||
// 必须指定需要实现的接口类型 否则MOD服会报错
|
// 必须指定需要实现的接口类型 否则MOD服会报错
|
||||||
command.setExecutor(new CommandExecutor({
|
command.setExecutor(new CommandExecutor({
|
||||||
onCommand: super.setExecutor(plugin, command, executor)
|
onCommand: super.setExecutor(plugin, command, executor)
|
||||||
}))
|
}));
|
||||||
}
|
}
|
||||||
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||||
// 必须指定需要实现的接口类型 否则MOD服会报错
|
// 必须指定需要实现的接口类型 否则MOD服会报错
|
||||||
command.setTabCompleter(new TabCompleter({
|
command.setTabCompleter(new TabCompleter({
|
||||||
onTabComplete: super.setTabCompleter(plugin, command, tabCompleter)
|
onTabComplete: super.setTabCompleter(plugin, command, tabCompleter)
|
||||||
}))
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
import { MiaoScriptConsole } from '@ccms/api'
|
import { MiaoScriptConsole } from '@ccms/api'
|
||||||
|
|
||||||
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
let Bukkit = org.bukkit.Bukkit;
|
||||||
|
|
||||||
export class BukkitConsole extends MiaoScriptConsole {
|
export class BukkitConsole extends MiaoScriptConsole {
|
||||||
sender(sender, ...args) {
|
sender(sender, ...args) {
|
||||||
if (!(sender instanceof Java.type('org.bukkit.command.CommandSender'))) {
|
if (!(sender instanceof Java.type('org.bukkit.command.CommandSender'))) {
|
||||||
this.error(`First parameter ${sender} not instanceof org.bukkit.command.CommandSender can't send message!`)
|
this.error(`First parameter ${sender} not instanceof org.bukkit.command.CommandSender can't send message!`)
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
if (Object.prototype.toString.call(args[0]) === "[object Array]") {
|
if (Object.prototype.toString.call(args[0]) === "[object Array]") {
|
||||||
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
||||||
} else {
|
} else {
|
||||||
sender.sendMessage(this.prefix + args.join(' '))
|
sender.sendMessage(this.prefix + args.join(' '));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console(...args: string[]): void {
|
console(...args: string[]): void {
|
||||||
this.sender(Bukkit.getConsoleSender(), args.join(' '))
|
this.sender(Bukkit.getConsoleSender(), args.join(' '));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
114
packages/bukkit/src/enhance/chat.ts
Normal file
114
packages/bukkit/src/enhance/chat.ts
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
/*global Java, base, module, exports, require*/
|
||||||
|
var nmsChatSerializerClass;
|
||||||
|
var nmsChatSerializerMethod;
|
||||||
|
var packetTypeConstructor;
|
||||||
|
var nmsChatMessageTypeClass;
|
||||||
|
var chatMessageTypes;
|
||||||
|
|
||||||
|
var RemapUtils;
|
||||||
|
|
||||||
|
var playerConnectionFieldName;
|
||||||
|
var sendPacketMethod;
|
||||||
|
|
||||||
|
var downgrade = false;
|
||||||
|
/**
|
||||||
|
* 获取NMS版本
|
||||||
|
*/
|
||||||
|
//@ts-ignore
|
||||||
|
var nmsVersion = org.bukkit.Bukkit.server.class.name.split('.')[3];
|
||||||
|
/**
|
||||||
|
* 获取NMS类
|
||||||
|
*/
|
||||||
|
function nmsCls(name) {
|
||||||
|
return base.getClass(['net.minecraft.server', nmsVersion, name].join('.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
function remapMethod(clazz: any, origin: string, test: string, params) {
|
||||||
|
try {
|
||||||
|
return clazz.getMethod(origin, params)
|
||||||
|
} catch (ex) {
|
||||||
|
if (RemapUtils) {
|
||||||
|
return clazz.getMethod(RemapUtils.mapMethod(clazz, origin, params), params)
|
||||||
|
} else {
|
||||||
|
return clazz.getMethod(test, params)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function remapFieldName(clazz: any, origin: string, test: string) {
|
||||||
|
try {
|
||||||
|
return clazz.getField(origin)
|
||||||
|
} catch (ex) {
|
||||||
|
if (RemapUtils) {
|
||||||
|
return clazz.getField(RemapUtils.mapFieldName(clazz, origin))
|
||||||
|
} else {
|
||||||
|
return clazz.getField(test)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function init() {
|
||||||
|
try {
|
||||||
|
RemapUtils = Java.type('catserver.server.remapper.RemapUtils');
|
||||||
|
} catch (ex) {
|
||||||
|
}
|
||||||
|
nmsChatSerializerClass = nmsCls(nmsVersion.split("_")[1] > 7 ? "IChatBaseComponent$ChatSerializer" : "ChatSerializer");
|
||||||
|
nmsChatSerializerMethod = remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
|
||||||
|
var packetTypeClass = nmsCls("PacketPlayOutChat");
|
||||||
|
Java.from(packetTypeClass.constructors).forEach(function(c) {
|
||||||
|
if (c.parameterTypes.length === 2) {
|
||||||
|
packetTypeConstructor = c
|
||||||
|
}
|
||||||
|
});
|
||||||
|
nmsChatMessageTypeClass = packetTypeConstructor.parameterTypes[1];
|
||||||
|
if (nmsChatMessageTypeClass.isEnum()) {
|
||||||
|
chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants();
|
||||||
|
} else {
|
||||||
|
switch (nmsChatMessageTypeClass.name) {
|
||||||
|
case "int":
|
||||||
|
//@ts-ignore
|
||||||
|
nmsChatMessageTypeClass = java.lang.Integer;
|
||||||
|
break;
|
||||||
|
case "byte":
|
||||||
|
//@ts-ignore
|
||||||
|
nmsChatMessageTypeClass = java.lang.Byte;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var entityPlayerClass = nmsCls('EntityPlayer');
|
||||||
|
var packetClass = nmsCls('Packet');
|
||||||
|
var playerConnectionField = remapFieldName(entityPlayerClass, 'playerConnection', 'field_71135_a')
|
||||||
|
playerConnectionFieldName = playerConnectionField.getName()
|
||||||
|
sendPacketMethod = remapMethod(playerConnectionField.getType(), 'sendPacket', 'func_179290_a', packetClass)
|
||||||
|
}
|
||||||
|
|
||||||
|
function json(sender, json) {
|
||||||
|
if (downgrade) {
|
||||||
|
return '/tellraw ' + sender.name + ' ' + json
|
||||||
|
} else {
|
||||||
|
send(sender, json, 0);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function send(sender, json, type) {
|
||||||
|
//@ts-ignore
|
||||||
|
sendPacket(sender, packetTypeConstructor.newInstance(nmsChatSerializerMethod.invoke(null, json), chatMessageTypes == null ? nmsChatMessageTypeClass.valueOf(java.lang.String.valueOf(type)) : chatMessageTypes[type]))
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendPacket(player, p) {
|
||||||
|
sendPacketMethod.invoke(player.handle[playerConnectionFieldName], p)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
init();
|
||||||
|
} catch (ex) {
|
||||||
|
org.bukkit.Bukkit.getConsoleSender().sendMessage(`§6[§cMS§6][§bbukkit§6][§achat§6] §cNMS Inject Error §4${ex} §cDowngrade to Command Mode...`)
|
||||||
|
downgrade = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
let chat = {
|
||||||
|
json
|
||||||
|
}
|
||||||
|
|
||||||
|
export default chat
|
||||||
@@ -1,14 +1,13 @@
|
|||||||
import { event, plugin } from '@ccms/api'
|
import { event, plugin } from '@ccms/api'
|
||||||
import { inject, provideSingleton } from '@ccms/container'
|
import { inject, provideSingleton } from '@ccms/container';
|
||||||
import * as reflect from '@ccms/common/dist/reflect'
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
|
||||||
const URL = Java.type('java.net.URL')
|
const Bukkit = Java.type("org.bukkit.Bukkit");
|
||||||
const Bukkit = Java.type("org.bukkit.Bukkit")
|
const Event = Java.type("org.bukkit.event.Event");
|
||||||
const Event = Java.type("org.bukkit.event.Event")
|
const Modifier = Java.type("java.lang.reflect.Modifier");
|
||||||
const Modifier = Java.type("java.lang.reflect.Modifier")
|
const Listener = Java.type("org.bukkit.event.Listener");
|
||||||
const Listener = Java.type("org.bukkit.event.Listener")
|
const EventPriority = Java.type("org.bukkit.event.EventPriority");
|
||||||
const EventPriority = Java.type("org.bukkit.event.EventPriority")
|
const EventExecutor = Java.type("org.bukkit.plugin.EventExecutor");
|
||||||
const EventExecutor = Java.type("org.bukkit.plugin.EventExecutor")
|
|
||||||
|
|
||||||
@provideSingleton(event.Event)
|
@provideSingleton(event.Event)
|
||||||
export class BukkitEvent extends event.Event {
|
export class BukkitEvent extends event.Event {
|
||||||
@@ -16,19 +15,11 @@ export class BukkitEvent extends event.Event {
|
|||||||
private pluginInstance: any
|
private pluginInstance: any
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super('org/bukkit/event')
|
super('org/bukkit/event');
|
||||||
}
|
}
|
||||||
|
|
||||||
getJarFile(resource: string) {
|
getJarFile(resource: string) {
|
||||||
try {
|
return super.getJarFile('org/bukkit/Bukkit.class', Bukkit.class.classLoader)
|
||||||
return super.getJarFile('org/bukkit/Bukkit.class', Bukkit.class.classLoader)
|
|
||||||
} catch (error) {
|
|
||||||
// 兼容 LoliServer 的 Bukkit 包无法获取的问题
|
|
||||||
let ModList = Java.type('net.minecraftforge.fml.ModList').get()
|
|
||||||
let forgeFile = ModList.getModFileById("forge").getFile().getFilePath()
|
|
||||||
let jarPath = `jar:file:${forgeFile}!/org/bukkit/Bukkit.class`
|
|
||||||
return new URL(jarPath).openConnection().jarFile
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
isValidEvent(clazz: any): boolean {
|
isValidEvent(clazz: any): boolean {
|
||||||
// 继承于 org.bukkit.event.Event
|
// 继承于 org.bukkit.event.Event
|
||||||
@@ -36,10 +27,10 @@ export class BukkitEvent extends event.Event {
|
|||||||
// 访问符为Public
|
// 访问符为Public
|
||||||
Modifier.isPublic(clazz.getModifiers()) &&
|
Modifier.isPublic(clazz.getModifiers()) &&
|
||||||
// 不是抽象类
|
// 不是抽象类
|
||||||
!Modifier.isAbstract(clazz.getModifiers())
|
!Modifier.isAbstract(clazz.getModifiers());
|
||||||
}
|
}
|
||||||
register(eventCls: any, exec: Function, priority: event.EventPriority, ignoreCancel: boolean) {
|
register(eventCls: any, exec: Function, priority: event.EventPriority, ignoreCancel: boolean) {
|
||||||
let listener = new Listener({})
|
let listener = new Listener({});
|
||||||
Bukkit.pluginManager.registerEvent(
|
Bukkit.pluginManager.registerEvent(
|
||||||
eventCls,
|
eventCls,
|
||||||
listener,
|
listener,
|
||||||
@@ -48,10 +39,10 @@ export class BukkitEvent extends event.Event {
|
|||||||
execute: exec
|
execute: exec
|
||||||
}),
|
}),
|
||||||
this.pluginInstance,
|
this.pluginInstance,
|
||||||
ignoreCancel)
|
ignoreCancel);
|
||||||
return listener
|
return listener;
|
||||||
}
|
}
|
||||||
unregister(event: any, listener: any): void {
|
unregister(event: any, listener: any): void {
|
||||||
reflect.on(event).call('getHandlerList').get().unregister(listener)
|
reflect.on(event).call('getHandlerList').get().unregister(listener);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,15 @@
|
|||||||
/// <reference types="@javatypes/spigot-api" />
|
/// <reference types="@ccms/types/dist/typings/bukkit" />
|
||||||
|
|
||||||
import { server } from '@ccms/api'
|
import { server } from '@ccms/api'
|
||||||
import { Container } from '@ccms/container'
|
import { Container } from '@ccms/container'
|
||||||
|
|
||||||
import { BukkitConsole } from './console'
|
import { BukkitConsole } from './console';
|
||||||
import './item'
|
import './event';
|
||||||
import './chat'
|
import './server';
|
||||||
import './task'
|
import './command';
|
||||||
import './event'
|
import './channel';
|
||||||
import './server'
|
import './task';
|
||||||
import { BukkitNativePluginManager } from './plugin'
|
|
||||||
import './command'
|
|
||||||
import './channel'
|
|
||||||
import './particle'
|
|
||||||
|
|
||||||
export default function BukkitImpl(container: Container) {
|
export default function BukkitImpl(container: Container) {
|
||||||
container.bind(server.Console).toConstantValue(BukkitConsole)
|
container.bind(server.Console).toConstantValue(BukkitConsole);
|
||||||
container.rebind(server.NativePluginManager).toConstantValue(new BukkitNativePluginManager())
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,224 +0,0 @@
|
|||||||
/*global Java, base, module, exports, require*/
|
|
||||||
let bukkitChatInvoke: BukkitChatInvoke
|
|
||||||
/**
|
|
||||||
* 获取NMS类
|
|
||||||
*/
|
|
||||||
abstract class BukkitChatInvoke {
|
|
||||||
private downgrade: boolean = false
|
|
||||||
protected RemapUtils: any
|
|
||||||
protected ComponentSerializer: any
|
|
||||||
|
|
||||||
protected ChatSerializer: any
|
|
||||||
protected nmsChatSerializerMethodName: string
|
|
||||||
protected PacketPlayOutChat: any
|
|
||||||
protected chatMessageTypes: any
|
|
||||||
protected playerConnectionFieldName: string
|
|
||||||
protected playerFieldName: string
|
|
||||||
protected sendPacketMethodName: string
|
|
||||||
|
|
||||||
constructor(private nmsVersion) {
|
|
||||||
}
|
|
||||||
|
|
||||||
init() {
|
|
||||||
try {
|
|
||||||
try {
|
|
||||||
this.ComponentSerializer = Java.type('net.md_5.bungee.chat.ComponentSerializer')
|
|
||||||
this.RemapUtils = Java.type('catserver.server.remapper.RemapUtils')
|
|
||||||
} catch (ex: any) {
|
|
||||||
}
|
|
||||||
let nmsChatSerializerClass = this.getNmsChatSerializerClass()
|
|
||||||
this.nmsChatSerializerMethodName = this.getNmsChatSerializerMethodName(nmsChatSerializerClass)
|
|
||||||
this.ChatSerializer = Java.type(nmsChatSerializerClass.getName())
|
|
||||||
let packetTypeClass = this.getPacketPlayOutChatClass()
|
|
||||||
this.PacketPlayOutChat = Java.type(packetTypeClass.getName())
|
|
||||||
let constructors = packetTypeClass.constructors
|
|
||||||
for (const constructor of Java.from(constructors)) {
|
|
||||||
let parameterTypes = constructor.parameterTypes
|
|
||||||
if (parameterTypes.length === 2 || parameterTypes.length === 3) {
|
|
||||||
let nmsChatMessageTypeClass = parameterTypes[1]
|
|
||||||
if (nmsChatMessageTypeClass.isEnum()) {
|
|
||||||
this.chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants()
|
|
||||||
break
|
|
||||||
} else if (nmsChatMessageTypeClass.getName() == 'int') {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let playerConnectionField = this.getPlayerConnectionField()
|
|
||||||
this.playerConnectionFieldName = playerConnectionField.getName()
|
|
||||||
this.sendPacketMethodName = this.getSendPacketMethodName(playerConnectionField.getType())
|
|
||||||
} catch (ex: any) {
|
|
||||||
org.bukkit.Bukkit.getConsoleSender().sendMessage(`§6[§cMS§6][§bbukkit§6][§achat§6] §cNMS Inject Error §4${ex} §cDowngrade to Command Mode...`)
|
|
||||||
this.downgrade = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
abstract getNmsChatSerializerClass()
|
|
||||||
abstract getNmsChatSerializerMethodName(nmsChatSerializerClass: any)
|
|
||||||
abstract getPacketPlayOutChatClass()
|
|
||||||
abstract getPacketPlayOutChat(sender: any, json: any, type: number)
|
|
||||||
abstract getPlayerConnectionField()
|
|
||||||
abstract getPacketClass()
|
|
||||||
abstract getSendPacketMethodName(playerConnectionClass: any)
|
|
||||||
|
|
||||||
nmsCls(name: string) {
|
|
||||||
return base.getClass(['net.minecraft.server', this.nmsVersion, name].join('.'))
|
|
||||||
}
|
|
||||||
|
|
||||||
remapMethod(clazz: any, methods: string[], params: any) {
|
|
||||||
for (const method of methods) {
|
|
||||||
try {
|
|
||||||
if (this.RemapUtils) {
|
|
||||||
return clazz.getMethod(this.RemapUtils.mapMethod(clazz, method, params), params)
|
|
||||||
} else {
|
|
||||||
return clazz.getMethod(method, params)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new Error(`Class ${clazz} not found method ${methods}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
remapFieldName(clazz: any, fields: string[]) {
|
|
||||||
for (const field of fields) {
|
|
||||||
try {
|
|
||||||
if (this.RemapUtils) {
|
|
||||||
return clazz.getField(this.RemapUtils.mapFieldName(clazz, field))
|
|
||||||
} else {
|
|
||||||
return clazz.getField(field)
|
|
||||||
}
|
|
||||||
} catch (ex: any) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new Error(`Class ${clazz} not found field ${fields}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
json(sender: any, json: string) {
|
|
||||||
if (this.downgrade) {
|
|
||||||
return sender.spigot().sendMessage(this.ComponentSerializer.parse(json))
|
|
||||||
} else {
|
|
||||||
this.send(sender, json, 0)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
send(sender: any, json: any, type: number) {
|
|
||||||
this.sendPacket(sender, this.getPacketPlayOutChat(sender, json, type))
|
|
||||||
}
|
|
||||||
sendPacket(player: { handle: { [x: string]: { [x: string]: (arg0: any) => void } } }, p: any) {
|
|
||||||
player.handle[this.playerConnectionFieldName][this.sendPacketMethodName](p)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class BukkitChatInvokeBase extends BukkitChatInvoke {
|
|
||||||
getSendPacketMethodName(playerConnectionClass: any) {
|
|
||||||
return this.remapMethod(playerConnectionClass, ['sendPacket', 'a', 'func_179290_a'], this.getPacketClass()).getName()
|
|
||||||
}
|
|
||||||
getNmsChatSerializerMethodName(nmsChatSerializerClass: any) {
|
|
||||||
let nmsChatSerializerMethod = this.remapMethod(nmsChatSerializerClass, ['serialize', 'a', 'func_150699_a'], base.getClass('java.lang.String'))
|
|
||||||
return nmsChatSerializerMethod.getName()
|
|
||||||
}
|
|
||||||
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
|
||||||
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), type)
|
|
||||||
}
|
|
||||||
getNmsChatSerializerClass() {
|
|
||||||
return this.nmsCls("ChatSerializer")
|
|
||||||
}
|
|
||||||
getPacketPlayOutChatClass() {
|
|
||||||
return this.nmsCls("PacketPlayOutChat")
|
|
||||||
}
|
|
||||||
getPlayerConnectionField() {
|
|
||||||
return this.remapFieldName(this.nmsCls('EntityPlayer'), ['playerConnection', 'field_71135_a'])
|
|
||||||
}
|
|
||||||
getPacketClass() {
|
|
||||||
return this.nmsCls('Packet')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class BukkitChatInvoke_1_7_10 extends BukkitChatInvokeBase {
|
|
||||||
}
|
|
||||||
|
|
||||||
class BukkitChatInvoke_1_8 extends BukkitChatInvoke_1_7_10 {
|
|
||||||
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
|
||||||
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), this.chatMessageTypes[type])
|
|
||||||
}
|
|
||||||
getNmsChatSerializerClass() {
|
|
||||||
return this.nmsCls("IChatBaseComponent$ChatSerializer")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
class BukkitChatInvoke_1_16_5 extends BukkitChatInvoke_1_8 {
|
|
||||||
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
|
||||||
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), this.chatMessageTypes[type], sender.getUniqueId())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class BukkitChatInvoke_1_17_1 extends BukkitChatInvoke_1_16_5 {
|
|
||||||
getPacketPlayOutChatClass() {
|
|
||||||
return base.getClass('net.minecraft.network.protocol.game.PacketPlayOutChat')
|
|
||||||
}
|
|
||||||
getNmsChatSerializerClass() {
|
|
||||||
return base.getClass('net.minecraft.network.chat.IChatBaseComponent$ChatSerializer')
|
|
||||||
}
|
|
||||||
getPlayerConnectionField() {
|
|
||||||
return base.getClass('net.minecraft.server.level.EntityPlayer').getField('b')
|
|
||||||
}
|
|
||||||
getPacketClass() {
|
|
||||||
return base.getClass('net.minecraft.network.protocol.Packet')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
class BukkitChatInvoke_1_18_2 extends BukkitChatInvoke_1_17_1 {
|
|
||||||
getSendPacketMethodName(playerConnectionClass: any) {
|
|
||||||
return playerConnectionClass.getMethod('a', this.getPacketClass()).getName()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
class BukkitChatInvoke_1_19 extends BukkitChatInvoke_1_18_2 {
|
|
||||||
getPacketPlayOutChatClass() {
|
|
||||||
return base.getClass('net.minecraft.network.protocol.game.ClientboundSystemChatPacket')
|
|
||||||
}
|
|
||||||
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
|
||||||
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), type)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
class BukkitChatInvoke_1_20 extends BukkitChatInvoke_1_19 {
|
|
||||||
getNmsChatSerializerClass() {
|
|
||||||
return base.getClass('net.minecraft.network.chat.IChatBaseComponent')
|
|
||||||
}
|
|
||||||
getNmsChatSerializerMethodName(nmsChatSerializerClass: any) {
|
|
||||||
let nmsChatSerializerMethod = this.remapMethod(nmsChatSerializerClass, ['literal', 'a'], base.getClass('java.lang.String'))
|
|
||||||
return nmsChatSerializerMethod.getName()
|
|
||||||
}
|
|
||||||
getPlayerConnectionField() {
|
|
||||||
return base.getClass('net.minecraft.server.level.EntityPlayer').getField('f')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
let Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
|
||||||
// @ts-ignore
|
|
||||||
let nmsVersion = Bukkit.getServer().class.name.split('.')[3]
|
|
||||||
let nmsSubVersion = nmsVersion.split("_")[1]
|
|
||||||
if (nmsSubVersion >= 20) {
|
|
||||||
bukkitChatInvoke = new BukkitChatInvoke_1_20(nmsVersion)
|
|
||||||
} else if (nmsSubVersion >= 19) {
|
|
||||||
bukkitChatInvoke = new BukkitChatInvoke_1_19(nmsVersion)
|
|
||||||
} else if (nmsSubVersion >= 18) {
|
|
||||||
bukkitChatInvoke = new BukkitChatInvoke_1_18_2(nmsVersion)
|
|
||||||
} else if (nmsSubVersion >= 17) {
|
|
||||||
bukkitChatInvoke = new BukkitChatInvoke_1_17_1(nmsVersion)
|
|
||||||
} else if (nmsSubVersion >= 16) {
|
|
||||||
bukkitChatInvoke = new BukkitChatInvoke_1_16_5(nmsVersion)
|
|
||||||
} else if (nmsSubVersion >= 8) {
|
|
||||||
bukkitChatInvoke = new BukkitChatInvoke_1_8(nmsVersion)
|
|
||||||
} else {
|
|
||||||
bukkitChatInvoke = new BukkitChatInvoke_1_7_10(nmsVersion)
|
|
||||||
}
|
|
||||||
bukkitChatInvoke.init()
|
|
||||||
} catch (ex: any) {
|
|
||||||
}
|
|
||||||
|
|
||||||
let chat = {
|
|
||||||
invoke: bukkitChatInvoke,
|
|
||||||
json: bukkitChatInvoke.json.bind(bukkitChatInvoke),
|
|
||||||
send: bukkitChatInvoke.send.bind(bukkitChatInvoke)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default chat
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,128 +0,0 @@
|
|||||||
import { item } from "@ccms/api"
|
|
||||||
import { provideSingleton } from "@ccms/container"
|
|
||||||
|
|
||||||
import { itemIds } from './internal/item'
|
|
||||||
|
|
||||||
const Material: typeof org.bukkit.Material = Java.type('org.bukkit.Material')
|
|
||||||
const ItemStack: typeof org.bukkit.inventory.ItemStack = Java.type('org.bukkit.inventory.ItemStack')
|
|
||||||
|
|
||||||
@provideSingleton(item.Item)
|
|
||||||
export class BukkitItem extends item.Item {
|
|
||||||
private CraftItemStack: any
|
|
||||||
private NBTTagCompound: any
|
|
||||||
private nmsSaveNBTMethodName: any
|
|
||||||
private MojangsonParser: any
|
|
||||||
private nmsItemStack: any
|
|
||||||
private mpParseMethodName: any
|
|
||||||
private nmsVersion: any
|
|
||||||
constructor() {
|
|
||||||
super()
|
|
||||||
this.reflect()
|
|
||||||
}
|
|
||||||
builder(): item.ItemBuilder {
|
|
||||||
return new BukkitItemBuilder()
|
|
||||||
}
|
|
||||||
toJson(item: any): string {
|
|
||||||
let nbt = new this.NBTTagCompound()
|
|
||||||
return this.CraftItemStack.asNMSCopy(item)[this.nmsSaveNBTMethodName](nbt).toString()
|
|
||||||
}
|
|
||||||
fromJson(json: string) {
|
|
||||||
return this.CraftItemStack.asBukkitCopy(new this.nmsItemStack(this.MojangsonParser[this.mpParseMethodName](json)))
|
|
||||||
}
|
|
||||||
private obcCls(name: string) {
|
|
||||||
return base.getClass(['org.bukkit.craftbukkit', this.nmsVersion, name].join('.'))
|
|
||||||
}
|
|
||||||
private nmsCls(name: string) {
|
|
||||||
return base.getClass(['net.minecraft.server', this.nmsVersion, name].join('.'))
|
|
||||||
}
|
|
||||||
private reflect() {
|
|
||||||
try {
|
|
||||||
let Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
|
||||||
// @ts-ignore
|
|
||||||
this.nmsVersion = Bukkit.getServer().class.name.split('.')[3]
|
|
||||||
let CraftItemStackClass = this.obcCls('inventory.CraftItemStack')
|
|
||||||
this.CraftItemStack = Java.type(CraftItemStackClass.getName())
|
|
||||||
// @ts-ignore
|
|
||||||
let asNMSCopyMethod = CraftItemStackClass.getMethod('asNMSCopy', ItemStack.class)
|
|
||||||
let nmsItemStackClass = asNMSCopyMethod.getReturnType()
|
|
||||||
this.nmsItemStack = Java.type(nmsItemStackClass.getName())
|
|
||||||
let nmsNBTTagCompoundClass = undefined
|
|
||||||
for (let method of Java.from(nmsItemStackClass.getMethods())) {
|
|
||||||
let rt = method.getReturnType()
|
|
||||||
if (method.getParameterTypes().length == 0 && "NBTTagCompound" == rt.getSimpleName()) {
|
|
||||||
nmsNBTTagCompoundClass = rt
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.NBTTagCompound = Java.type(nmsNBTTagCompoundClass.getName())
|
|
||||||
for (let method of Java.from(nmsItemStackClass.getMethods())) {
|
|
||||||
let params = method.getParameterTypes()
|
|
||||||
let rt = method.getReturnType()
|
|
||||||
if (params.length == 1 && "NBTTagCompound" == params[0].getSimpleName() && "NBTTagCompound" == rt.getSimpleName()) {
|
|
||||||
this.nmsSaveNBTMethodName = method.getName()
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
this.MojangsonParser = this.nmsCls('MojangsonParser').static
|
|
||||||
} catch (error) {
|
|
||||||
this.MojangsonParser = Java.type('net.minecraft.nbt.MojangsonParser')
|
|
||||||
}
|
|
||||||
for (let method of Java.from(this.MojangsonParser.class.getMethods())) {
|
|
||||||
let params = method.getParameterTypes()
|
|
||||||
let rt = method.getReturnType()
|
|
||||||
if (params.length == 1 && "String" == params[0].getSimpleName() && "NBTTagCompound" == rt.getSimpleName()) {
|
|
||||||
this.mpParseMethodName = method.getName()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
console.log('Bukkit 物品管理器初始化失败:', error)
|
|
||||||
if (global.debug) {
|
|
||||||
console.ex(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class BukkitItemBuilder implements item.ItemBuilder {
|
|
||||||
private itemStack: org.bukkit.inventory.ItemStack
|
|
||||||
private itemMeta: org.bukkit.inventory.meta.ItemMeta
|
|
||||||
|
|
||||||
from(itemStack: any): item.ItemBuilder {
|
|
||||||
this.itemStack = itemStack
|
|
||||||
this.itemMeta = this.itemStack.getItemMeta()
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
create(type: string | number): item.ItemBuilder {
|
|
||||||
let material = undefined
|
|
||||||
if (typeof type == 'number') {
|
|
||||||
type = itemIds[type]
|
|
||||||
}
|
|
||||||
material = Material[type] || Material[Material['LEGACY_PREFIX'] + type]
|
|
||||||
this.itemStack = new ItemStack(material)
|
|
||||||
this.itemMeta = this.itemStack.getItemMeta()
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
name(name: string): item.ItemBuilder {
|
|
||||||
this.itemMeta.setDisplayName(name)
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
lore(...lores: string[]): item.ItemBuilder {
|
|
||||||
this.itemMeta.setLore(lores)
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
amount(amount: number): item.ItemBuilder {
|
|
||||||
this.itemStack.setAmount(amount)
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
durability(durability: number): item.ItemBuilder {
|
|
||||||
this.itemStack.setDurability(durability)
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
clone() {
|
|
||||||
return this.build().clone()
|
|
||||||
}
|
|
||||||
build() {
|
|
||||||
this.itemStack.setItemMeta(this.itemMeta)
|
|
||||||
return this.itemStack
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
import { provideSingleton } from '@ccms/container'
|
|
||||||
import { particle } from '@ccms/api'
|
|
||||||
|
|
||||||
@provideSingleton(particle.ParticleManager)
|
|
||||||
export class BukkitParticleManager extends particle.ParticleManager {
|
|
||||||
}
|
|
||||||
|
|
||||||
@provideSingleton(particle.ParticleSpawner)
|
|
||||||
export class BukkitParticleSpawner extends particle.ParticleSpawner {
|
|
||||||
spawn(location: org.bukkit.Location, particle: particle.Particle) {
|
|
||||||
location.getWorld().spawnParticle(
|
|
||||||
particle.getParticle(),
|
|
||||||
location,
|
|
||||||
particle.getCount(),
|
|
||||||
particle.getOffsetX(),
|
|
||||||
particle.getOffsetY(),
|
|
||||||
particle.getOffsetZ(),
|
|
||||||
particle.getExtra(),
|
|
||||||
particle.getData()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
spawnToPlayer(player: org.bukkit.entity.Player, location: org.bukkit.Location, particle: particle.Particle) {
|
|
||||||
player.spawnParticle(
|
|
||||||
particle.getParticle(),
|
|
||||||
location,
|
|
||||||
particle.getCount(),
|
|
||||||
particle.getOffsetX(),
|
|
||||||
particle.getOffsetY(),
|
|
||||||
particle.getOffsetZ(),
|
|
||||||
particle.getExtra(),
|
|
||||||
particle.getData())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
import { server } from '@ccms/api'
|
|
||||||
|
|
||||||
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
|
||||||
|
|
||||||
export class BukkitNativePluginManager extends server.NativePluginManager {
|
|
||||||
private bukkitPluginManager: org.bukkit.plugin.PluginManager
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
super()
|
|
||||||
this.bukkitPluginManager = Bukkit.getPluginManager()
|
|
||||||
}
|
|
||||||
|
|
||||||
list(): server.NativePlugin[] {
|
|
||||||
return Java.from(this.bukkitPluginManager.getPlugins()).map(plugin => this.convert(plugin))
|
|
||||||
}
|
|
||||||
has(name: string): boolean {
|
|
||||||
return !!this.bukkitPluginManager.getPlugin(name)
|
|
||||||
}
|
|
||||||
get(name: string): server.NativePlugin {
|
|
||||||
return this.convert(this.bukkitPluginManager.getPlugin(name))
|
|
||||||
}
|
|
||||||
enable(name: string): server.NativePlugin {
|
|
||||||
let origin = this.bukkitPluginManager.getPlugin(name)
|
|
||||||
if (!origin) { throw new Error(`Native Plugin ${name} not found.`) }
|
|
||||||
if (!origin.isEnabled()) {
|
|
||||||
this.bukkitPluginManager.enablePlugin(origin)
|
|
||||||
}
|
|
||||||
return this.convert(origin)
|
|
||||||
}
|
|
||||||
disable(name: string): server.NativePlugin {
|
|
||||||
let origin = this.bukkitPluginManager.getPlugin(name)
|
|
||||||
if (!origin) { throw new Error(`Native Plugin ${name} not found.`) }
|
|
||||||
if (origin.isEnabled()) {
|
|
||||||
this.bukkitPluginManager.disablePlugin(origin)
|
|
||||||
}
|
|
||||||
return this.convert(origin)
|
|
||||||
}
|
|
||||||
|
|
||||||
private convert(plugin: org.bukkit.plugin.Plugin): server.NativePlugin {
|
|
||||||
if (!plugin) return plugin as any
|
|
||||||
let desc = plugin.getDescription()
|
|
||||||
return {
|
|
||||||
name: plugin.getName(),
|
|
||||||
version: desc.getVersion(),
|
|
||||||
authors: Java.from(desc.getAuthors()),
|
|
||||||
depends: Java.from(desc.getDepend()),
|
|
||||||
softDepends: Java.from(desc.getSoftDepend()),
|
|
||||||
enable: plugin.isEnabled(),
|
|
||||||
origin: plugin
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,27 +1,29 @@
|
|||||||
import { server } from '@ccms/api'
|
import { server, constants } from '@ccms/api'
|
||||||
import { provideSingleton } from '@ccms/container'
|
import { provideSingleton } from '@ccms/container';
|
||||||
|
|
||||||
import * as reflect from '@ccms/common/dist/reflect'
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
import chat from './enhance/chat'
|
||||||
|
|
||||||
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
let Bukkit = org.bukkit.Bukkit;
|
||||||
|
|
||||||
@provideSingleton(server.Server)
|
@provideSingleton(server.Server)
|
||||||
export class BukkitServer extends server.ReflectServer {
|
export class BukkitServer implements server.Server {
|
||||||
private pluginsFolder: string
|
private pluginsFolder: string;
|
||||||
|
private pipeline: any;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super()
|
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath();
|
||||||
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath()
|
this.reflectPipeline()
|
||||||
}
|
}
|
||||||
|
|
||||||
getPlayer(name: string) {
|
getPlayer(name: string) {
|
||||||
return Bukkit.getPlayerExact(name)
|
return Bukkit.getPlayer(name)
|
||||||
}
|
}
|
||||||
getVersion(): string {
|
getVersion(): string {
|
||||||
return Bukkit.getVersion()
|
return Bukkit.getVersion()
|
||||||
}
|
}
|
||||||
getOnlinePlayers() {
|
getOnlinePlayers() {
|
||||||
return Bukkit.getOnlinePlayers()
|
return Bukkit.getOnlinePlayers() as unknown as any[]
|
||||||
}
|
}
|
||||||
getConsoleSender() {
|
getConsoleSender() {
|
||||||
return Bukkit.getConsoleSender()
|
return Bukkit.getConsoleSender()
|
||||||
@@ -29,12 +31,6 @@ export class BukkitServer extends server.ReflectServer {
|
|||||||
getService(service: string) {
|
getService(service: string) {
|
||||||
return Bukkit.getServicesManager().getRegistration(base.getClass(service))?.getProvider()
|
return Bukkit.getServicesManager().getRegistration(base.getClass(service))?.getProvider()
|
||||||
}
|
}
|
||||||
broadcast(message: string, permission: string) {
|
|
||||||
return Bukkit.broadcast(message, permission)
|
|
||||||
}
|
|
||||||
broadcastMessage(message: string) {
|
|
||||||
return Bukkit.broadcastMessage(message)
|
|
||||||
}
|
|
||||||
dispatchCommand(sender: string | any, command: string): boolean {
|
dispatchCommand(sender: string | any, command: string): boolean {
|
||||||
if (typeof sender === 'string') {
|
if (typeof sender === 'string') {
|
||||||
sender = this.getPlayer(sender)
|
sender = this.getPlayer(sender)
|
||||||
@@ -45,18 +41,44 @@ export class BukkitServer extends server.ReflectServer {
|
|||||||
return Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)
|
return Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)
|
||||||
}
|
}
|
||||||
getPluginsFolder(): string {
|
getPluginsFolder(): string {
|
||||||
return this.pluginsFolder
|
return this.pluginsFolder;
|
||||||
}
|
}
|
||||||
getNativePluginManager() {
|
getNativePluginManager() {
|
||||||
return Bukkit.getPluginManager() as any
|
return Bukkit.getPluginManager() as any;
|
||||||
}
|
|
||||||
getDedicatedServer() {
|
|
||||||
return reflect.on(Bukkit.getServer()).get('console').get()
|
|
||||||
}
|
}
|
||||||
getNettyPipeline() {
|
getNettyPipeline() {
|
||||||
return this.pipeline
|
return this.pipeline;
|
||||||
}
|
}
|
||||||
getRootLogger() {
|
sendJson(sender: string | any, json: object | string): void {
|
||||||
return this.rootLogger
|
if (typeof sender === "string") {
|
||||||
|
sender = this.getPlayer(sender)
|
||||||
|
}
|
||||||
|
let result = chat.json(sender, json)
|
||||||
|
if (result !== false) {
|
||||||
|
this.dispatchConsoleCommand(result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private reflectPipeline() {
|
||||||
|
let consoleServer = reflect.on(Bukkit.getServer()).get('console').get()
|
||||||
|
let connection: any;
|
||||||
|
let promise: any;
|
||||||
|
for (const method of constants.Reflect.Method.getServerConnection) {
|
||||||
|
try {
|
||||||
|
connection = reflect.on(consoleServer).call(method).get()
|
||||||
|
if (connection.class.name.indexOf('ServerConnection') !== -1) { break; }
|
||||||
|
connection = undefined;
|
||||||
|
} catch (error) { }
|
||||||
|
}
|
||||||
|
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
||||||
|
for (const field of constants.Reflect.Field.listeningChannels) {
|
||||||
|
try {
|
||||||
|
promise = reflect.on(connection).get(field).get().get(0);
|
||||||
|
if (promise.class.name.indexOf('Promise') !== -1) { break; }
|
||||||
|
promise = undefined;
|
||||||
|
} catch (error) { }
|
||||||
|
}
|
||||||
|
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
||||||
|
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,37 @@
|
|||||||
import { task, plugin } from '@ccms/api'
|
import { task, plugin } from '@ccms/api'
|
||||||
import { provideSingleton } from '@ccms/container'
|
import { inject, provideSingleton } from '@ccms/container';
|
||||||
|
|
||||||
const Bukkit = Java.type('org.bukkit.Bukkit')
|
const Bukkit = Java.type('org.bukkit.Bukkit');
|
||||||
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable')
|
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable');
|
||||||
const Callable = Java.type('java.util.concurrent.Callable')
|
const Callable = Java.type('java.util.concurrent.Callable')
|
||||||
|
|
||||||
@provideSingleton(task.TaskManager)
|
@provideSingleton(task.TaskManager)
|
||||||
export class BukkitTaskManager extends task.TaskManager {
|
export class BukkitTaskManager implements task.TaskManager {
|
||||||
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
@inject(plugin.PluginInstance)
|
||||||
return new BukkitTask(owner, func, id)
|
private pluginInstance: any;
|
||||||
|
|
||||||
|
create(func: Function): task.Task {
|
||||||
|
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||||
|
return new BukkitTask(this.pluginInstance, func);
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return Bukkit.getScheduler().callSyncMethod(base.getInstance(), new Callable({ call: () => func() })).get()
|
return Bukkit.getScheduler().callSyncMethod(this.pluginInstance, new Callable({ call: () => func() })).get()
|
||||||
}
|
}
|
||||||
disable0() {
|
disable() {
|
||||||
Bukkit.getScheduler().cancelTasks(base.getInstance())
|
Bukkit.getScheduler().cancelTasks(this.pluginInstance);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BukkitTask extends task.Task {
|
export class BukkitTask extends task.Task {
|
||||||
submit0(...args: any[]): task.Cancelable {
|
submit(): task.Cancelable {
|
||||||
let run = new BukkitRunnable({ run: () => this.run(...args) })
|
let run = new BukkitRunnable({
|
||||||
let suffix = this.isAsync ? 'Asynchronously' : ''
|
run: () => this.run()
|
||||||
|
})
|
||||||
|
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||||
if (this.interval) {
|
if (this.interval) {
|
||||||
return run[`runTaskTimer${suffix}`](base.getInstance(), this.laterTime, this.interval)
|
return run[funcName](this.plugin, this.laterTime, this.interval)
|
||||||
} else {
|
} else {
|
||||||
return run[`runTaskLater${suffix}`](base.getInstance(), this.laterTime)
|
return run[funcName](this.plugin, this.laterTime)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
"extends": "../../tsconfig.json",
|
"extends": "../../tsconfig.json",
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"baseUrl": "src",
|
"baseUrl": "src",
|
||||||
"outDir": "dist",
|
"outDir": "dist"
|
||||||
"resolveJsonModule": true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/bungee",
|
"name": "@ccms/bungee",
|
||||||
"version": "0.28.0-beta.11",
|
"version": "0.6.1",
|
||||||
"description": "MiaoScript bungee package",
|
"description": "MiaoScript bungee package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -12,23 +12,20 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"files": [
|
|
||||||
"dist/**/*.js",
|
|
||||||
"dist/**/*.ts",
|
|
||||||
"dist/**/*.map"
|
|
||||||
],
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "pnpm clean && tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@javatypes/bungee-api": "^0.0.3"
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "workspace:*",
|
"@ccms/api": "^0.6.1",
|
||||||
"@ccms/common": "workspace:*",
|
"@ccms/common": "^0.6.1",
|
||||||
"@ccms/container": "workspace:*"
|
"@ccms/container": "^0.6.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,20 +6,20 @@ const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
|||||||
@provideSingleton(channel.Channel)
|
@provideSingleton(channel.Channel)
|
||||||
export class BungeeChannel extends channel.Channel {
|
export class BungeeChannel extends channel.Channel {
|
||||||
@inject(event.Event)
|
@inject(event.Event)
|
||||||
private eventManager: event.Event
|
private eventManager: event.Event;
|
||||||
|
|
||||||
send(player: any, channel: string, data: any) {
|
send(player: any, channel: string, data: any) {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
register(channel: string, listener: channel.ChannelListener) {
|
register(channel: string, listener: channel.ChannelListener) {
|
||||||
Bungee.registerChannel(channel)
|
Bungee.registerChannel(channel);
|
||||||
// console.console('§6[§eWARN§6] §eMiaoScript channel in BungeeCord only register. you need self hanler PluginMessageEvent!')
|
// console.console('§6[§eWARN§6] §eMiaoScript channel in BungeeCord only register. you need self hanler PluginMessageEvent!')
|
||||||
return this.eventManager.listen({ description: { name: channel } }, "PluginMessageEvent", (event: net.md_5.bungee.api.event.PluginMessageEvent) => {
|
return this.eventManager.listen({ description: { name: channel } }, "PluginMessageEvent", (event: net.md_5.bungee.api.event.PluginMessageEvent) => {
|
||||||
listener(event.getData(), event)
|
listener(event.getData(), event)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
unregister(channel: string, off: any) {
|
unregister(channel: string, listener: any) {
|
||||||
Bungee.unregisterChannel(channel)
|
Bungee.unregisterChannel(channel);
|
||||||
off()
|
listener.off();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ export class BungeeEvent extends event.Event {
|
|||||||
currentPriorityMap.put(listener, methods);
|
currentPriorityMap.put(listener, methods);
|
||||||
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
||||||
return listener;
|
return listener;
|
||||||
} catch (ex: any) {
|
} catch (ex) {
|
||||||
console.ex(ex)
|
console.ex(ex)
|
||||||
} finally {
|
} finally {
|
||||||
this.lock.unlock()
|
this.lock.unlock()
|
||||||
@@ -108,7 +108,7 @@ export class BungeeEvent extends event.Event {
|
|||||||
}
|
}
|
||||||
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
||||||
}
|
}
|
||||||
} catch (ex: any) {
|
} catch (ex) {
|
||||||
console.ex(ex)
|
console.ex(ex)
|
||||||
} finally {
|
} finally {
|
||||||
this.lock.unlock()
|
this.lock.unlock()
|
||||||
|
|||||||
@@ -1,17 +1,15 @@
|
|||||||
/// <reference types="@javatypes/bungee-api" />
|
/// <reference types="@ccms/types/dist/typings/bungee" />
|
||||||
|
|
||||||
import { server } from '@ccms/api'
|
import { server } from '@ccms/api'
|
||||||
import { Container } from '@ccms/container'
|
import { Container } from '@ccms/container'
|
||||||
|
|
||||||
import { BungeeConsole } from './console'
|
import { BungeeConsole } from './console';
|
||||||
import './task'
|
import './event';
|
||||||
import './event'
|
import './server';
|
||||||
import './server'
|
import './command';
|
||||||
import { BungeeNativePluginManager } from './plugin'
|
import './channel';
|
||||||
import './command'
|
import './task';
|
||||||
import './channel'
|
|
||||||
|
|
||||||
export default function BungeeImpl(container: Container) {
|
export default function BungeeImpl(container: Container) {
|
||||||
container.bind(server.Console).toConstantValue(BungeeConsole)
|
container.bind(server.Console).toConstantValue(BungeeConsole);
|
||||||
container.rebind(server.NativePluginManager).toConstantValue(new BungeeNativePluginManager())
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
import { server } from '@ccms/api'
|
|
||||||
|
|
||||||
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
|
||||||
|
|
||||||
export class BungeeNativePluginManager extends server.NativePluginManager {
|
|
||||||
private bungeePluginManager: net.md_5.bungee.api.plugin.PluginManager
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
super()
|
|
||||||
this.bungeePluginManager = Bungee.getPluginManager()
|
|
||||||
}
|
|
||||||
|
|
||||||
list(): server.NativePlugin[] {
|
|
||||||
return Java.from(this.bungeePluginManager.getPlugins()).map(plugin => this.convert(plugin))
|
|
||||||
}
|
|
||||||
has(name: string): boolean {
|
|
||||||
return !!this.bungeePluginManager.getPlugin(name)
|
|
||||||
}
|
|
||||||
get(name: string): server.NativePlugin {
|
|
||||||
return this.convert(this.bungeePluginManager.getPlugin(name))
|
|
||||||
}
|
|
||||||
|
|
||||||
private convert(plugin: net.md_5.bungee.api.plugin.Plugin): server.NativePlugin {
|
|
||||||
if (!plugin) return plugin as any
|
|
||||||
let desc = plugin.getDescription()
|
|
||||||
return {
|
|
||||||
name: desc.getName(),
|
|
||||||
version: desc.getVersion(),
|
|
||||||
authors: [desc.getAuthor()],
|
|
||||||
depends: Java.from(desc.getDepends()) as any,
|
|
||||||
softDepends: Java.from(desc.getSoftDepends()) as any,
|
|
||||||
enable: true,
|
|
||||||
origin: plugin
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,30 +3,29 @@ import { provideSingleton, inject, postConstruct } from '@ccms/container'
|
|||||||
|
|
||||||
import * as reflect from '@ccms/common/dist/reflect'
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
|
||||||
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
||||||
|
|
||||||
@provideSingleton(server.Server)
|
@provideSingleton(server.Server)
|
||||||
export class BungeeServer implements server.Server {
|
export class BungeeServer implements server.Server {
|
||||||
private pluginsFolder: string
|
private pluginsFolder: string;
|
||||||
private pipeline: any
|
private pipeline: any;
|
||||||
private rootLogger: any
|
|
||||||
|
|
||||||
@inject(task.TaskManager)
|
@inject(task.TaskManager)
|
||||||
private task: task.TaskManager
|
private task: task.TaskManager
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.pluginsFolder = Bungee.getPluginsFolder().getCanonicalPath()
|
this.pluginsFolder = Bungee.getPluginsFolder().getCanonicalPath();
|
||||||
}
|
}
|
||||||
|
|
||||||
@postConstruct()
|
@postConstruct()
|
||||||
initialize() {
|
initialize() {
|
||||||
let count = 0
|
let count = 0;
|
||||||
let wait = this.task.create(() => {
|
let wait = this.task.create(() => {
|
||||||
try {
|
try {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
this.pipeline = reflect.on(base.getInstance().getProxy()).get('listeners').get().toArray()[0].pipeline()
|
this.pipeline = reflect.on(base.getInstance().getProxy()).get('listeners').get().toArray()[0].pipeline()
|
||||||
wait.cancel()
|
wait.cancel();
|
||||||
} catch (ex: any) {
|
} catch (ex) {
|
||||||
count++
|
count++
|
||||||
if (count > 50) {
|
if (count > 50) {
|
||||||
console.error('Reflect BungeeCord netty channel pipeline error time > 50times. Err: ' + ex)
|
console.error('Reflect BungeeCord netty channel pipeline error time > 50times. Err: ' + ex)
|
||||||
@@ -36,15 +35,10 @@ export class BungeeServer implements server.Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}).later(10).timer(20).submit()
|
}).later(10).timer(20).submit()
|
||||||
try {
|
|
||||||
this.rootLogger = Bungee.getLogger()
|
|
||||||
} catch (error: any) {
|
|
||||||
console.error("Can't found rootLogger!")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getPlayer(name: string) {
|
getPlayer(name: string) {
|
||||||
return Bungee.getPlayer(name)
|
return Bungee.getPlayer(name);
|
||||||
}
|
}
|
||||||
getVersion(): string {
|
getVersion(): string {
|
||||||
return Bungee.getVersion()
|
return Bungee.getVersion()
|
||||||
@@ -56,13 +50,7 @@ export class BungeeServer implements server.Server {
|
|||||||
return Bungee.getConsole()
|
return Bungee.getConsole()
|
||||||
}
|
}
|
||||||
getService(service: string) {
|
getService(service: string) {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
|
||||||
broadcast(message: string, permission: string) {
|
|
||||||
return Bungee.broadcast(message)
|
|
||||||
}
|
|
||||||
broadcastMessage(message: string) {
|
|
||||||
return Bungee.broadcast(message)
|
|
||||||
}
|
}
|
||||||
dispatchCommand(sender: string | any, command: string): boolean {
|
dispatchCommand(sender: string | any, command: string): boolean {
|
||||||
if (typeof sender === 'string') {
|
if (typeof sender === 'string') {
|
||||||
@@ -74,15 +62,15 @@ export class BungeeServer implements server.Server {
|
|||||||
return Bungee.getPluginManager().dispatchCommand(Bungee.getConsole(), command)
|
return Bungee.getPluginManager().dispatchCommand(Bungee.getConsole(), command)
|
||||||
}
|
}
|
||||||
getPluginsFolder(): string {
|
getPluginsFolder(): string {
|
||||||
return this.pluginsFolder
|
return this.pluginsFolder;
|
||||||
}
|
}
|
||||||
getNativePluginManager() {
|
getNativePluginManager() {
|
||||||
return Bungee.getPluginManager() as any
|
return Bungee.getPluginManager() as any
|
||||||
}
|
}
|
||||||
getNettyPipeline() {
|
getNettyPipeline() {
|
||||||
return this.pipeline
|
return this.pipeline;
|
||||||
}
|
}
|
||||||
getRootLogger() {
|
sendJson(sender: string | any, json: string): void {
|
||||||
return this.rootLogger
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,32 +1,36 @@
|
|||||||
import { task, plugin } from '@ccms/api'
|
import { task, plugin } from '@ccms/api'
|
||||||
import { inject, provideSingleton } from '@ccms/container'
|
import { inject, provideSingleton } from '@ccms/container';
|
||||||
|
|
||||||
var Runnable = Java.type('java.lang.Runnable')
|
var Runnable = Java.type('java.lang.Runnable')
|
||||||
let TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
let TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
||||||
|
|
||||||
@provideSingleton(task.TaskManager)
|
@provideSingleton(task.TaskManager)
|
||||||
export class BungeeTaskManager extends task.TaskManager {
|
export class BungeeTaskManager implements task.TaskManager {
|
||||||
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
@inject(plugin.PluginInstance)
|
||||||
return new BungeeTask(owner, func, id)
|
private pluginInstance: any;
|
||||||
|
|
||||||
|
create(func: Function): task.Task {
|
||||||
|
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||||
|
return new BungeeTask(this.pluginInstance, func);
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return func()
|
return func();
|
||||||
}
|
}
|
||||||
disable0() {
|
disable() {
|
||||||
base.getInstance().getProxy().getScheduler().cancel(base.getInstance())
|
this.pluginInstance.getProxy().getScheduler().cancel(this.pluginInstance)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BungeeTask extends task.Task {
|
export class BungeeTask extends task.Task {
|
||||||
submit0(...args: any[]): task.Cancelable {
|
submit(): task.Cancelable {
|
||||||
let run = new Runnable({ run: () => this.run(...args) })
|
let run = new Runnable({ run: () => this.run() })
|
||||||
if (this.isAsync) {
|
if (this.isAsync) {
|
||||||
return base.getInstance().getProxy().getScheduler().runAsync(base.getInstance(), run)
|
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
||||||
}
|
}
|
||||||
if (this.interval) {
|
if (this.interval) {
|
||||||
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
|
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
|
||||||
} else {
|
} else {
|
||||||
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, TimeUnit.MILLISECONDS)
|
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, TimeUnit.MILLISECONDS)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
31
packages/client/package.json
Normal file
31
packages/client/package.json
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"private": true,
|
||||||
|
"name": "@ccms/client",
|
||||||
|
"version": "0.6.0",
|
||||||
|
"description": "MiaoScript client package",
|
||||||
|
"keywords": [
|
||||||
|
"miaoscript",
|
||||||
|
"minecraft",
|
||||||
|
"bukkit",
|
||||||
|
"sponge"
|
||||||
|
],
|
||||||
|
"author": "MiaoWoo <admin@yumc.pw>",
|
||||||
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
|
"license": "ISC",
|
||||||
|
"main": "dist/index.js",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "ts-node-dev --respawn --debounce=1500 src/index.ts",
|
||||||
|
"clean": "rimraf dist",
|
||||||
|
"watch": "tsc --watch",
|
||||||
|
"build": "yarn clean && tsc",
|
||||||
|
"start": "node dist/index.js",
|
||||||
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"minecraft-protocol": "^1.11.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^3.8.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
101
packages/client/src/color.ts
Normal file
101
packages/client/src/color.ts
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
class MessagePart {
|
||||||
|
text: string
|
||||||
|
color: string
|
||||||
|
clickEvent: MessagePartEvent
|
||||||
|
hoverEvent: MessagePartEvent
|
||||||
|
translate: string
|
||||||
|
with: MessagePart[]
|
||||||
|
extra: MessagePart[]
|
||||||
|
}
|
||||||
|
|
||||||
|
class MessagePartEvent {
|
||||||
|
action: string
|
||||||
|
value: string
|
||||||
|
}
|
||||||
|
|
||||||
|
var colorMap = []
|
||||||
|
colorMap['0'] = '38;5;0'
|
||||||
|
colorMap['1'] = '38;5;4'
|
||||||
|
colorMap['2'] = '38;5;2'
|
||||||
|
colorMap['3'] = '38;5;6'
|
||||||
|
colorMap['4'] = '38;5;1'
|
||||||
|
colorMap['5'] = '38;5;5'
|
||||||
|
colorMap['6'] = '38;5;3'
|
||||||
|
colorMap['7'] = '38;5;7'
|
||||||
|
colorMap['8'] = '38;5;8'
|
||||||
|
colorMap['9'] = '38;5;12'
|
||||||
|
colorMap['a'] = '38;5;10'
|
||||||
|
colorMap['b'] = '38;5;14'
|
||||||
|
colorMap['c'] = '38;5;9'
|
||||||
|
colorMap['d'] = '38;5;13'
|
||||||
|
colorMap['e'] = '38;5;11'
|
||||||
|
colorMap['f'] = '38;5;15'
|
||||||
|
colorMap['r'] = '0'
|
||||||
|
colorMap['l'] = '1'
|
||||||
|
colorMap['n'] = '4'
|
||||||
|
var regexMap = []
|
||||||
|
for (const c in colorMap) {
|
||||||
|
regexMap[colorMap[c]] = new RegExp(`§${c}`, "g")
|
||||||
|
}
|
||||||
|
function mcColor2ANSI(str) {
|
||||||
|
for (const regex in regexMap) {
|
||||||
|
str = str.replace(regexMap[regex], `\u001b[${regex}m`)
|
||||||
|
}
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
let jsonColorMap = {
|
||||||
|
"black": '0',
|
||||||
|
"dark_blue": '1',
|
||||||
|
"dark_green": '2',
|
||||||
|
"dark_aqua": '3',
|
||||||
|
"dark_red": '4',
|
||||||
|
"dark_purple": '5',
|
||||||
|
"gold": '6',
|
||||||
|
"gray": '7',
|
||||||
|
"dark_gray": '8',
|
||||||
|
"blue": '9',
|
||||||
|
"green": 'a',
|
||||||
|
"aqua": 'b',
|
||||||
|
"red": 'c',
|
||||||
|
"light_purple": 'd',
|
||||||
|
"yellow": 'e',
|
||||||
|
"white": 'f',
|
||||||
|
"obfuscated": 'k',
|
||||||
|
"bold": 'l',
|
||||||
|
"strikethrough": 'm',
|
||||||
|
"underline": 'n',
|
||||||
|
"italic": 'o',
|
||||||
|
"reset": 'r',
|
||||||
|
};
|
||||||
|
|
||||||
|
function json2text(json: MessagePart): string {
|
||||||
|
let temp = "";
|
||||||
|
if (json.color) {
|
||||||
|
temp += `§${jsonColorMap[json.color]}`
|
||||||
|
}
|
||||||
|
temp += json.text || json.translate || ''
|
||||||
|
if (json.extra) {
|
||||||
|
json.extra.forEach((ext) => {
|
||||||
|
temp += json2text(ext)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return temp += '§r'
|
||||||
|
}
|
||||||
|
|
||||||
|
function $(input: any) {
|
||||||
|
if (typeof input === "string") {
|
||||||
|
input = JSON.parse(input)
|
||||||
|
}
|
||||||
|
input = json2text(input) + '§r'
|
||||||
|
if (input.startsWith('§卐')) {
|
||||||
|
input = input.substring(2)
|
||||||
|
}
|
||||||
|
return mcColor2ANSI(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
json2text,
|
||||||
|
mcColor2ANSI,
|
||||||
|
$
|
||||||
|
}
|
||||||
27
packages/client/src/event.ts
Normal file
27
packages/client/src/event.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { $ } from './color'
|
||||||
|
|
||||||
|
export function attachEvents(client) {
|
||||||
|
client.on('chat', (packet) => {
|
||||||
|
// Listen for chat messages and echo them back.
|
||||||
|
var jsonMsg = JSON.parse(packet.message);
|
||||||
|
console.log($(jsonMsg))
|
||||||
|
})
|
||||||
|
client.on('state', (newState, oldState) => {
|
||||||
|
console.log('Client Change State', oldState, 'to', newState)
|
||||||
|
let targetServer = process.argv[3]
|
||||||
|
if (newState == "play" && targetServer) {
|
||||||
|
setTimeout(() => {
|
||||||
|
client.write('chat', {
|
||||||
|
message: '/server ' + targetServer
|
||||||
|
})
|
||||||
|
}, 3000)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
client.on('update_health', (packet) => {
|
||||||
|
if (packet.health <= 0) {
|
||||||
|
console.log("Player Dead Auto Respawn...")
|
||||||
|
client.write('client_command', { payload: 0 })
|
||||||
|
} else if (packet.health > 0) {
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
14
packages/client/src/forge.ts
Normal file
14
packages/client/src/forge.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
export function attachForge(client) {
|
||||||
|
client.on('custom_payload', function(packet) {
|
||||||
|
if (packet.channel === 'FML|HS') {
|
||||||
|
client.write('custom_payload', {
|
||||||
|
channel: 'FML|HS',
|
||||||
|
data: Buffer.of(0x01, 0x02)
|
||||||
|
});
|
||||||
|
client.write('custom_payload', {
|
||||||
|
channel: 'FML|HS',
|
||||||
|
data: Buffer.of(0x02, 0x00)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
78
packages/client/src/index.ts
Normal file
78
packages/client/src/index.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import { createInterface } from 'readline'
|
||||||
|
import { createClient } from 'minecraft-protocol'
|
||||||
|
|
||||||
|
import { attachForge } from './forge'
|
||||||
|
import { attachEvents } from './event'
|
||||||
|
|
||||||
|
let username = process.argv[2] || 'Mr_jtb'
|
||||||
|
let version = process.argv[3] || '1.12.2'
|
||||||
|
let client = createConnection('192.168.2.5', 25577, username)
|
||||||
|
|
||||||
|
function createConnection(host: string, port: number, username: string) {
|
||||||
|
let client = createClient({
|
||||||
|
version,
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
username,
|
||||||
|
skipValidation: true
|
||||||
|
})
|
||||||
|
|
||||||
|
attachForge(client)
|
||||||
|
attachEvents(client)
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
client.on('error', (error) => {
|
||||||
|
console.log("Client Error", error)
|
||||||
|
})
|
||||||
|
|
||||||
|
client.on('end', (resone) => {
|
||||||
|
console.log("Client End Resone:", resone)
|
||||||
|
client = createConnection('192.168.2.5', 25577, username)
|
||||||
|
})
|
||||||
|
|
||||||
|
const rl = createInterface({
|
||||||
|
input: process.stdin,
|
||||||
|
output: process.stdout,
|
||||||
|
completer: (line, func) => {
|
||||||
|
let args = line.split(' ')
|
||||||
|
let comp = args[args.length - 1]
|
||||||
|
client.once('tab_complete', (msg) => {
|
||||||
|
let mcts = msg.matches.filter(s => s)
|
||||||
|
func(null, [mcts, comp])
|
||||||
|
})
|
||||||
|
client.write('tab_complete', {
|
||||||
|
text: line
|
||||||
|
})
|
||||||
|
},
|
||||||
|
terminal: true,
|
||||||
|
prompt: ''
|
||||||
|
})
|
||||||
|
|
||||||
|
rl.on('line', function (line) {
|
||||||
|
switch (line) {
|
||||||
|
case "":
|
||||||
|
break;
|
||||||
|
case "eval":
|
||||||
|
break;
|
||||||
|
case "write":
|
||||||
|
break;
|
||||||
|
case "/respawn":
|
||||||
|
client.write('client_command', { payload: 0 })
|
||||||
|
break;
|
||||||
|
case "//reco":
|
||||||
|
client.end("")
|
||||||
|
client = createConnection('192.168.2.5', 25577, username)
|
||||||
|
break;
|
||||||
|
case "//quit":
|
||||||
|
console.info('Disconnected')
|
||||||
|
client.end("")
|
||||||
|
break;
|
||||||
|
case "//end":
|
||||||
|
console.info('Forcibly ended client')
|
||||||
|
process.exit(0)
|
||||||
|
default:
|
||||||
|
client.write('chat', { message: line })
|
||||||
|
}
|
||||||
|
rl.prompt()
|
||||||
|
})
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/common",
|
"name": "@ccms/common",
|
||||||
"version": "0.28.0-beta.11",
|
"version": "0.6.1",
|
||||||
"description": "MiaoScript common package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
"minecraft",
|
"minecraft",
|
||||||
@@ -12,20 +12,19 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"files": [
|
|
||||||
"dist/**/*.js",
|
|
||||||
"dist/**/*.ts",
|
|
||||||
"dist/**/*.map"
|
|
||||||
],
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "pnpm clean && tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "workspace:*",
|
"reflect-metadata": "^0.1.13",
|
||||||
"@javatypes/jdk": "^0.0.3"
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^3.8.3"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@ccms/nashorn": "^0.6.1"
|
||||||
},
|
},
|
||||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,9 @@ export function concat(...args: string[]) {
|
|||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
export function file(...opts: any[]): any {
|
export function file(...opts: any[]): any {
|
||||||
if (!opts[0]) { throw new Error("文件名称不得为 undefined 或者 null !") }
|
if (!opts[0]) {
|
||||||
|
console.warn("文件名称不得为 undefined 或者 null !");
|
||||||
|
}
|
||||||
switch (opts.length) {
|
switch (opts.length) {
|
||||||
case 1:
|
case 1:
|
||||||
var f = opts[0];
|
var f = opts[0];
|
||||||
@@ -141,7 +143,7 @@ export function del(file) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (file.isDirectory()) {
|
if (file.isDirectory()) {
|
||||||
Files.list(file.toPath()).collect(Collector.toList()).forEach(function (f) {
|
Files.list(file.toPath()).collect(Collector.toList()).forEach(function(f) {
|
||||||
del(f);
|
del(f);
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import * as querystring from 'querystring'
|
|
||||||
|
|
||||||
const URL = Java.type('java.net.URL')
|
const URL = Java.type('java.net.URL')
|
||||||
const Paths = Java.type('java.nio.file.Paths')
|
const Paths = Java.type('java.nio.file.Paths');
|
||||||
const Files = Java.type('java.nio.file.Files')
|
const Files = Java.type('java.nio.file.Files');
|
||||||
const StandardCopyOption = Java.type('java.nio.file.StandardCopyOption')
|
const StandardCopyOption = Java.type('java.nio.file.StandardCopyOption');
|
||||||
|
|
||||||
export type Method =
|
export type Method =
|
||||||
| 'get' | 'GET'
|
| 'get' | 'GET'
|
||||||
@@ -15,58 +13,36 @@ export type Method =
|
|||||||
| 'patch' | 'PATCH'
|
| 'patch' | 'PATCH'
|
||||||
|
|
||||||
interface RequestConfig {
|
interface RequestConfig {
|
||||||
url?: string
|
url?: string;
|
||||||
method?: Method
|
method?: Method;
|
||||||
headers?: { [key: string]: string }
|
headers?: { [key: string]: string };
|
||||||
params?: { [key: string]: string }
|
params?: { [key: string]: string };
|
||||||
data?: any,
|
data?: any;
|
||||||
connectTimeout?: number,
|
|
||||||
readTimeout?: number,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function request(config: RequestConfig) {
|
function request(config: RequestConfig) {
|
||||||
// @ts-ignore XMLHttpRequest class only exist nashorn polyfill
|
// @ts-ignore
|
||||||
let xhr = new XMLHttpRequest()
|
let xhr = new XMLHttpRequest();
|
||||||
if (config.connectTimeout) {
|
xhr.open(config.method, config.url, false);
|
||||||
xhr.connectTimeout = config.connectTimeout
|
|
||||||
}
|
|
||||||
if (config.readTimeout) {
|
|
||||||
xhr.readTimeout = config.readTimeout
|
|
||||||
}
|
|
||||||
xhr.open(config.method, config.url, false)
|
|
||||||
for (const header in config.headers) {
|
for (const header in config.headers) {
|
||||||
xhr.setRequestHeader(header, config.headers[header])
|
xhr.setRequestHeader(header, config.headers[header]);
|
||||||
}
|
}
|
||||||
let body = config.data
|
xhr.send(config.data);
|
||||||
if (body && typeof body !== "string") {
|
if ((xhr.getResponseHeader("Content-Type") + '').indexOf('application/json') != -1) {
|
||||||
switch (config.headers['Content-Type']) {
|
|
||||||
case "application/json":
|
|
||||||
body = JSON.stringify(body)
|
|
||||||
break
|
|
||||||
case "application/x-www-form-urlencoded":
|
|
||||||
body = querystring.encode(body)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
xhr.send(body)
|
|
||||||
if (xhr.getResponseHeader("Content-Type").indexOf('application/json') != -1) {
|
|
||||||
xhr.responseType = "json"
|
xhr.responseType = "json"
|
||||||
}
|
}
|
||||||
// @ts-ignore get only exist nashorn polyfill
|
return xhr.get();
|
||||||
return xhr.get()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function download(url: string, target: string) {
|
function download(url: string, target: string) {
|
||||||
console.debug(`Start Download file ${target} from ${url}....`)
|
console.debug(`Start Download file ${target} from ${url}....`)
|
||||||
Files.copy(new URL(url).openStream(), Paths.get(target), StandardCopyOption.REPLACE_EXISTING)
|
Files.copy(new URL(url).openStream(), Paths.get(target), StandardCopyOption.REPLACE_EXISTING);
|
||||||
console.debug(`File ${target} Download Complate...`)
|
console.debug(`File ${target} Download Complate...`)
|
||||||
}
|
}
|
||||||
|
|
||||||
function _proxy(method: Method) {
|
function _proxy(method: Method) {
|
||||||
return function (url: string, data?: any, config: RequestConfig = {}) {
|
return function (url: string, data?: any, config?: RequestConfig) {
|
||||||
if (!config.headers) { config.headers = {} }
|
return request({ url, method, data, ...config });
|
||||||
config.headers['Content-Type'] = config.headers['Content-Type'] ?? 'application/json'
|
|
||||||
return request({ url, method, data, ...config })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,202 +1,196 @@
|
|||||||
/// <reference types="@javatypes/jdk" />
|
|
||||||
|
|
||||||
const JavaClass = Java.type('java.lang.Class')
|
|
||||||
const JavaObject = Java.type('java.lang.Object')
|
|
||||||
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException')
|
|
||||||
const fieldCache = new Map<string, java.lang.reflect.Field>()
|
|
||||||
const methodCache = new Map<string, java.lang.reflect.Method>()
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 反射工具类
|
* 反射工具类
|
||||||
* Created by MiaoWoo on 2017/2/9 0009.
|
* Created by MiaoWoo on 2017/2/9 0009.
|
||||||
*/
|
*/
|
||||||
|
const JavaClass = Java.type('java.lang.Class');
|
||||||
|
const JavaObject = Java.type('java.lang.Object')
|
||||||
|
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException');
|
||||||
|
const methodCache = [];
|
||||||
|
|
||||||
class Reflect {
|
class Reflect {
|
||||||
private obj: java.lang.Object
|
private obj: any;
|
||||||
private class: java.lang.Class<any>
|
private class: any
|
||||||
|
|
||||||
constructor(obj: any) {
|
constructor(obj: any) {
|
||||||
// if (obj === undefined || obj === null) { throw Error(`reflect object can't be ${obj}!`) }
|
// if (obj === undefined || obj === null) { throw Error(`reflect object can't be ${obj}!`) }
|
||||||
if (obj instanceof JavaClass) {
|
if (obj instanceof JavaClass) {
|
||||||
this.obj = null
|
this.obj = null;
|
||||||
this.class = obj
|
this.class = obj;
|
||||||
} else {
|
} else {
|
||||||
this.obj = obj
|
this.obj = obj;
|
||||||
if (obj !== null && obj !== undefined && obj.class) {
|
if (obj !== null && obj !== undefined && obj.class) {
|
||||||
this.class = obj.class
|
this.class = obj.class;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
method(name: string, ...args: java.lang.Class<any>[]) {
|
method(...args: any[]) {
|
||||||
return declaredMethod(this.class, name, ...args)
|
return declaredMethod(this.class, args[0], types(args.slice(1)));
|
||||||
}
|
}
|
||||||
|
|
||||||
methods() {
|
methods() {
|
||||||
return Java.from(declaredMethods(this.class))
|
return Java.from(declaredMethods(this.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
field(nameOrIndex: string | java.lang.String | number, declared = false): java.lang.reflect.Field {
|
field(name): Reflect {
|
||||||
if (nameOrIndex == undefined || nameOrIndex == null) throw new Error(`reflect field name can't be ${nameOrIndex} from ${this.class.getName()}!`)
|
try {
|
||||||
let key = this.class.getName() + ':' + nameOrIndex + ':' + declared
|
// Try getting a public field
|
||||||
if (fieldCache.has(key)) {
|
let field = this.class.field(name);
|
||||||
return fieldCache.get(key)
|
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));
|
||||||
}
|
}
|
||||||
let field = null
|
};
|
||||||
if (typeof nameOrIndex == "number") {
|
|
||||||
field = this.fields(declared)[nameOrIndex]
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
// Try getting a public field
|
|
||||||
field = this.class.getField(nameOrIndex)
|
|
||||||
} catch (ex: any) {
|
|
||||||
// Try again, getting a non-public field
|
|
||||||
field = declaredField(this.class, nameOrIndex)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!field) throw new Error(`can't reflect field ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${this.class.getName()}!`)
|
|
||||||
fieldCache.set(key, field)
|
|
||||||
return accessible(field)
|
|
||||||
}
|
|
||||||
|
|
||||||
fields(declared = false): java.lang.reflect.Field[] {
|
fields(declared = false) {
|
||||||
return Java.from(declared ? this.class.getDeclaredFields() : this.class.getFields())
|
return Java.from(declared ? this.class.declaredFields : this.class.fields);
|
||||||
}
|
}
|
||||||
|
|
||||||
values(declared = false) {
|
values(declared = false) {
|
||||||
return this.fields(declared).reduce((cache, field) => { return cache[field.getName()] = this.get(field.getName()).get() }, {}) as any
|
let cache = {};
|
||||||
|
this.fields(declared).forEach(fed => cache[fed.name] = this.field(fed.name).get())
|
||||||
|
return cache;
|
||||||
}
|
}
|
||||||
|
|
||||||
call(...args: any[]): Reflect {
|
call(...args): Reflect {
|
||||||
let params = args.slice(1)
|
let params = args.slice(1);
|
||||||
let method = accessible(declaredMethod(this.class, args[0], ...types(params)))
|
let method = accessible(declaredMethod(this.class, args[0], types(params)));
|
||||||
let result = method.invoke(this.get(), params)
|
let result = method.invoke(this.get(), params);
|
||||||
return result && on(result)
|
return result && on(result);
|
||||||
}
|
};
|
||||||
|
|
||||||
get(): any
|
get(...args): Reflect | any {
|
||||||
get(index: number, declared?: boolean): Reflect
|
return args.length === 1 ? this.field(args[0]) : this.obj;
|
||||||
get(prop: string): Reflect
|
};
|
||||||
get(param?: string | number, declared: boolean = true): Reflect | any {
|
|
||||||
if (arguments.length === 0) return this.obj
|
|
||||||
return on(this.field(param, declared).get(this.obj))
|
|
||||||
}
|
|
||||||
|
|
||||||
set(param: string | number, value: any, declared: boolean = true): Reflect {
|
// noinspection JSUnusedGlobalSymbols
|
||||||
this.field(param, declared).set(this.obj, value)
|
set(name, value): Reflect {
|
||||||
return this
|
accessible(declaredField(this.class, name)).set(this.obj, value);
|
||||||
}
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
create(...args): Reflect {
|
create(...args): Reflect {
|
||||||
return on(declaredConstructor(this.class, args).newInstance(args))
|
return on(declaredConstructor(this.class, args).newInstance(args));
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get an array of types for an array of objects
|
* Get an array of types for an array of objects
|
||||||
*/
|
*/
|
||||||
function types(values: any[], def?: any) {
|
function types(values, def?) {
|
||||||
if (values === null) {
|
if (values === null) {
|
||||||
return []
|
return [];
|
||||||
}
|
}
|
||||||
let result: java.lang.Class<any>[] = []
|
let result: any[] = [];
|
||||||
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class))
|
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class));
|
||||||
return result
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
function accessible<T extends java.lang.reflect.AccessibleObject>(accessible: T): T {
|
function accessible(accessible) {
|
||||||
if (!accessible?.isAccessible()) {
|
if (accessible === null) {
|
||||||
accessible.setAccessible(true)
|
return null;
|
||||||
}
|
}
|
||||||
return accessible
|
if (!accessible.isAccessible()) {
|
||||||
|
accessible.setAccessible(true);
|
||||||
|
}
|
||||||
|
return accessible;
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredConstructor(clazz, param) {
|
function declaredConstructor(clazz, param) {
|
||||||
let constructor
|
let constructor;
|
||||||
try {
|
try {
|
||||||
constructor = clazz.getDeclaredConstructor(types(param))
|
constructor = clazz.getDeclaredConstructor(types(param));
|
||||||
} catch (ex: any) {
|
} catch (ex) {
|
||||||
try {
|
try {
|
||||||
constructor = clazz.getDeclaredConstructor(types(param, true))
|
constructor = clazz.getDeclaredConstructor(types(param, true));
|
||||||
} catch (ex: any) {
|
} catch (ex) {
|
||||||
constructor = clazz.getDeclaredConstructors()[0]
|
constructor = clazz.getDeclaredConstructors()[0];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return accessible(constructor)
|
return accessible(constructor);
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.String) {
|
function declaredField(clazz, name) {
|
||||||
if (!clazz) { throw Error(`target class can't be ${clazz}!`) }
|
if (!clazz) { throw Error(`target class can't be ${clazz}!`) }
|
||||||
let target = clazz
|
let target = clazz;
|
||||||
let field = null
|
let field = null;
|
||||||
// noinspection JSUnresolvedVariable
|
// noinspection JSUnresolvedVariable
|
||||||
while (target !== JavaObject.class) {
|
while (target !== JavaObject.class) {
|
||||||
console.debug(`reflect field ${name} from ${target.getName()}`)
|
|
||||||
try {
|
try {
|
||||||
field = target.getDeclaredField(name)
|
field = target.getDeclaredField(name);
|
||||||
if (field !== null) { break }
|
if (field !== null) { break; }
|
||||||
} catch (error: any) {
|
} catch (e) {
|
||||||
if (target === undefined) { break }
|
if (target === undefined) { break; }
|
||||||
target = target.getSuperclass()
|
target = target.getSuperclass();
|
||||||
console.debug(`switch to super class: ${target.getName()}`)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (field === null) {
|
if (field === null) {
|
||||||
throw new NoSuchFieldException(name + " is not found in " + clazz.getName())
|
throw new NoSuchFieldException(name + " is not found in " + clazz.name);
|
||||||
}
|
}
|
||||||
return field
|
return field;
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredMethod(clazz: java.lang.Class<any>, nameOrIndex: string | number, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
|
function declaredMethod(clazz, name, clazzs) {
|
||||||
let key = clazz.getName() + '.' + nameOrIndex + ':' + (clazzs || []).map(c => c.getName()).join(':')
|
let key = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
|
||||||
if (methodCache.has(key)) { return methodCache.get(key) }
|
if (!methodCache[key]) {
|
||||||
let target = clazz
|
try {
|
||||||
if (typeof nameOrIndex === "number") {
|
methodCache[key] = clazz.getMethod(name, clazzs);
|
||||||
methodCache.set(key, declaredMethods(clazz)[nameOrIndex])
|
} catch (ex) {
|
||||||
} else {
|
|
||||||
while (target !== JavaObject.class && !methodCache.has(key)) {
|
|
||||||
try {
|
try {
|
||||||
console.debug(`reflect method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${target.getName()}`)
|
methodCache[key] = clazz.getDeclaredMethod(name, clazzs);
|
||||||
try {
|
} catch (ex) {
|
||||||
methodCache.set(key, target.getMethod(nameOrIndex, clazzs as any))
|
for (const m of Java.from(declaredMethods(clazz))) {
|
||||||
} catch (ex: any) {
|
if (m.name == name) {
|
||||||
try {
|
methodCache[key] = m;
|
||||||
methodCache.set(key, target.getDeclaredMethod(nameOrIndex, clazzs as any))
|
break;
|
||||||
} catch (ex: any) {
|
|
||||||
for (const m of Java.from(declaredMethods(target))) {
|
|
||||||
if (m.getName() == nameOrIndex) {
|
|
||||||
methodCache.set(key, m)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new Error(`method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} not found.`)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
|
||||||
if (target === undefined) { break }
|
|
||||||
target = target.getSuperclass()
|
|
||||||
console.debug(`switch to super class: ${target.getName()}`)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!methodCache.has(key)) throw new Error(`can't reflect method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${clazz.getName()}!`)
|
return methodCache[key];
|
||||||
return methodCache.get(key)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredMethods(clazz: java.lang.Class<any>) {
|
function declaredMethods(clazz) {
|
||||||
return clazz.getDeclaredMethods()
|
return clazz.declaredMethods;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let classMethodsCache: any[] = [];
|
||||||
|
|
||||||
function mapToObject(javaObj) {
|
function mapToObject(javaObj) {
|
||||||
if (!Java.isJavaObject(javaObj)) { throw new TypeError(`argument ${javaObj} is not a java object.`) }
|
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
||||||
let target = Proxy.newProxy(javaObj, {
|
let target = {};
|
||||||
apply: (target, name, args) => { return args ? javaObj[name](args) : javaObj[name]() }
|
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t));
|
||||||
})
|
return target;
|
||||||
return target
|
}
|
||||||
|
|
||||||
|
function getJavaObjectMethods(javaObj) {
|
||||||
|
let className = javaObj.class.name;
|
||||||
|
if (!classMethodsCache[className]) {
|
||||||
|
let names: any[] = [];
|
||||||
|
let methods = javaObj.class.methods;
|
||||||
|
for (let 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) {
|
function on(obj) {
|
||||||
// if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
|
// if (!obj || !obj.class) { throw new TypeError(`参数 ${obj} 不是一个Java对象!`) }
|
||||||
return new Reflect(obj)
|
return new Reflect(obj);
|
||||||
}
|
}
|
||||||
|
|
||||||
export = {
|
export = {
|
||||||
|
|||||||
@@ -17,14 +17,14 @@ class ChatMessagePart {
|
|||||||
}
|
}
|
||||||
|
|
||||||
convert() {
|
convert() {
|
||||||
return this.internal
|
return this.internal;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Tellraw {
|
class Tellraw {
|
||||||
static duplicateChar = '§卐'
|
static duplicateChar = '§卐'
|
||||||
static create() {
|
static create() {
|
||||||
return new Tellraw().then(Tellraw.duplicateChar)
|
return new Tellraw().then(Tellraw.duplicateChar);
|
||||||
}
|
}
|
||||||
|
|
||||||
private cache: string = '';
|
private cache: string = '';
|
||||||
@@ -32,81 +32,77 @@ class Tellraw {
|
|||||||
|
|
||||||
then(part: ChatMessagePart | string) {
|
then(part: ChatMessagePart | string) {
|
||||||
if (typeof part === "string") {
|
if (typeof part === "string") {
|
||||||
var newPart = new ChatMessagePart()
|
var newPart = new ChatMessagePart();
|
||||||
newPart.text = part
|
newPart.text = part
|
||||||
this.then(newPart)
|
this.then(newPart);
|
||||||
return this
|
return this;
|
||||||
}
|
}
|
||||||
var last = this.latest()
|
var last = this.latest();
|
||||||
if (!last.text) {
|
if (!last.text) {
|
||||||
last.text = part.text
|
last.text = part.text;
|
||||||
} else {
|
} else {
|
||||||
this.parts.push(part)
|
this.parts.push(part);
|
||||||
}
|
}
|
||||||
this.cache = null
|
this.cache = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
text(text: string) {
|
text(text: string) {
|
||||||
this.latest().text = text
|
this.latest().text = text;
|
||||||
return this
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
tip(texts: string) {
|
tip(text: string) {
|
||||||
return this.hover(texts)
|
this.latest().hover("show_text", text);
|
||||||
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
hover(texts: string) {
|
item(text: string) {
|
||||||
this.latest().hover("show_text", texts)
|
this.latest().hover("show_item", text);
|
||||||
return this
|
return this;
|
||||||
}
|
|
||||||
|
|
||||||
item(item: string) {
|
|
||||||
this.latest().hover("show_item", item)
|
|
||||||
return this
|
|
||||||
}
|
}
|
||||||
|
|
||||||
command(command: string) {
|
command(command: string) {
|
||||||
this.latest().click("run_command", command)
|
this.latest().click("run_command", command);
|
||||||
return this
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
suggest(url: string) {
|
suggest(url: string) {
|
||||||
this.latest().click("suggest_command", url)
|
this.latest().click("suggest_command", url);
|
||||||
return this
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
file(path: string) {
|
file(path: string) {
|
||||||
this.latest().click("open_file", path)
|
this.latest().click("open_file", path);
|
||||||
return this
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
link(url: string) {
|
link(url: string) {
|
||||||
this.latest().click("open_url", url)
|
this.latest().click("open_url", url);
|
||||||
return this
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
latest() {
|
latest() {
|
||||||
return this.parts[this.parts.length - 1]
|
return this.parts[this.parts.length - 1];
|
||||||
}
|
}
|
||||||
|
|
||||||
json() {
|
json() {
|
||||||
if (!this.cache) {
|
if (!this.cache) {
|
||||||
var temp = []
|
var temp = [];
|
||||||
this.parts.forEach(t => {
|
this.parts.forEach(t => {
|
||||||
temp.push(t.convert())
|
temp.push(t.convert());
|
||||||
})
|
});
|
||||||
this.cache = JSON.stringify(temp)
|
this.cache = JSON.stringify(temp);
|
||||||
console.trace(this.cache)
|
console.trace(this.cache);
|
||||||
}
|
}
|
||||||
return this.cache
|
return this.cache;
|
||||||
}
|
}
|
||||||
|
|
||||||
string() {
|
string() {
|
||||||
var temp = ''
|
var temp = '';
|
||||||
this.parts.forEach(t => {
|
this.parts.forEach(t => {
|
||||||
temp += t.text
|
temp += t.text
|
||||||
})
|
});
|
||||||
return temp
|
return temp;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
const Thread = Java.type('java.lang.Thread')
|
|
||||||
const ThreadGroup = Java.type("java.lang.ThreadGroup")
|
|
||||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
|
||||||
const ThreadPoolExecutor = Java.type('java.util.concurrent.ThreadPoolExecutor')
|
|
||||||
const LinkedBlockingQueue = Java.type("java.util.concurrent.LinkedBlockingQueue")
|
|
||||||
|
|
||||||
interface ThreadPoolConfig {
|
|
||||||
corePoolSize?: number
|
|
||||||
maximumPoolSize?: number
|
|
||||||
keepAliveTime?: number
|
|
||||||
workQueueSize?: number
|
|
||||||
groupName: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export default {
|
|
||||||
create(config: ThreadPoolConfig): java.util.concurrent.ThreadPoolExecutor {
|
|
||||||
let threadCount = new AtomicInteger(0)
|
|
||||||
config = {
|
|
||||||
corePoolSize: 10,
|
|
||||||
maximumPoolSize: 100,
|
|
||||||
keepAliveTime: 60,
|
|
||||||
workQueueSize: 500,
|
|
||||||
...config
|
|
||||||
}
|
|
||||||
return new ThreadPoolExecutor(
|
|
||||||
config.corePoolSize, config.maximumPoolSize, config.keepAliveTime, Packages.java.util.concurrent.TimeUnit.SECONDS,
|
|
||||||
new LinkedBlockingQueue(config.workQueueSize),
|
|
||||||
(run: any) => new Thread(new ThreadGroup(config.groupName), run, config.groupName + "-" + threadCount.incrementAndGet()),
|
|
||||||
new ThreadPoolExecutor.CallerRunsPolicy()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
export type Version = [string, string, string]
|
|
||||||
|
|
||||||
export class VersionUtils {
|
|
||||||
static isEqual(version: string, targetVersion: string): boolean {
|
|
||||||
return version == targetVersion
|
|
||||||
}
|
|
||||||
static isGreaterOrEqual(version: string, targetVersion: string): boolean {
|
|
||||||
const v1 = parseVersion(version)
|
|
||||||
const v2 = parseVersion(targetVersion)
|
|
||||||
|
|
||||||
return (
|
|
||||||
v1[0] > v2[0] ||
|
|
||||||
(v1[0] === v2[0] && v1[1] > v2[1]) ||
|
|
||||||
(v1[0] === v2[0] && v1[1] === v2[1] && v1[2] >= v2[2])
|
|
||||||
)
|
|
||||||
}
|
|
||||||
static isGreater(version: string, targetVersion: string): boolean {
|
|
||||||
const v1 = parseVersion(version)
|
|
||||||
const v2 = parseVersion(targetVersion)
|
|
||||||
|
|
||||||
return (
|
|
||||||
v1[0] > v2[0] ||
|
|
||||||
(v1[0] === v2[0] && v1[1] > v2[1]) ||
|
|
||||||
(v1[0] === v2[0] && v1[1] === v2[1] && v1[2] > v2[2])
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseVersion(version: string = ""): Version {
|
|
||||||
const v: Version = ['0', '0', '0']
|
|
||||||
|
|
||||||
version.split(".").forEach((value, i) => (v[i] = value))
|
|
||||||
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/compile",
|
"name": "@ccms/compile",
|
||||||
"version": "0.28.0-beta.11",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript compile package",
|
"description": "MiaoScript compile package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -12,15 +12,15 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"files": [
|
|
||||||
"dist/**/*.js",
|
|
||||||
"dist/**/*.ts",
|
|
||||||
"dist/**/*.map"
|
|
||||||
],
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "pnpm clean && tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^3.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/container",
|
"name": "@ccms/container",
|
||||||
"version": "0.28.0-beta.11",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript container package",
|
"description": "MiaoScript container package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -12,22 +12,19 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"files": [
|
|
||||||
"dist/**/*.js",
|
|
||||||
"dist/**/*.ts",
|
|
||||||
"dist/**/*.map"
|
|
||||||
],
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "pnpm clean && tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
|
||||||
"inversify": "^6.0.1",
|
|
||||||
"inversify-binding-decorators": "^4.0.0"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "workspace:*"
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^3.8.3"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"inversify": "^5.0.1",
|
||||||
|
"inversify-binding-decorators": "^4.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
export namespace ioc {
|
|
||||||
export const Autowired = Symbol('Autowired')
|
|
||||||
export const Resource = Symbol('Resource')
|
|
||||||
export const JavaClass = Symbol('JavaClass')
|
|
||||||
export const JavaInstance = Symbol('JavaInstance')
|
|
||||||
export const JavaStaticClass = Symbol('JavaStaticClass')
|
|
||||||
}
|
|
||||||
@@ -1,64 +1,93 @@
|
|||||||
import { interfaces, Container } from "inversify"
|
import { interfaces, Container } from "inversify";
|
||||||
import { _proxyGetter } from "./utils"
|
|
||||||
|
|
||||||
let _container: Container
|
let _container: Container;
|
||||||
|
|
||||||
const ContainerInstance = Symbol.for("@ccms/ioc:Container")
|
const ContainerInstance = Symbol.for("@ccms/ioc:Container");
|
||||||
|
const INJECTION = Symbol.for("INJECTION");
|
||||||
|
|
||||||
|
function _proxyGetter(
|
||||||
|
proto: any,
|
||||||
|
key: string,
|
||||||
|
resolve: () => any,
|
||||||
|
doCache: boolean
|
||||||
|
) {
|
||||||
|
function getter(this: object) {
|
||||||
|
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
|
||||||
|
Reflect.defineMetadata(INJECTION, resolve(), this, key);
|
||||||
|
}
|
||||||
|
if (Reflect.hasMetadata(INJECTION, this, key)) {
|
||||||
|
return Reflect.getMetadata(INJECTION, this, key);
|
||||||
|
} else {
|
||||||
|
return resolve();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setter(this: object, newVal: any) {
|
||||||
|
Reflect.defineMetadata(INJECTION, newVal, this, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.defineProperty(proto, key, {
|
||||||
|
configurable: true,
|
||||||
|
enumerable: true,
|
||||||
|
get: getter,
|
||||||
|
set: setter
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function initContainer(container: Container) {
|
function initContainer(container: Container) {
|
||||||
Reflect.defineMetadata(ContainerInstance, container, Reflect)
|
Reflect.defineMetadata(ContainerInstance, container, Reflect);
|
||||||
return _container = container
|
_container = container;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getContainer(): Container {
|
function getContainer(): Container {
|
||||||
return _container || initContainer(new Container())
|
return _container || Reflect.getMetadata(ContainerInstance, Reflect)
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePropertyInjectDecorator(doCache: boolean) {
|
function makePropertyInjectDecorator(doCache: boolean) {
|
||||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||||
return function (proto: any, key: string): void {
|
return function(proto: any, key: string): void {
|
||||||
let resolve = () => {
|
let resolve = () => {
|
||||||
return getContainer().get(serviceIdentifier)
|
return getContainer().get(serviceIdentifier);
|
||||||
}
|
};
|
||||||
_proxyGetter(proto, key, resolve, doCache)
|
_proxyGetter(proto, key, resolve, doCache);
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePropertyInjectNamedDecorator(doCache: boolean) {
|
function makePropertyInjectNamedDecorator(doCache: boolean) {
|
||||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>, named: string) {
|
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>, named: string) {
|
||||||
return function (proto: any, key: string): void {
|
return function(proto: any, key: string): void {
|
||||||
let resolve = () => {
|
let resolve = () => {
|
||||||
return getContainer().getNamed(serviceIdentifier, named)
|
return getContainer().getNamed(serviceIdentifier, named);
|
||||||
}
|
};
|
||||||
_proxyGetter(proto, key, resolve, doCache)
|
_proxyGetter(proto, key, resolve, doCache);
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePropertyInjectTaggedDecorator(doCache: boolean) {
|
function makePropertyInjectTaggedDecorator(doCache: boolean) {
|
||||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>, key: string, value: any) {
|
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>, key: string, value: any) {
|
||||||
return function (proto: any, propertyName: string): void {
|
return function(proto: any, propertyName: string): void {
|
||||||
let resolve = () => {
|
let resolve = () => {
|
||||||
return getContainer().getTagged(serviceIdentifier, key, value)
|
return getContainer().getTagged(serviceIdentifier, key, value);
|
||||||
}
|
};
|
||||||
_proxyGetter(proto, propertyName, resolve, doCache)
|
_proxyGetter(proto, propertyName, resolve, doCache);
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePropertyMultiInjectDecorator(doCache: boolean) {
|
function makePropertyMultiInjectDecorator(doCache: boolean) {
|
||||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||||
return function (proto: any, key: string): void {
|
return function(proto: any, key: string): void {
|
||||||
let resolve = () => {
|
let resolve = () => {
|
||||||
return getContainer().getAll(serviceIdentifier)
|
return getContainer().getAll(serviceIdentifier);
|
||||||
}
|
};
|
||||||
_proxyGetter(proto, key, resolve, doCache)
|
_proxyGetter(proto, key, resolve, doCache);
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
let doCache = true
|
let doCache = true;
|
||||||
|
|
||||||
let lazyInject = makePropertyInjectDecorator(doCache)
|
let lazyInject = makePropertyInjectDecorator(doCache)
|
||||||
let lazyInjectNamed = makePropertyInjectNamedDecorator(doCache)
|
let lazyInjectNamed = makePropertyInjectNamedDecorator(doCache)
|
||||||
@@ -73,4 +102,4 @@ export {
|
|||||||
lazyInjectNamed,
|
lazyInjectNamed,
|
||||||
lazyInjectTagged,
|
lazyInjectTagged,
|
||||||
lazyMultiInject
|
lazyMultiInject
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -1,180 +1,25 @@
|
|||||||
/// <reference types="@ccms/nashorn" />
|
import "reflect-metadata";
|
||||||
|
import { initContainer } from './decorators'
|
||||||
|
import { interfaces, Container } from 'inversify';
|
||||||
|
import { fluentProvide } from 'inversify-binding-decorators';
|
||||||
|
|
||||||
import "reflect-metadata"
|
const provideNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
|
||||||
import { initContainer, getContainer } from './decorators'
|
return fluentProvide(identifier).whenTargetNamed(name).done();
|
||||||
import { interfaces, Container, inject, named } from 'inversify'
|
};
|
||||||
import { fluentProvide } from 'inversify-binding-decorators'
|
|
||||||
import { ioc } from "./constants"
|
|
||||||
import { _proxyGetter } from "./utils"
|
|
||||||
|
|
||||||
/**
|
const provideSingleton = (identifier: interfaces.ServiceIdentifier<any>) => {
|
||||||
* 注册一个命名对象
|
return fluentProvide(identifier).inSingletonScope().done();
|
||||||
* @param identifier 标识符
|
};
|
||||||
* @param name 名称
|
|
||||||
*/
|
|
||||||
export const provideNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
|
|
||||||
return fluentProvide(identifier).whenTargetNamed(name).done()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
const DefaultContainer = new Container();
|
||||||
* 注册一个单例对象
|
initContainer(DefaultContainer);
|
||||||
* @param identifier 标识符
|
|
||||||
*/
|
|
||||||
export const provideSingleton = (identifier: interfaces.ServiceIdentifier<any>) => {
|
|
||||||
return fluentProvide(identifier).inSingletonScope().done()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 注册一个单例对象
|
|
||||||
* @param identifier 标识符
|
|
||||||
*/
|
|
||||||
export const provideSingletonNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
|
|
||||||
return fluentProvide(identifier).inSingletonScope().whenTargetNamed(name).done()
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getJavaClass(className: string) {
|
|
||||||
try { return Java.type(className).class; return } catch (error: any) { }
|
|
||||||
try { return base.getClass(className); return } catch (error: any) { }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获得一个 java.lang.Class
|
|
||||||
* @param className Java全类名
|
|
||||||
*/
|
|
||||||
export const JavaClass = (className: string) => {
|
|
||||||
return function (target: object, propertyKey: string, index?: number) {
|
|
||||||
_proxyGetter(target, propertyKey, () => {
|
|
||||||
return getJavaClass(className) || console.warn('JavaClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
|
||||||
}, true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getJSClass(className: string) {
|
|
||||||
try { return Java.type(className) } catch (error: any) { }
|
|
||||||
try { return base.getClass(className).static } catch (error: any) { }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获得一个JS的Java类
|
|
||||||
* @param className Java 全类名
|
|
||||||
*/
|
|
||||||
export const JSClass = (className: string) => {
|
|
||||||
return function (target: object, propertyKey: string, index?: number) {
|
|
||||||
_proxyGetter(target, propertyKey, () => {
|
|
||||||
return getJSClass(className) || console.warn('JSClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
|
||||||
}, true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 自动注入实例由平台实现
|
|
||||||
* @param className 类名
|
|
||||||
*/
|
|
||||||
export const Autowired = (className?: any) => {
|
|
||||||
return function (target: any, propertyKey: string, index?: number) {
|
|
||||||
let container = getContainer()
|
|
||||||
if (className && (className instanceof Symbol || className instanceof Function)) {
|
|
||||||
return inject(className)(target, propertyKey, index)
|
|
||||||
}
|
|
||||||
let type = Reflect.getMetadata('design:type', target, propertyKey)
|
|
||||||
if (type && type !== Object && !Java.isJavaObject(type)) {
|
|
||||||
inject(type)(target, propertyKey, index)
|
|
||||||
named(className || propertyKey)(target, propertyKey, index)
|
|
||||||
} else if (container.isBound(ioc.Autowired)) {
|
|
||||||
console.debug('Autowired', 'ioc.Autowired', 'named', className || propertyKey)
|
|
||||||
target[propertyKey] = container.getNamed(ioc.Autowired, className || propertyKey)
|
|
||||||
} else {
|
|
||||||
throw new Error(`No matching bindings found for target: ${target.constructor.name} type: ${type} named: ${className || propertyKey}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 自动注入资源由平台实现
|
|
||||||
* @param className 类名
|
|
||||||
*/
|
|
||||||
export const Resource = (resourceName?: string | any) => {
|
|
||||||
return function (target: any, propertyKey: string, index?: number) {
|
|
||||||
target[propertyKey] = getContainer().getNamed(ioc.Resource, resourceName || propertyKey)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const DocumentBuilderFactory = Java.type('javax.xml.parsers.DocumentBuilderFactory')
|
|
||||||
|
|
||||||
export const MavenDepend = (groupId: string, artifactId: string, version: string, recursion = false) => {
|
|
||||||
return function (target: any) {
|
|
||||||
loadMavenDepend(groupId, artifactId, version, recursion)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const loadedMavenDepend = new Set<string>()
|
|
||||||
|
|
||||||
export function loadMavenDepend(groupId: string, artifactId: string, version: string, recursion = false) {
|
|
||||||
const key = `${groupId}:${artifactId}:${version}`
|
|
||||||
try {
|
|
||||||
if (loadedMavenDepend.has(key)) { return }
|
|
||||||
console.info('loading maven dependency', key)
|
|
||||||
let [pom, _] = base.loadMavenDepend(groupId, artifactId, version)
|
|
||||||
loadedMavenDepend.add(key)
|
|
||||||
if (recursion) {
|
|
||||||
let doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(pom)
|
|
||||||
let dependencies = doc.getElementsByTagName("dependency")
|
|
||||||
let size = dependencies.length
|
|
||||||
if (!size) { return }
|
|
||||||
console.debug(key, 'found', size, 'dependencies loading...')
|
|
||||||
for (let i = 0; i < size; i++) {
|
|
||||||
const dependency = dependencies.item(i)
|
|
||||||
const gav = dependency.getChildNodes()
|
|
||||||
const length = gav.length
|
|
||||||
const dependencyVersion = { groupId: '', artifactId: '', version: '' }
|
|
||||||
for (let j = 0; j < length; j++) {
|
|
||||||
const prop = gav.item(j)
|
|
||||||
switch (prop.getNodeName()) {
|
|
||||||
case "groupId":
|
|
||||||
dependencyVersion.groupId = prop.getTextContent()
|
|
||||||
break
|
|
||||||
case "artifactId":
|
|
||||||
dependencyVersion.artifactId = prop.getTextContent()
|
|
||||||
break
|
|
||||||
case "version":
|
|
||||||
dependencyVersion.version = prop.getTextContent()
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
loadMavenDepend(dependencyVersion.groupId, dependencyVersion.artifactId, dependencyVersion.version, recursion)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
console.warn('load maven dependency', key, 'failed. Error:', error)
|
|
||||||
if (global.debug) {
|
|
||||||
console.ex(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const reduceMetadata = (ctx: interfaces.Context): any => {
|
|
||||||
return ctx.currentRequest.target.metadata.reduce((result, entry, index) => {
|
|
||||||
result[entry.key] = entry.value
|
|
||||||
return result
|
|
||||||
}, {})
|
|
||||||
}
|
|
||||||
|
|
||||||
function initAutowired(container: Container) {
|
|
||||||
container.bind(ioc.Autowired).toDynamicValue((ctx) => {
|
|
||||||
var metadata: any = reduceMetadata(ctx)
|
|
||||||
let key = Object.prototype.toString.call(metadata.named)
|
|
||||||
if (key === "[object Function]" || key === "[object Symbol]") { return container.get(metadata.named) }
|
|
||||||
console.warn('container Autowired', metadata.named, 'failed. Error: illegal serviceIdentifier type', key)
|
|
||||||
console.debug(metadata.named, 'metadata', JSON.stringify(metadata))
|
|
||||||
return undefined
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DefaultContainer = new Container()
|
|
||||||
initContainer(DefaultContainer)
|
|
||||||
initAutowired(DefaultContainer)
|
|
||||||
|
|
||||||
export * from 'inversify'
|
export * from 'inversify'
|
||||||
export * from './constants'
|
|
||||||
export * from './decorators'
|
export * from './decorators'
|
||||||
export * from 'inversify-binding-decorators'
|
export * from 'inversify-binding-decorators'
|
||||||
|
export {
|
||||||
|
fluentProvide,
|
||||||
|
provideNamed,
|
||||||
|
provideSingleton,
|
||||||
|
DefaultContainer
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
const INJECTION = Symbol.for("INJECTION")
|
|
||||||
|
|
||||||
export function _proxyGetter(
|
|
||||||
proto: any,
|
|
||||||
key: string,
|
|
||||||
resolve: () => any,
|
|
||||||
doCache: boolean
|
|
||||||
) {
|
|
||||||
function getter(this: object) {
|
|
||||||
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
|
|
||||||
Reflect.defineMetadata(INJECTION, resolve(), this, key)
|
|
||||||
}
|
|
||||||
if (Reflect.hasMetadata(INJECTION, this, key)) {
|
|
||||||
return Reflect.getMetadata(INJECTION, this, key)
|
|
||||||
} else {
|
|
||||||
return resolve()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function setter(this: object, newVal: any) {
|
|
||||||
Reflect.defineMetadata(INJECTION, newVal, this, key)
|
|
||||||
}
|
|
||||||
|
|
||||||
Object.defineProperty(proto, key, {
|
|
||||||
configurable: true,
|
|
||||||
enumerable: true,
|
|
||||||
get: getter,
|
|
||||||
set: setter
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/core",
|
"name": "@ccms/core",
|
||||||
"version": "0.28.0-beta.11",
|
"version": "0.6.1",
|
||||||
"description": "MiaoScript core package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
"minecraft",
|
"minecraft",
|
||||||
@@ -12,28 +12,20 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"files": [
|
|
||||||
"dist/**/*.js",
|
|
||||||
"dist/**/*.ts",
|
|
||||||
"dist/**/*.map"
|
|
||||||
],
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "pnpm rollup -c rollup.config.js --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "pnpm clean && pnpm rollup -c rollup.config.js",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@rollup/plugin-typescript": "^11.1.6",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rollup": "^2.79.2",
|
"rimraf": "^3.0.2",
|
||||||
"rollup-obfuscator": "^3.0.2",
|
"typescript": "^3.8.3"
|
||||||
"rollup-plugin-peer-deps-external": "^2.2.4"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "workspace:*",
|
"@ccms/api": "^0.6.1",
|
||||||
"@ccms/common": "workspace:*",
|
"@ccms/container": "^0.6.0"
|
||||||
"@ccms/container": "workspace:*",
|
|
||||||
"js-yaml": "^4.1.0"
|
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,49 +0,0 @@
|
|||||||
import typescript from '@rollup/plugin-typescript'
|
|
||||||
import peerDepsExternal from 'rollup-plugin-peer-deps-external'
|
|
||||||
import { obfuscator } from 'rollup-obfuscator'
|
|
||||||
|
|
||||||
import pkg from './package.json'
|
|
||||||
|
|
||||||
const external = ['path', 'fs', 'typescript', 'tslib']
|
|
||||||
/**
|
|
||||||
* @type {import('rollup').RollupOptions}
|
|
||||||
*/
|
|
||||||
export default {
|
|
||||||
input: 'src/index.ts',
|
|
||||||
plugins: [
|
|
||||||
peerDepsExternal(),
|
|
||||||
typescript(),
|
|
||||||
obfuscator({
|
|
||||||
compact: true,
|
|
||||||
deadCodeInjection: true,
|
|
||||||
deadCodeInjectionThreshold: 1,
|
|
||||||
identifierNamesGenerator: 'mangled-shuffled',
|
|
||||||
numbersToExpressions: true,
|
|
||||||
simplify: true,
|
|
||||||
stringArray: true,
|
|
||||||
stringArrayThreshold: 1,
|
|
||||||
stringArrayEncoding: ['rc4'],
|
|
||||||
stringArrayCallsTransform: true,
|
|
||||||
stringArrayCallsTransformThreshold: 1,
|
|
||||||
stringArrayWrappersChainedCalls: true,
|
|
||||||
stringArrayWrappersParametersMaxCount: 3,
|
|
||||||
sourceMap: true,
|
|
||||||
sourceMapSourcesMode: 'sources',
|
|
||||||
inputFileName: `${pkg.name}.ts`,
|
|
||||||
transformObjectKeys: true,
|
|
||||||
unicodeEscapeSequence: true,
|
|
||||||
target: 'browser-no-eval'
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
external,
|
|
||||||
treeshake: false,
|
|
||||||
output: [
|
|
||||||
{
|
|
||||||
format: 'cjs',
|
|
||||||
interop: "auto",
|
|
||||||
exports: "named",
|
|
||||||
sourcemap: true,
|
|
||||||
file: pkg.main || `dist/${pkg.name}.js`
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
1
packages/core/src/.gitignore
vendored
1
packages/core/src/.gitignore
vendored
@@ -1 +0,0 @@
|
|||||||
script
|
|
||||||
@@ -1,163 +1,103 @@
|
|||||||
let containerStartTime = Date.now()
|
let containerStartTime = Date.now();
|
||||||
console.i18n("ms.core.ioc.initialize", { scope: global.scope })
|
console.i18n("ms.core.ioc.initialize", { scope: global.scope });
|
||||||
import { plugin, server, task, constants, console as jsconsole } from '@ccms/api'
|
import { plugin, server, task, constants } from '@ccms/api'
|
||||||
import { DefaultContainer as container, provideSingleton, ContainerInstance, buildProviderModule, Autowired } from '@ccms/container'
|
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule } from '@ccms/container'
|
||||||
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
|
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
|
||||||
import * as yaml from 'js-yaml'
|
|
||||||
import http from '@ccms/common/dist/http'
|
|
||||||
import * as fs from '@ccms/common/dist/fs'
|
|
||||||
|
|
||||||
const UUID = Java.type('java.util.UUID')
|
|
||||||
const MiaoScriptAPI = Java.type('pw.yumc.MiaoScript.api.MiaoScriptAPI')
|
|
||||||
|
|
||||||
@provideSingleton(MiaoScriptCore)
|
@provideSingleton(MiaoScriptCore)
|
||||||
class MiaoScriptCore {
|
class MiaoScriptCore {
|
||||||
@Autowired(server.Console)
|
@inject(server.Console)
|
||||||
private Console: Console
|
private Console: Console;
|
||||||
@Autowired()
|
@inject(task.TaskManager)
|
||||||
private pluginManager: plugin.PluginManager
|
private taskManager: task.TaskManager;
|
||||||
|
@inject(plugin.PluginFolder)
|
||||||
|
private pluginFolder: string;
|
||||||
|
@inject(plugin.PluginManager)
|
||||||
|
private pluginManager: plugin.PluginManager;
|
||||||
|
|
||||||
enable() {
|
enable() {
|
||||||
process.emit('core.before.enable', this)
|
this.loadServerConsole();
|
||||||
this.loadServerConsole()
|
this.loadTaskFunction();
|
||||||
try {
|
global.level = "TRACE"
|
||||||
MiaoScriptAPI.setPluginManager(this.pluginManager)
|
this.loadPlugins();
|
||||||
} catch (error) {
|
return () => this.disable();
|
||||||
}
|
|
||||||
process.emit('core.enable', this)
|
|
||||||
process.emit('core.after.enable', this)
|
|
||||||
console.i18n("ms.core.engine.completed", {
|
|
||||||
loader: base.version,
|
|
||||||
version: 'v' + global.ScriptEngineVersion,
|
|
||||||
time: (Date.now() - global.ScriptEngineStartTime) / 1000
|
|
||||||
})
|
|
||||||
return () => this.disable()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
loadServerConsole() {
|
loadServerConsole() {
|
||||||
process.emit('core.before.load.console', this)
|
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
global.setGlobal('console', new this.Console(), { writable: false, configurable: false })
|
global.setGlobal('console', new this.Console())
|
||||||
process.emit('core.after.load.console', this)
|
}
|
||||||
|
|
||||||
|
loadTaskFunction() {
|
||||||
|
global.setGlobal('setTimeout', (func: Function, tick: number, async: boolean = false) => this.taskManager.create(func).later(tick).async(async).submit())
|
||||||
|
global.setGlobal('setInterval', (func: Function, tick: number, async: boolean = false) => this.taskManager.create(func).timer(tick).async(async).submit())
|
||||||
|
}
|
||||||
|
|
||||||
|
loadPlugins() {
|
||||||
|
let loadPluginStartTime = new Date().getTime()
|
||||||
|
console.i18n("ms.core.plugin.initialize")
|
||||||
|
this.pluginManager.scan(this.pluginFolder);
|
||||||
|
this.pluginManager.build();
|
||||||
|
this.pluginManager.load();
|
||||||
|
this.pluginManager.enable();
|
||||||
|
console.i18n("ms.core.plugin.completed", { time: (new Date().getTime() - loadPluginStartTime) / 1000 })
|
||||||
}
|
}
|
||||||
|
|
||||||
disable() {
|
disable() {
|
||||||
process.emit('core.before.disable', this)
|
|
||||||
let disableStartTime = Date.now()
|
|
||||||
console.i18n("ms.core.engine.disable")
|
console.i18n("ms.core.engine.disable")
|
||||||
process.emit('core.disable', this)
|
this.pluginManager.disable();
|
||||||
process.emit('core.after.disable', this)
|
this.taskManager.disable();
|
||||||
loadCoreScript('exit')
|
//@ts-ignore
|
||||||
process.emit('core.before.exit', this)
|
require.disable()
|
||||||
process.exit(0)
|
|
||||||
process.emit('core.exit', this)
|
|
||||||
console.i18n("ms.core.engine.disable.finish", {
|
|
||||||
loader: base.version,
|
|
||||||
version: 'v' + global.ScriptEngineVersion,
|
|
||||||
time: (new Date().getTime() - disableStartTime) / 1000
|
|
||||||
})
|
|
||||||
process.emit('core.after.exit', this)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function detectServer(): constants.ServerType {
|
function detectServer(): constants.ServerType {
|
||||||
try {
|
try {
|
||||||
Java.type("org.bukkit.Bukkit")
|
Java.type("org.bukkit.Bukkit");
|
||||||
return constants.ServerType.Bukkit
|
return constants.ServerType.Bukkit
|
||||||
} catch (ex: any) {
|
} catch (ex) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Java.type("org.spongepowered.api.Sponge")
|
Java.type("org.spongepowered.api.Sponge");
|
||||||
return constants.ServerType.Sponge
|
return constants.ServerType.Sponge
|
||||||
} catch (ex: any) {
|
} catch (ex) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Java.type("cn.nukkit.Nukkit")
|
Java.type("cn.nukkit.Nukkit");
|
||||||
return constants.ServerType.Nukkit
|
return constants.ServerType.Nukkit
|
||||||
} catch (ex: any) {
|
} catch (ex) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Java.type("net.md_5.bungee.api.ProxyServer")
|
Java.type("net.md_5.bungee.api.ProxyServer");
|
||||||
return constants.ServerType.Bungee
|
return constants.ServerType.Bungee
|
||||||
} catch (ex: any) {
|
} catch (ex) {
|
||||||
}
|
|
||||||
try {
|
|
||||||
Java.type("org.springframework.boot.SpringApplication")
|
|
||||||
return constants.ServerType.Spring
|
|
||||||
} catch (ex: any) {
|
|
||||||
}
|
}
|
||||||
throw Error('Unknow Server Type...')
|
throw Error('Unknow Server Type...')
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadCoreScript(name) {
|
|
||||||
try {
|
|
||||||
let scriptname = name + (global.debug ? '-debug' : '')
|
|
||||||
engineLoad({
|
|
||||||
script: http.get(`https://mscript.yumc.pw/api/plugin/download/name/${scriptname}`),
|
|
||||||
name: `core/${scriptname}.js`
|
|
||||||
})
|
|
||||||
} catch (error: any) {
|
|
||||||
if (global.debug) {
|
|
||||||
console.debug(error)
|
|
||||||
console.ex(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadMiaoScriptConfig() {
|
|
||||||
let configFile = fs.concat(root, 'config.yml')
|
|
||||||
if (!fs.exists(configFile)) {
|
|
||||||
global.ScriptEngineConfig = base.save(configFile, yaml.dump({
|
|
||||||
uuid: UUID.randomUUID().toString(),
|
|
||||||
slow_execute: 50
|
|
||||||
}))
|
|
||||||
} else {
|
|
||||||
global.ScriptEngineConfig = yaml.load(base.read(configFile))
|
|
||||||
}
|
|
||||||
global.ScriptSlowExecuteTime = global.ScriptEngineConfig.slow_execute || 50
|
|
||||||
}
|
|
||||||
|
|
||||||
function createCore() {
|
|
||||||
let corePackageStartTime = new Date().getTime()
|
|
||||||
container.bind(ContainerInstance).toConstantValue(container)
|
|
||||||
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance())
|
|
||||||
container.bind(plugin.PluginFolder).toConstantValue('plugins')
|
|
||||||
let type = detectServer()
|
|
||||||
|
|
||||||
process.emit('core.before.initialize.detect')
|
|
||||||
console.i18n("ms.core.initialize.detect", { scope: global.scope, type })
|
|
||||||
container.bind(server.ServerType).toConstantValue(type)
|
|
||||||
container.bind(server.ServerChecker).toSelf().inSingletonScope()
|
|
||||||
container.bind(server.NativePluginManager).toSelf().inSingletonScope()
|
|
||||||
container.bind(server.NativePluginChecker).toSelf().inSingletonScope()
|
|
||||||
process.emit('core.after.initialize.detect')
|
|
||||||
|
|
||||||
process.emit('core.before.package.initialize')
|
|
||||||
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
|
|
||||||
require(`${global.scope}/${type}`).default(container)
|
|
||||||
require(`${global.scope}/plugin`)
|
|
||||||
container.load(buildProviderModule())
|
|
||||||
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 })
|
|
||||||
process.emit('core.after.package.initialize')
|
|
||||||
return container.get<MiaoScriptCore>(MiaoScriptCore)
|
|
||||||
}
|
|
||||||
|
|
||||||
function initialize() {
|
function initialize() {
|
||||||
process.emit('core.before.initialize')
|
|
||||||
loadMiaoScriptConfig()
|
|
||||||
global.ScriptEngineVersion = require('../package.json').version
|
|
||||||
global.setGlobal('loadCoreScript', loadCoreScript)
|
|
||||||
loadCoreScript('initialize')
|
|
||||||
try {
|
try {
|
||||||
return createCore()
|
let corePackageStartTime = new Date().getTime()
|
||||||
} catch (error: any) {
|
container.bind(ContainerInstance).toConstantValue(container);
|
||||||
console.i18n("core.initialize.error", { error })
|
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance());
|
||||||
jsconsole.getStackTrace(error, false).forEach(line => console.log(line))
|
container.bind(plugin.PluginFolder).toConstantValue('plugins');
|
||||||
process.emit('core.initialize.error')
|
let type = detectServer();
|
||||||
return { enable: () => () => console.i18n('ms.core.engine.disable.abnormal') }
|
console.i18n("ms.core.initialize.detect", { scope: global.scope, type });
|
||||||
} finally {
|
container.bind(server.ServerType).toConstantValue(type);
|
||||||
process.emit('core.after.initialize')
|
console.i18n("ms.core.package.initialize", { scope: global.scope, type });
|
||||||
|
require(`${global.scope}/${type}`).default(container);
|
||||||
|
require(`${global.scope}/plugin`)
|
||||||
|
container.load(buildProviderModule());
|
||||||
|
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 });
|
||||||
|
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
||||||
|
console.i18n("ms.core.engine.completed", { time: (Date.now() - global.NashornEngineStartTime) / 1000 });
|
||||||
|
return disable;
|
||||||
|
} catch (error) {
|
||||||
|
console.i18n("ms.core.initialize.error", { error });
|
||||||
|
console.ex(error)
|
||||||
|
return () => console.i18n('ms.core.engine.disable.abnormal')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default initialize()
|
export default initialize();
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "@ccms/database",
|
|
||||||
"version": "0.28.0-beta.11",
|
|
||||||
"description": "MiaoScript database package",
|
|
||||||
"keywords": [
|
|
||||||
"miaoscript",
|
|
||||||
"minecraft",
|
|
||||||
"bukkit",
|
|
||||||
"sponge"
|
|
||||||
],
|
|
||||||
"author": "MiaoWoo <admin@yumc.pw>",
|
|
||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
|
||||||
"license": "ISC",
|
|
||||||
"main": "dist/index.js",
|
|
||||||
"files": [
|
|
||||||
"dist/**/*.js",
|
|
||||||
"dist/**/*.ts",
|
|
||||||
"dist/**/*.map"
|
|
||||||
],
|
|
||||||
"scripts": {
|
|
||||||
"clean": "rimraf dist",
|
|
||||||
"watch": "tsc --watch",
|
|
||||||
"build": "pnpm clean && tsc",
|
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@javatypes/spring-jdbc": "^0.0.3"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@ccms/api": "workspace:*",
|
|
||||||
"@ccms/container": "workspace:*"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
export const METADATA_KEY = {
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
import { database } from '@ccms/api'
|
|
||||||
import { JSClass } from '@ccms/container'
|
|
||||||
|
|
||||||
const Thread = Java.type('java.lang.Thread')
|
|
||||||
const JavaString = Java.type('java.lang.String')
|
|
||||||
const Properties = Java.type('java.util.Properties')
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 数据库封装类
|
|
||||||
*/
|
|
||||||
export class DataBase extends database.DataBase {
|
|
||||||
private dataSource: javax.sql.DataSource
|
|
||||||
private jdbcTemplate: org.springframework.jdbc.core.JdbcTemplate
|
|
||||||
|
|
||||||
@JSClass('com.zaxxer.hikari.HikariDataSource')
|
|
||||||
private HikariDataSource: any
|
|
||||||
@JSClass('com.zaxxer.hikari.HikariConfig')
|
|
||||||
private HikariConfig: any
|
|
||||||
@JSClass('org.springframework.jdbc.core.JdbcTemplate')
|
|
||||||
private JdbcTemplate: typeof org.springframework.jdbc.core.JdbcTemplate
|
|
||||||
|
|
||||||
constructor(dbConfig: database.DataBaseConfig) {
|
|
||||||
super()
|
|
||||||
if (!dbConfig.url) { throw new Error('DataBase url can\'t be null!') }
|
|
||||||
this.createDataSource(dbConfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
private createDataSource(dbConfig: database.DataBaseConfig) {
|
|
||||||
if (typeof dbConfig.url === "string") {
|
|
||||||
let originClassLoader = Thread.currentThread().getContextClassLoader()
|
|
||||||
Thread.currentThread().setContextClassLoader(base.getInstance().class.classLoader)
|
|
||||||
let config = new this.HikariConfig()
|
|
||||||
if (dbConfig.driverClassName) {
|
|
||||||
config.setDriverClassName(dbConfig.driverClassName)
|
|
||||||
} else {
|
|
||||||
switch (dbConfig.type) {
|
|
||||||
case "h2":
|
|
||||||
config.setDriverClassName("org.h2.Driver")
|
|
||||||
break
|
|
||||||
case "sqlite":
|
|
||||||
config.setDriverClassName("org.sqlite.JDBC")
|
|
||||||
break
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (dbConfig.username) {
|
|
||||||
config.setUsername(dbConfig.username)
|
|
||||||
}
|
|
||||||
if (dbConfig.password) {
|
|
||||||
config.setPassword(dbConfig.password)
|
|
||||||
}
|
|
||||||
config.setJdbcUrl(dbConfig.url)
|
|
||||||
if (dbConfig.properties) {
|
|
||||||
let properties = new Properties()
|
|
||||||
for (const key in dbConfig.properties) {
|
|
||||||
properties.setProperty(key, dbConfig.properties[key])
|
|
||||||
}
|
|
||||||
config.setDataSourceProperties(properties)
|
|
||||||
}
|
|
||||||
console.debug('createDataSource from config ' + JSON.stringify(dbConfig))
|
|
||||||
this.dataSource = new this.HikariDataSource(config)
|
|
||||||
Thread.currentThread().setContextClassLoader(originClassLoader)
|
|
||||||
} else {
|
|
||||||
this.dataSource = dbConfig.url
|
|
||||||
}
|
|
||||||
this.jdbcTemplate = new this.JdbcTemplate(this.dataSource)
|
|
||||||
}
|
|
||||||
|
|
||||||
getDataSource() {
|
|
||||||
return this.dataSource
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 执行SQL查询
|
|
||||||
* @param sql SQL语句
|
|
||||||
* @param args 参数
|
|
||||||
*/
|
|
||||||
query<T>(sql: string, ...args: any[]): Array<T> {
|
|
||||||
let startTime = Date.now()
|
|
||||||
let result = Java.from<any>(this.jdbcTemplate.queryForList(sql, args))
|
|
||||||
console.debug(JavaString.format(`\n[DB] query \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 执行SQL更新
|
|
||||||
* @param sql SQL语句
|
|
||||||
* @param args 参数
|
|
||||||
*/
|
|
||||||
update(sql: string, ...args: any[]): number {
|
|
||||||
let startTime = Date.now()
|
|
||||||
let result = this.jdbcTemplate.update(sql, args)
|
|
||||||
console.debug(JavaString.format(`\n[DB] update \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 执行SQL语句
|
|
||||||
* @param sql SQL语句
|
|
||||||
*/
|
|
||||||
execute(sql: string): void {
|
|
||||||
let startTime = Date.now()
|
|
||||||
this.jdbcTemplate.execute(sql)
|
|
||||||
console.debug(`\n[DB] execute \nSQL : ${sql} \nCOST : ${Date.now() - startTime}ms`)
|
|
||||||
}
|
|
||||||
|
|
||||||
close() {
|
|
||||||
//@ts-ignore
|
|
||||||
this.dataSource.close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
/// <reference types="@ccms/nashorn" />
|
|
||||||
/// <reference types="@javatypes/jdk" />
|
|
||||||
/// <reference types="@javatypes/spring-jdbc" />
|
|
||||||
|
|
||||||
import { loadMavenDepend } from '@ccms/container'
|
|
||||||
|
|
||||||
loadMavenDepend('com.h2database', 'h2', '2.1.212')
|
|
||||||
loadMavenDepend("com.zaxxer", "HikariCP", "4.0.3")
|
|
||||||
loadMavenDepend("org.springframework", "spring-jdbc", "5.3.19", true)
|
|
||||||
|
|
||||||
export * from './database'
|
|
||||||
export * from './manager'
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
import { database } from '@ccms/api'
|
|
||||||
import { JSClass, provideSingleton } from '@ccms/container'
|
|
||||||
import { DataBase } from './database'
|
|
||||||
|
|
||||||
@provideSingleton(database.DataBaseManager)
|
|
||||||
export class DataBaseManager extends database.DataBaseManager {
|
|
||||||
private mainDatabase: DataBase
|
|
||||||
private databases = new Map<string, DataBase>()
|
|
||||||
|
|
||||||
@JSClass('org.h2.tools.Server')
|
|
||||||
private Server: any
|
|
||||||
|
|
||||||
private webManager: any
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
super()
|
|
||||||
process.on('exit', () => this.shutdown())
|
|
||||||
}
|
|
||||||
|
|
||||||
startWebManager(...args: string[]) {
|
|
||||||
this.webManager = this.Server.createWebServer(args)
|
|
||||||
this.webManager.start()
|
|
||||||
}
|
|
||||||
|
|
||||||
stopWebManager() {
|
|
||||||
if (this.webManager) {
|
|
||||||
this.webManager.stop()
|
|
||||||
this.webManager.shutdown()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
shutdown() {
|
|
||||||
this.stopWebManager()
|
|
||||||
this.disable()
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* 设置主数据库
|
|
||||||
* @param mainDatabase 主数据库
|
|
||||||
*/
|
|
||||||
setMainDatabase(mainDatabase: DataBase) {
|
|
||||||
this.mainDatabase = mainDatabase
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获得主数据库
|
|
||||||
* Get MainDatabase
|
|
||||||
*/
|
|
||||||
getMainDatabase() {
|
|
||||||
return this.mainDatabase
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 创建数据库
|
|
||||||
* Create A Database Instance
|
|
||||||
* @param name 数据库名称 用于代码 database Name use at code
|
|
||||||
* @param config 数据库配置
|
|
||||||
*/
|
|
||||||
createDatabase(name: string, config: database.DataBaseConfig) {
|
|
||||||
return Java.synchronized(() => {
|
|
||||||
if (!this.databases.has(name)) {
|
|
||||||
this.databases.set(name, new DataBase(config))
|
|
||||||
}
|
|
||||||
return this.databases.get(name)
|
|
||||||
}, this.databases)()
|
|
||||||
}
|
|
||||||
|
|
||||||
removeDatabase(name: string) {
|
|
||||||
if (this.databases.has(name)) {
|
|
||||||
this.databases.get(name).close()
|
|
||||||
}
|
|
||||||
return this.databases.delete(name)
|
|
||||||
}
|
|
||||||
|
|
||||||
getDatabase(name: string) {
|
|
||||||
return this.databases.get(name)
|
|
||||||
}
|
|
||||||
|
|
||||||
disable() {
|
|
||||||
this.databases.forEach((db) => db.close())
|
|
||||||
this.databases.clear()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
ms.i18n.completed: "Internationalization component initialization completed. Current Language: English"
|
ms.ployfill.initialize: "Initialization Java Nashorn ployfill. Please wait..."
|
||||||
ms.polyfill.initialize: "Initialization Java Nashorn polyfill. Please wait..."
|
ms.ployfill.completed: "Java Nashorn ployfill loading completed... Cost ({time}s)!"
|
||||||
ms.polyfill.completed: "Java Nashorn polyfill loading completed... Cost ({time}s)!"
|
|
||||||
|
|
||||||
ms.core.ioc.initialize: "Initialization MiaoScript IOC Container {scope}/container. Please wait..."
|
ms.core.ioc.initialize: "Initialization MiaoScript IOC Container {scope}/container. Please wait..."
|
||||||
ms.core.ioc.completed: "MiaoScript IOC Container {scope}/container loading completed({time}s)!"
|
ms.core.ioc.completed: "MiaoScript IOC Container {scope}/container loading completed({time}s)!"
|
||||||
@@ -12,7 +11,6 @@ ms.core.plugin.initialize: "Initialization MiaoScript Plugin System. Please wait
|
|||||||
ms.core.plugin.completed: "MiaoScript Plugin System loading completed({time}s)!"
|
ms.core.plugin.completed: "MiaoScript Plugin System loading completed({time}s)!"
|
||||||
ms.core.engine.completed: "MiaoScript ScriptEngine loading completed... Done({time}s)!"
|
ms.core.engine.completed: "MiaoScript ScriptEngine loading completed... Done({time}s)!"
|
||||||
ms.core.engine.disable: "Disable MiaoScript Engine..."
|
ms.core.engine.disable: "Disable MiaoScript Engine..."
|
||||||
ms.core.engine.disable.finish: "MiaoScript framework {loader} engine {version} 关闭完成... 耗时({time}s)!"
|
|
||||||
ms.core.engine.disable.abnormal: "abnormal Initialization MiaoScript Engine. Skip disable step..."
|
ms.core.engine.disable.abnormal: "abnormal Initialization MiaoScript Engine. Skip disable step..."
|
||||||
|
|
||||||
ms.api.event.resource.not.found: "Can't Mapping Event Because not found Resources {resource}!"
|
ms.api.event.resource.not.found: "Can't Mapping Event Because not found Resources {resource}!"
|
||||||
@@ -22,22 +20,17 @@ ms.api.event.not.found: "§6Plugin §b{name} §6register {event} error. event no
|
|||||||
ms.api.event.execute.slow: "§cWARN! §6Plugin §b{name} §6execute §d{event} §6evnet §ccost §4{cost}ms !"
|
ms.api.event.execute.slow: "§cWARN! §6Plugin §b{name} §6execute §d{event} §6evnet §ccost §4{cost}ms !"
|
||||||
ms.api.event.execute.error: "§6Plugin §b{name} §6execute §d{event} §6event error §4{ex}"
|
ms.api.event.execute.error: "§6Plugin §b{name} §6execute §d{event} §6event error §4{ex}"
|
||||||
ms.api.event.listen.plugin.name.empty: "Plugin name can't be empty!"
|
ms.api.event.listen.plugin.name.empty: "Plugin name can't be empty!"
|
||||||
ms.api.event.register: "[{name}] register event {event} priority {priority} ignoreCancelled {ignore}"
|
ms.api.event.register: "[{name}] register event {event}"
|
||||||
ms.api.event.unregister: "[{name}] unregister event {event}"
|
ms.api.event.unregister: "[{name}] unregister event {event}"
|
||||||
|
|
||||||
ms.api.command.register.input.error: "CommandExec Must be a function... Input: {exec}"
|
ms.api.command.register.input.error: "CommandExec Must be a function... Input: {exec}"
|
||||||
ms.api.command.register: "[{plugin}] register command {name}({cmd})..."
|
ms.api.command.register: "[{plugin}] register command {name}({cmd})..."
|
||||||
ms.api.command.unregister: "[{plugin}] unregister command {name}..."
|
ms.api.command.unregister: "[{plugin}] unregister command {name}..."
|
||||||
ms.api.command.execute.slow: "§cWarn. §6Player §a{player} §6exec §b{plugin} §6Plugin §d{command} {args} §6Command §cCost §4{cost}ms !"
|
|
||||||
ms.api.command.execute.error: "§6Player {player} §6exec §b{plugin} §6Plugin Command §d{command} {args} §6error §4{ex}"
|
ms.api.command.execute.error: "§6Player {player} §6exec §b{plugin} §6Plugin Command §d{command} {args} §6error §4{ex}"
|
||||||
ms.api.command.tab.completer.slow: "§cWarn. §6Player §a{player} §6exec §b{plugin} §6Plugin §d{command} {args} §6TabComplete §cCost §4{cost}ms !"
|
|
||||||
ms.api.command.tab.completer.error: "§6Player {player} §6exec §b{plugin} §6Plugin TabComplete §d{command} {args} §6error §4{ex}"
|
ms.api.command.tab.completer.error: "§6Player {player} §6exec §b{plugin} §6Plugin TabComplete §d{command} {args} §6error §4{ex}"
|
||||||
|
|
||||||
ms.plugin.initialize: "Initialization MiaoScript Plugin System: Plugin: {plugin} Loader: {loader}..."
|
ms.plugin.initialize: "Initialization MiaoScript Plugin System: Plugin: {plugin} Loader: {loader}..."
|
||||||
ms.plugin.event.map: "Total {count} {type} Event Mapping Complate..."
|
ms.plugin.event.map: "Total {count} {type} Event Mapping Complate..."
|
||||||
ms.plugin.event.map.error: "Mapping {type} Event Failed. Error: {error}"
|
ms.plugin.manager.scan: "Scanning Plugins in {folder} ..."
|
||||||
ms.plugin.manager.scan: "Scanner {scanner} Scanning Plugins in {folder} ..."
|
|
||||||
ms.plugin.manager.scan.finish: "Scanner {scanner} Found {size} Plugins in {folder} Start Build..."
|
|
||||||
ms.plugin.manager.initialize.error: "§6Plugin §b{name} §6initialize error §4{ex}"
|
ms.plugin.manager.initialize.error: "§6Plugin §b{name} §6initialize error §4{ex}"
|
||||||
ms.plugin.manager.stage: "{stage} {plugin} version {version} by {author}"
|
ms.plugin.manager.stage: "{stage} {plugin} version {version} by {author}"
|
||||||
ms.plugin.manager.stage.exec: "[{plugin}] Exec {name} Stage {stage} When servers is {servers}..."
|
ms.plugin.manager.stage.exec: "[{plugin}] Exec {name} Stage {stage} When servers is {servers}..."
|
||||||
@@ -45,11 +38,7 @@ ms.plugin.manager.stage.exec.error: "§6Plugin §b{plugin} §6exec §d{executor}
|
|||||||
ms.plugin.manager.stage.load: "Loading"
|
ms.plugin.manager.stage.load: "Loading"
|
||||||
ms.plugin.manager.stage.enable: "Enabling"
|
ms.plugin.manager.stage.enable: "Enabling"
|
||||||
ms.plugin.manager.stage.disable: "Disabling"
|
ms.plugin.manager.stage.disable: "Disabling"
|
||||||
ms.plugin.manager.build: "Plugin {name}({version}) Build Finish source: {file}({scanner}) loader: {loader} Cost: {cost}s."
|
|
||||||
ms.plugin.manager.build.error: "§6Load Plugin From §b{file} §6failed. §4Error: §c{error}"
|
|
||||||
ms.plugin.manager.build.update: "Auto Update Plugin {name} ..."
|
ms.plugin.manager.build.update: "Auto Update Plugin {name} ..."
|
||||||
ms.plugin.manager.build.not.extends: "§4Found error plugin §b{source} §4it's not extends interfaces.Plugin, the plugin will be ignore!"
|
ms.plugin.manager.build.not.extends: "§4Found error plugin §b{source} §4it's not extends interfaces.Plugin, the plugin will be ignore!"
|
||||||
ms.plugin.manager.build.exists: "§4Found duplicate plugin §b{exists} §4and §b{source}§4. the first plugin will be ignore!"
|
ms.plugin.manager.build.exists: "§4Found duplicate plugin §b{exists} §4and §b{source}§4. the first plugin will be ignore!"
|
||||||
ms.plugin.manager.config.load.error: "[{plugin}] config {name}.{format} load failed. Error: {error}"
|
|
||||||
ms.plugin.manager.config.save.error: "[{plugin}] config {name}.{format} save failed. Error: {error}"
|
|
||||||
ms.plugin.manager.config.save.default: "[{plugin}] config {name}.{format} not exists. auto create from default variable..."
|
ms.plugin.manager.config.save.default: "[{plugin}] config {name}.{format} not exists. auto create from default variable..."
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
ms.i18n.completed: "国际化组件 初始化完成 当前语言: 简体中文"
|
ms.ployfill.initialize: "加载 Java Nashorn 补丁. 请稍候..."
|
||||||
ms.polyfill.initialize: "加载 Java Nashorn 补丁. 请稍候..."
|
ms.ployfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
|
||||||
ms.polyfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
|
|
||||||
|
|
||||||
ms.core.ioc.initialize: "初始化 MiaoScript IOC 容器 {scope}/container. 请稍候..."
|
ms.core.ioc.initialize: "初始化 MiaoScript IOC 容器 {scope}/container. 请稍候..."
|
||||||
ms.core.ioc.completed: "MiaoScript IOC 容器 {scope}/container 加载完成 耗时({time}s)"
|
ms.core.ioc.completed: "MiaoScript IOC 容器 {scope}/container 加载完成 耗时({time}s)"
|
||||||
@@ -10,9 +9,8 @@ ms.core.package.initialize: "初始化 MiaoScript 扩展 {scope}/core {scope}/{t
|
|||||||
ms.core.package.completed: "MiaoScript 扩展 {scope}/core {scope}/{type} {scope}/plugin 加载完成 耗时({time}s)"
|
ms.core.package.completed: "MiaoScript 扩展 {scope}/core {scope}/{type} {scope}/plugin 加载完成 耗时({time}s)"
|
||||||
ms.core.plugin.initialize: "MiaoScript 开始引导插件系统. 请稍候..."
|
ms.core.plugin.initialize: "MiaoScript 开始引导插件系统. 请稍候..."
|
||||||
ms.core.plugin.completed: "MiaoScript 插件加载完毕 耗时({time}s)!"
|
ms.core.plugin.completed: "MiaoScript 插件加载完毕 耗时({time}s)!"
|
||||||
ms.core.engine.completed: "MiaoScript 框架 {loader} 引擎 {version} 加载完毕... 耗时({time}s)!"
|
ms.core.engine.completed: "MiaoScript 脚本引擎 加载完毕... 耗时({time}s)!"
|
||||||
ms.core.engine.disable: "MiaoScript 关闭脚本引擎 请稍候..."
|
ms.core.engine.disable: "关闭 MiaoScript 引擎..."
|
||||||
ms.core.engine.disable.finish: "MiaoScript 框架 {loader} 引擎 {version} 关闭完成... 耗时({time}s)!"
|
|
||||||
ms.core.engine.disable.abnormal: "引擎异常启动或初始化未完成 跳过关闭流程..."
|
ms.core.engine.disable.abnormal: "引擎异常启动或初始化未完成 跳过关闭流程..."
|
||||||
|
|
||||||
ms.api.event.resource.not.found: "无法映射事件 未找到资源文件 {resource}!"
|
ms.api.event.resource.not.found: "无法映射事件 未找到资源文件 {resource}!"
|
||||||
@@ -22,22 +20,17 @@ ms.api.event.not.found: "§6插件 §b{name} §6注册事件 §c{event} §6失
|
|||||||
ms.api.event.execute.slow: "§c注意! §6插件 §b{name} §6处理 §d{event} §6事件 §c耗时 §4{cost}ms !"
|
ms.api.event.execute.slow: "§c注意! §6插件 §b{name} §6处理 §d{event} §6事件 §c耗时 §4{cost}ms !"
|
||||||
ms.api.event.execute.error: "§6插件 §b{name} §6处理 §d{event} §6事件时发生异常 §4{ex}"
|
ms.api.event.execute.error: "§6插件 §b{name} §6处理 §d{event} §6事件时发生异常 §4{ex}"
|
||||||
ms.api.event.listen.plugin.name.empty: "插件名称为空 请检查传入参数!"
|
ms.api.event.listen.plugin.name.empty: "插件名称为空 请检查传入参数!"
|
||||||
ms.api.event.register: "[{name}] 注册事件 {event} => 执行器 {exec} 优先级 {priority} 忽略取消 {ignore}"
|
ms.api.event.register: "[{name}] 注册事件 {event}"
|
||||||
ms.api.event.unregister: "[{name}] 注销事件 {event} => 执行器 {exec}"
|
ms.api.event.unregister: "[{name}] 注销事件 {event}"
|
||||||
|
|
||||||
ms.api.command.register.input.error: "CommandExec 必须为一个函数... 输入: {exec}"
|
ms.api.command.register.input.error: "CommandExec 必须为一个函数... 输入: {exec}"
|
||||||
ms.api.command.register: "[{plugin}] 注册命令 {name}({cmd})..."
|
ms.api.command.register: "[{plugin}] 注册命令 {name}({cmd})..."
|
||||||
ms.api.command.unregister: "[{plugin}] 注销命令 {name}..."
|
ms.api.command.unregister: "[{plugin}] 注销命令 {name}..."
|
||||||
ms.api.command.execute.slow: "§c注意! §6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6命令 §c耗时 §4{cost}ms !"
|
|
||||||
ms.api.command.execute.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6命令时发生异常 §4{ex}"
|
ms.api.command.execute.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6命令时发生异常 §4{ex}"
|
||||||
ms.api.command.tab.completer.slow: "§c注意! §6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6补全 §c耗时 §4{cost}ms !"
|
|
||||||
ms.api.command.tab.completer.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6补全时发生异常 §4{ex}"
|
ms.api.command.tab.completer.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6补全时发生异常 §4{ex}"
|
||||||
|
|
||||||
ms.plugin.initialize: "初始化 MiaoScript 插件系统: 实例: {plugin} 加载器: {loader}..."
|
ms.plugin.initialize: "初始化 MiaoScript 插件系统: 实例: {plugin} 加载器: {loader}..."
|
||||||
ms.plugin.event.map: "映射 {type} 事件 成功 总计 {count} 个 {type} 事件..."
|
ms.plugin.event.map: "总计 {count} 个 {type} 事件 映射完成..."
|
||||||
ms.plugin.event.map.error: "映射 {type} 事件 异常 将无法使用事件简称. Error: {error}"
|
ms.plugin.manager.scan: "扫描 {folder} 文件夹中插件..."
|
||||||
ms.plugin.manager.scan: "扫描器 {scanner} 扫描 {folder} 中的插件..."
|
|
||||||
ms.plugin.manager.scan.finish: "扫描器 {scanner} 在 {folder} 中 发现 {size} 个插件 开始编译..."
|
|
||||||
ms.plugin.manager.initialize.error: "§6插件 §b{name} §6初始化错误 §4{ex}"
|
ms.plugin.manager.initialize.error: "§6插件 §b{name} §6初始化错误 §4{ex}"
|
||||||
ms.plugin.manager.stage: "{stage} {plugin} 版本 {version} 作者 {author}"
|
ms.plugin.manager.stage: "{stage} {plugin} 版本 {version} 作者 {author}"
|
||||||
ms.plugin.manager.stage.exec: "[{plugin}] 执行 {stage} 阶段函数 {name} 匹配类型 {servers}..."
|
ms.plugin.manager.stage.exec: "[{plugin}] 执行 {stage} 阶段函数 {name} 匹配类型 {servers}..."
|
||||||
@@ -45,11 +38,7 @@ ms.plugin.manager.stage.exec.error: "§6插件 §b{plugin} §6执行 §d{executo
|
|||||||
ms.plugin.manager.stage.load: "加载"
|
ms.plugin.manager.stage.load: "加载"
|
||||||
ms.plugin.manager.stage.enable: "启用"
|
ms.plugin.manager.stage.enable: "启用"
|
||||||
ms.plugin.manager.stage.disable: "关闭"
|
ms.plugin.manager.stage.disable: "关闭"
|
||||||
ms.plugin.manager.build: "插件 {name}({version}) 编译完成 来源: {file}({scanner}) 引导: {loader} 编译耗时: {cost}s."
|
|
||||||
ms.plugin.manager.build.error: "§6从文件 §b{file} §6加载插件失败 §4错误: §c{error}"
|
|
||||||
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
|
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
|
||||||
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
|
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
|
||||||
ms.plugin.manager.build.duplicate: "§4发现已存在插件 §b{exists} §4和 §b{source}§4 存在冲突. 已存在插件将会被替换!"
|
ms.plugin.manager.build.duplicate: "§4发现已存在插件 §b{exists} §4和 §b{source}§4 存在冲突. 已存在插件将会被替换!"
|
||||||
ms.plugin.manager.config.load.error: "[{plugin}] 配置 {name}.{format} 加载失败. 错误: {error}"
|
|
||||||
ms.plugin.manager.config.save.error: "[{plugin}] 配置 {name}.{format} 保存失败. 错误: {error}"
|
|
||||||
ms.plugin.manager.config.save.default: "[{plugin}] 配置 {name}.{format} 不存在. 从默认值自动创建保存..."
|
ms.plugin.manager.config.save.default: "[{plugin}] 配置 {name}.{format} 不存在. 从默认值自动创建保存..."
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/i18n",
|
"name": "@ccms/i18n",
|
||||||
"version": "0.28.0-beta.11",
|
"version": "0.6.1",
|
||||||
"description": "MiaoScript i18n package",
|
"description": "MiaoScript i18n package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -12,24 +12,21 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"files": [
|
|
||||||
"dist/**/*.js",
|
|
||||||
"dist/**/*.ts",
|
|
||||||
"dist/**/*.map",
|
|
||||||
"languages"
|
|
||||||
],
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "pnpm clean && tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
|
||||||
"js-yaml": "^4.1.0"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ccms/nashorn": "workspace:*",
|
"@types/js-yaml": "^3.12.3",
|
||||||
"@types/js-yaml": "^4.0.9"
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"typescript": "^3.8.3"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@ccms/nashorn": "^0.6.1",
|
||||||
|
"js-yaml": "^3.13.1"
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
/// <reference types="@ccms/nashorn" />
|
/// <reference types="@ccms/nashorn" />
|
||||||
import * as yaml from 'js-yaml'
|
import * as yaml from 'js-yaml'
|
||||||
|
|
||||||
const File = Java.type("java.io.File")
|
const File = Java.type("java.io.File");
|
||||||
const separatorChar = File.separatorChar
|
const separatorChar = File.separatorChar;
|
||||||
type TranslateParam = { [key: string]: any }
|
type TranslateParam = { [key: string]: any }
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
interface Console {
|
interface Console {
|
||||||
i18n(name: string, param?: TranslateParam)
|
i18n(name: string, param?: TranslateParam);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,20 +23,20 @@ export class Translate {
|
|||||||
|
|
||||||
constructor(root: string | TranslateContent) {
|
constructor(root: string | TranslateContent) {
|
||||||
if (typeof root == 'string') {
|
if (typeof root == 'string') {
|
||||||
this.root = root
|
this.root = root;
|
||||||
} else {
|
} else {
|
||||||
this.langMap = root.langMap
|
this.langMap = root.langMap;
|
||||||
this.fallbackMap = root.fallbackMap || {}
|
this.fallbackMap = root.fallbackMap || {};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
translate(name: string, param?: TranslateParam) {
|
translate(name: string, param?: TranslateParam) {
|
||||||
let langText: string = this.langMap[name] || this.fallbackMap[name]
|
let langText: string = this.langMap[name] || this.fallbackMap[name];
|
||||||
if (!langText) { return '[WARN] @ccms/i18n miss lang translate: ' + name }
|
if (!langText) { return '[WARN] @ccms/i18n miss lang translate: ' + name }
|
||||||
for (const key in param) {
|
for (const key in param) {
|
||||||
langText = langText.replace(new RegExp("{" + key + "}", 'gm'), param[key])
|
langText = langText.replace(new RegExp("{" + key + "}", 'gm'), param[key])
|
||||||
}
|
}
|
||||||
return langText
|
return langText;
|
||||||
}
|
}
|
||||||
|
|
||||||
initialize(lang: string = 'zh_cn', fallback: string = 'zh_cn') {
|
initialize(lang: string = 'zh_cn', fallback: string = 'zh_cn') {
|
||||||
@@ -45,12 +45,11 @@ export class Translate {
|
|||||||
console.i18n = (name: string, param?: TranslateParam) => {
|
console.i18n = (name: string, param?: TranslateParam) => {
|
||||||
console.log(this.translate(name, param))
|
console.log(this.translate(name, param))
|
||||||
}
|
}
|
||||||
console.i18n('ms.i18n.completed')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
readYamlFile(dir: string, name: string) {
|
readYamlFile(dir: string, name: string) {
|
||||||
let langFile = this.concat(dir, 'languages', name + '.yml')
|
let langFile = this.concat(dir, 'languages', name + '.yml');
|
||||||
return this.exists(langFile) && yaml.load(base.read(langFile))
|
return this.exists(langFile) && yaml.safeLoad(base.read(langFile))
|
||||||
}
|
}
|
||||||
|
|
||||||
concat(...args: string[]) {
|
concat(...args: string[]) {
|
||||||
|
|||||||
6
packages/molang/.gitignore
vendored
6
packages/molang/.gitignore
vendored
@@ -1,6 +0,0 @@
|
|||||||
node_modules
|
|
||||||
perf/*
|
|
||||||
|
|
||||||
|
|
||||||
tsconfig.tsbuildinfo
|
|
||||||
.DS_STORE
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "@ccms/molang",
|
|
||||||
"version": "0.28.0-beta.11",
|
|
||||||
"description": "A fast parser for Minecraft's MoLang",
|
|
||||||
"main": "dist/index.js",
|
|
||||||
"types": "dist/index.d.ts",
|
|
||||||
"files": [
|
|
||||||
"dist/**/*.js",
|
|
||||||
"dist/**/*.ts",
|
|
||||||
"dist/**/*.map"
|
|
||||||
],
|
|
||||||
"scripts": {
|
|
||||||
"clean": "rimraf dist",
|
|
||||||
"watch": "tsc --watch",
|
|
||||||
"build": "pnpm clean && tsc",
|
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/solvedDev/MoLang.git"
|
|
||||||
},
|
|
||||||
"author": "solvedDev",
|
|
||||||
"license": "MIT",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/solvedDev/MoLang/issues"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/solvedDev/MoLang#readme",
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/node": "^18.19.118"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,129 +0,0 @@
|
|||||||
import { ExecutionEnvironment } from './env/env'
|
|
||||||
import { IExpression, IParserConfig } from './main'
|
|
||||||
import { StaticExpression } from './parser/expressions/static'
|
|
||||||
import { StringExpression } from './parser/expressions/string'
|
|
||||||
import { MoLangParser } from './parser/molang'
|
|
||||||
|
|
||||||
export class MoLang {
|
|
||||||
protected expressionCache: Record<string, IExpression> = {}
|
|
||||||
protected totalCacheEntries = 0
|
|
||||||
protected executionEnvironment!: ExecutionEnvironment
|
|
||||||
|
|
||||||
protected parser: MoLangParser
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
env: Record<string, unknown> = {},
|
|
||||||
protected config: Partial<IParserConfig> = {}
|
|
||||||
) {
|
|
||||||
if (config.useOptimizer === undefined) this.config.useOptimizer = true
|
|
||||||
if (config.useCache === undefined) this.config.useCache = true
|
|
||||||
if (config.earlyReturnsSkipParsing === undefined)
|
|
||||||
this.config.earlyReturnsSkipParsing = true
|
|
||||||
if (config.earlyReturnsSkipTokenization === undefined)
|
|
||||||
this.config.earlyReturnsSkipTokenization = true
|
|
||||||
if (config.convertUndefined === undefined)
|
|
||||||
this.config.convertUndefined = false
|
|
||||||
|
|
||||||
this.parser = new MoLangParser({
|
|
||||||
...this.config,
|
|
||||||
tokenizer: undefined,
|
|
||||||
})
|
|
||||||
|
|
||||||
this.updateExecutionEnv(env)
|
|
||||||
}
|
|
||||||
|
|
||||||
updateConfig(newConfig: Partial<IParserConfig>) {
|
|
||||||
newConfig = Object.assign(this.config, newConfig)
|
|
||||||
|
|
||||||
if (newConfig.tokenizer) this.parser.setTokenizer(newConfig.tokenizer)
|
|
||||||
this.parser.updateConfig({ ...this.config, tokenizer: undefined })
|
|
||||||
this.executionEnvironment.updateConfig(newConfig)
|
|
||||||
}
|
|
||||||
updateExecutionEnv(env: Record<string, unknown>, isFlat = false) {
|
|
||||||
this.executionEnvironment = new ExecutionEnvironment(env, {
|
|
||||||
useRadians: this.config.useRadians,
|
|
||||||
convertUndefined: this.config.convertUndefined,
|
|
||||||
isFlat,
|
|
||||||
variableHandler: this.config.variableHandler,
|
|
||||||
})
|
|
||||||
this.parser.setExecutionEnvironment(this.executionEnvironment)
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Clears the MoLang expression cache
|
|
||||||
*/
|
|
||||||
clearCache() {
|
|
||||||
this.expressionCache = {}
|
|
||||||
this.totalCacheEntries = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execute the given MoLang string `expression`
|
|
||||||
* @param expression The MoLang string to execute
|
|
||||||
*
|
|
||||||
* @returns The value the MoLang expression corresponds to
|
|
||||||
*/
|
|
||||||
execute(expression: string) {
|
|
||||||
this.parser.setExecutionEnvironment(this.executionEnvironment)
|
|
||||||
const abstractSyntaxTree = this.parse(expression)
|
|
||||||
|
|
||||||
const result = abstractSyntaxTree.eval()
|
|
||||||
if (result === undefined) return 0
|
|
||||||
if (typeof result === 'boolean') return Number(result)
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Execute the given MoLang string `expression`
|
|
||||||
* In case of errors, return 0
|
|
||||||
* @param expression The MoLang string to execute
|
|
||||||
*
|
|
||||||
* @returns The value the MoLang expression corresponds to and 0 if the statement is invalid
|
|
||||||
*/
|
|
||||||
executeAndCatch(expression: string) {
|
|
||||||
try {
|
|
||||||
return this.execute(expression)
|
|
||||||
} catch {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse the given MoLang string `expression`
|
|
||||||
* @param expression The MoLang string to parse
|
|
||||||
*
|
|
||||||
* @returns An AST that corresponds to the MoLang expression
|
|
||||||
*/
|
|
||||||
parse(expression: string): IExpression {
|
|
||||||
if (this.config.useCache ?? true) {
|
|
||||||
const abstractSyntaxTree = this.expressionCache[expression]
|
|
||||||
if (abstractSyntaxTree) return abstractSyntaxTree
|
|
||||||
}
|
|
||||||
|
|
||||||
this.parser.init(expression)
|
|
||||||
let abstractSyntaxTree = this.parser.parseExpression()
|
|
||||||
if ((this.config.useOptimizer ?? true) && abstractSyntaxTree.isStatic())
|
|
||||||
abstractSyntaxTree = new StaticExpression(abstractSyntaxTree.eval())
|
|
||||||
// console.log(JSON.stringify(abstractSyntaxTree, null, ' '))
|
|
||||||
|
|
||||||
if (this.config.useCache ?? true) {
|
|
||||||
if (this.totalCacheEntries > (this.config.maxCacheSize || 256))
|
|
||||||
this.clearCache()
|
|
||||||
|
|
||||||
this.expressionCache[expression] = abstractSyntaxTree
|
|
||||||
this.totalCacheEntries++
|
|
||||||
}
|
|
||||||
|
|
||||||
return abstractSyntaxTree
|
|
||||||
}
|
|
||||||
|
|
||||||
resolveStatic(ast: IExpression) {
|
|
||||||
ast.walk((expr) => {
|
|
||||||
if (expr instanceof StringExpression) return
|
|
||||||
|
|
||||||
if (expr.isStatic()) return new StaticExpression(expr.eval())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
getParser() {
|
|
||||||
return this.parser
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
import { Parser } from '../parser/parse'
|
|
||||||
import { Token } from '../parser/../tokenizer/token'
|
|
||||||
import { IPrefixParselet } from '../parser/parselets/prefix'
|
|
||||||
import { Expression, IExpression } from '../parser/expression'
|
|
||||||
import { StringExpression } from '../parser/expressions/string'
|
|
||||||
import { StatementExpression } from '../parser/expressions/statement'
|
|
||||||
import { CustomMoLangParser } from './main'
|
|
||||||
import { GroupExpression } from '../parser/expressions/group'
|
|
||||||
|
|
||||||
export class CustomFunctionParselet implements IPrefixParselet {
|
|
||||||
constructor(public precedence = 0) {}
|
|
||||||
|
|
||||||
parse(parser: Parser, token: Token) {
|
|
||||||
parser.consume('LEFT_PARENT')
|
|
||||||
if (parser.match('RIGHT_PARENT'))
|
|
||||||
throw new Error(`function() called without arguments`)
|
|
||||||
|
|
||||||
let args: string[] = []
|
|
||||||
let functionBody: IExpression | undefined
|
|
||||||
let functionName: string | undefined
|
|
||||||
do {
|
|
||||||
const expr = parser.parseExpression()
|
|
||||||
if (expr instanceof StringExpression) {
|
|
||||||
if (!functionName) functionName = <string>expr.eval()
|
|
||||||
else args.push(<string>expr.eval())
|
|
||||||
} else if (
|
|
||||||
expr instanceof StatementExpression ||
|
|
||||||
expr instanceof GroupExpression
|
|
||||||
) {
|
|
||||||
functionBody = expr
|
|
||||||
} else {
|
|
||||||
throw new Error(
|
|
||||||
`Unexpected expresion: found "${expr.constructor.name}"`
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} while (parser.match('COMMA'))
|
|
||||||
parser.consume('RIGHT_PARENT')
|
|
||||||
|
|
||||||
if (!functionName)
|
|
||||||
throw new Error(
|
|
||||||
`Missing function() name (argument 1); found "${functionName}"`
|
|
||||||
)
|
|
||||||
if (!functionBody)
|
|
||||||
throw new Error(
|
|
||||||
`Missing function() body (argument ${args.length + 2})`
|
|
||||||
)
|
|
||||||
|
|
||||||
return new CustomFunctionExpression(
|
|
||||||
(<CustomMoLangParser>parser).functions,
|
|
||||||
functionName,
|
|
||||||
args,
|
|
||||||
functionBody
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class CustomFunctionExpression extends Expression {
|
|
||||||
type = 'CustomFunctionExpression'
|
|
||||||
constructor(
|
|
||||||
functions: Map<string, [string[], string]>,
|
|
||||||
functionName: string,
|
|
||||||
args: string[],
|
|
||||||
protected functionBody: IExpression
|
|
||||||
) {
|
|
||||||
super()
|
|
||||||
functions.set(functionName, [
|
|
||||||
args,
|
|
||||||
functionBody instanceof GroupExpression
|
|
||||||
? functionBody.allExpressions[0].toString()
|
|
||||||
: functionBody.toString(),
|
|
||||||
])
|
|
||||||
}
|
|
||||||
|
|
||||||
get allExpressions() {
|
|
||||||
return [this.functionBody]
|
|
||||||
}
|
|
||||||
setExpressionAt(_: number, expr: IExpression) {
|
|
||||||
this.functionBody = expr
|
|
||||||
}
|
|
||||||
|
|
||||||
get isReturn() {
|
|
||||||
// Scopes inside of functions may use return statements
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
isStatic() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
eval() {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,229 +0,0 @@
|
|||||||
import { ExecutionEnvironment } from '../env/env'
|
|
||||||
import { IParserConfig } from '../main'
|
|
||||||
import { MoLangParser } from '../parser/molang'
|
|
||||||
import { Tokenizer } from '../tokenizer/Tokenizer'
|
|
||||||
import { CustomFunctionParselet } from './function'
|
|
||||||
import { MoLang } from '../MoLang'
|
|
||||||
import { StatementExpression } from '../parser/expressions/statement'
|
|
||||||
import { transformStatement } from './transformStatement'
|
|
||||||
import { NameExpression } from '../parser/expressions/name'
|
|
||||||
import { ReturnExpression } from '../parser/expressions/return'
|
|
||||||
import { GenericOperatorExpression } from '../parser/expressions/genericOperator'
|
|
||||||
import { TernaryExpression } from '../parser/expressions/ternary'
|
|
||||||
import { IExpression } from '../parser/expression'
|
|
||||||
import { VoidExpression } from '../parser/expressions/void'
|
|
||||||
import { GroupExpression } from '../parser/expressions/group'
|
|
||||||
|
|
||||||
export class CustomMoLangParser extends MoLangParser {
|
|
||||||
public readonly functions = new Map<string, [string[], string]>()
|
|
||||||
|
|
||||||
constructor(config: Partial<IParserConfig>) {
|
|
||||||
super(config)
|
|
||||||
this.registerPrefix('FUNCTION', new CustomFunctionParselet())
|
|
||||||
}
|
|
||||||
|
|
||||||
reset() {
|
|
||||||
this.functions.clear()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class CustomMoLang {
|
|
||||||
protected parser: CustomMoLangParser
|
|
||||||
|
|
||||||
constructor(env: any) {
|
|
||||||
this.parser = new CustomMoLangParser({
|
|
||||||
useCache: false,
|
|
||||||
useOptimizer: true,
|
|
||||||
useAgressiveStaticOptimizer: true,
|
|
||||||
keepGroups: true,
|
|
||||||
earlyReturnsSkipParsing: false,
|
|
||||||
earlyReturnsSkipTokenization: false,
|
|
||||||
})
|
|
||||||
this.parser.setExecutionEnvironment(
|
|
||||||
new ExecutionEnvironment(this.parser, env)
|
|
||||||
)
|
|
||||||
this.parser.setTokenizer(new Tokenizer(new Set(['function'])))
|
|
||||||
}
|
|
||||||
|
|
||||||
get functions() {
|
|
||||||
return this.parser.functions
|
|
||||||
}
|
|
||||||
|
|
||||||
parse(expression: string) {
|
|
||||||
this.parser.init(expression)
|
|
||||||
const abstractSyntaxTree = this.parser.parseExpression()
|
|
||||||
|
|
||||||
return abstractSyntaxTree
|
|
||||||
}
|
|
||||||
|
|
||||||
transform(source: string) {
|
|
||||||
const molang = new MoLang(
|
|
||||||
{},
|
|
||||||
{
|
|
||||||
useCache: false,
|
|
||||||
keepGroups: true,
|
|
||||||
useOptimizer: true,
|
|
||||||
useAgressiveStaticOptimizer: true,
|
|
||||||
earlyReturnsSkipParsing: true,
|
|
||||||
earlyReturnsSkipTokenization: false,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
let totalScoped = 0
|
|
||||||
let ast = molang.parse(source)
|
|
||||||
|
|
||||||
let isComplexExpression = false
|
|
||||||
if (ast instanceof StatementExpression) {
|
|
||||||
isComplexExpression = true
|
|
||||||
}
|
|
||||||
|
|
||||||
let containsComplexExpressions = false
|
|
||||||
ast = ast.walk((expr: any) => {
|
|
||||||
// Only run code on function expressions which start with "f." or "function."
|
|
||||||
if (
|
|
||||||
expr.type !== 'FunctionExpression' ||
|
|
||||||
(!expr.name.name.startsWith?.('f.') &&
|
|
||||||
!expr.name.name.startsWith?.('function.'))
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
const nameExpr = expr.name
|
|
||||||
const functionName = nameExpr.name.replace(/(f|function)\./g, '')
|
|
||||||
const argValues = expr.args
|
|
||||||
|
|
||||||
let [args, functionBody] = this.functions.get(functionName) ?? []
|
|
||||||
if (!functionBody || !args) return
|
|
||||||
|
|
||||||
// Insert argument values
|
|
||||||
functionBody = functionBody.replace(
|
|
||||||
/(a|arg)\.(\w+)/g,
|
|
||||||
(match, prefix, argName) => {
|
|
||||||
const val =
|
|
||||||
argValues[args!.indexOf(argName)]?.toString() ?? '0'
|
|
||||||
|
|
||||||
return val.replace(/(t|temp)\./, 'outer_temp.')
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
let funcAst = transformStatement(molang.parse(functionBody))
|
|
||||||
if (funcAst instanceof StatementExpression) {
|
|
||||||
funcAst = molang.parse(`({${functionBody}}+t.return_value)`)
|
|
||||||
|
|
||||||
containsComplexExpressions = true
|
|
||||||
}
|
|
||||||
|
|
||||||
const varNameMap = new Map<string, string>()
|
|
||||||
funcAst = funcAst.walk((expr) => {
|
|
||||||
if (expr instanceof NameExpression) {
|
|
||||||
const fullName = expr.toString()
|
|
||||||
// Remove "a."/"t."/etc. from var name
|
|
||||||
let tmp = fullName.split('.')
|
|
||||||
const varType = tmp.shift()
|
|
||||||
const varName = tmp.join('.')
|
|
||||||
|
|
||||||
if (varType === 't' || varType === 'temp') {
|
|
||||||
// Scope temp./t. variables to functions
|
|
||||||
let newName = varNameMap.get(fullName)
|
|
||||||
if (!newName) {
|
|
||||||
newName = `t.__scvar${totalScoped++}`
|
|
||||||
varNameMap.set(fullName, newName)
|
|
||||||
}
|
|
||||||
|
|
||||||
expr.setName(newName)
|
|
||||||
} else if (varType === 'outer_temp') {
|
|
||||||
expr.setName(`t.${varName}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
return undefined
|
|
||||||
} else if (expr instanceof ReturnExpression) {
|
|
||||||
const nameExpr = new NameExpression(
|
|
||||||
molang.getParser().executionEnv,
|
|
||||||
't.return_value'
|
|
||||||
)
|
|
||||||
const returnValExpr = expr.allExpressions[0]
|
|
||||||
|
|
||||||
return new GenericOperatorExpression(
|
|
||||||
nameExpr,
|
|
||||||
returnValExpr,
|
|
||||||
'=',
|
|
||||||
() => {
|
|
||||||
nameExpr.setPointer(returnValExpr.eval())
|
|
||||||
}
|
|
||||||
)
|
|
||||||
} else if (expr instanceof StatementExpression) {
|
|
||||||
// Make early returns work correctly by adjusting ternary statements which contain return statements
|
|
||||||
const expressions: IExpression[] = []
|
|
||||||
|
|
||||||
for (let i = 0; i < expr.allExpressions.length; i++) {
|
|
||||||
const currExpr = expr.allExpressions[i]
|
|
||||||
|
|
||||||
if (
|
|
||||||
currExpr instanceof TernaryExpression &&
|
|
||||||
currExpr.hasReturn
|
|
||||||
) {
|
|
||||||
handleTernary(
|
|
||||||
currExpr,
|
|
||||||
expr.allExpressions.slice(i + 1)
|
|
||||||
)
|
|
||||||
|
|
||||||
expressions.push(currExpr)
|
|
||||||
break
|
|
||||||
} else if (currExpr.isReturn) {
|
|
||||||
expressions.push(currExpr)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
expressions.push(currExpr)
|
|
||||||
}
|
|
||||||
|
|
||||||
return new StatementExpression(expressions)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
return funcAst
|
|
||||||
})
|
|
||||||
|
|
||||||
const finalAst = molang.parse(ast.toString())
|
|
||||||
molang.resolveStatic(finalAst)
|
|
||||||
return !isComplexExpression && containsComplexExpressions
|
|
||||||
? `return ${finalAst.toString()};`
|
|
||||||
: finalAst.toString()
|
|
||||||
}
|
|
||||||
|
|
||||||
reset() {
|
|
||||||
this.functions.clear()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleTernary(
|
|
||||||
returnTernary: TernaryExpression,
|
|
||||||
currentExpressions: IExpression[]
|
|
||||||
) {
|
|
||||||
// If & else branch end with return statements -> we can omit everything after the ternary
|
|
||||||
if (returnTernary.isReturn) return
|
|
||||||
|
|
||||||
const notReturningBranchIndex = returnTernary.allExpressions[2].isReturn
|
|
||||||
? 1
|
|
||||||
: 2
|
|
||||||
const notReturningBranch =
|
|
||||||
returnTernary.allExpressions[notReturningBranchIndex]
|
|
||||||
|
|
||||||
if (!(notReturningBranch instanceof VoidExpression)) {
|
|
||||||
if (
|
|
||||||
notReturningBranch instanceof GroupExpression &&
|
|
||||||
notReturningBranch.allExpressions[0] instanceof StatementExpression
|
|
||||||
) {
|
|
||||||
currentExpressions.unshift(...notReturningBranch.allExpressions)
|
|
||||||
} else {
|
|
||||||
currentExpressions.unshift(notReturningBranch)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (currentExpressions.length > 0)
|
|
||||||
returnTernary.setExpressionAt(
|
|
||||||
notReturningBranchIndex,
|
|
||||||
new GroupExpression(
|
|
||||||
new StatementExpression(currentExpressions),
|
|
||||||
'{}'
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
import { IExpression } from '../parser/expression'
|
|
||||||
import { GroupExpression } from '../parser/expressions/group'
|
|
||||||
import { ReturnExpression } from '../parser/expressions/return'
|
|
||||||
import { StatementExpression } from '../parser/expressions/statement'
|
|
||||||
|
|
||||||
export function transformStatement(expression: IExpression) {
|
|
||||||
if (expression instanceof ReturnExpression)
|
|
||||||
return new GroupExpression(expression.allExpressions[0], '()')
|
|
||||||
if (!(expression instanceof StatementExpression)) return expression
|
|
||||||
if (expression.allExpressions.length > 1) return expression
|
|
||||||
|
|
||||||
// Only one statement, test whether it is a return statement
|
|
||||||
const expr = expression.allExpressions[0]
|
|
||||||
if (expr instanceof ReturnExpression) {
|
|
||||||
return new GroupExpression(expr.allExpressions[0], '()')
|
|
||||||
} else {
|
|
||||||
return expression
|
|
||||||
}
|
|
||||||
}
|
|
||||||
143
packages/molang/src/env/env.ts
vendored
143
packages/molang/src/env/env.ts
vendored
@@ -1,143 +0,0 @@
|
|||||||
import { standardEnv } from './standardEnv'
|
|
||||||
|
|
||||||
export type TVariableHandler = (
|
|
||||||
variableName: string,
|
|
||||||
variables: Record<string, unknown>
|
|
||||||
) => unknown
|
|
||||||
|
|
||||||
export interface IEnvConfig {
|
|
||||||
useRadians?: boolean
|
|
||||||
convertUndefined?: boolean
|
|
||||||
variableHandler?: TVariableHandler
|
|
||||||
isFlat?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ExecutionEnvironment {
|
|
||||||
protected env: Record<string, any>
|
|
||||||
|
|
||||||
constructor(env: Record<string, any>, public readonly config: IEnvConfig) {
|
|
||||||
if (!env) throw new Error(`Provided environment must be an object`)
|
|
||||||
|
|
||||||
if (config.isFlat)
|
|
||||||
this.env = Object.assign(
|
|
||||||
env,
|
|
||||||
standardEnv(config.useRadians ?? false)
|
|
||||||
)
|
|
||||||
else
|
|
||||||
this.env = {
|
|
||||||
...standardEnv(config.useRadians ?? false),
|
|
||||||
...this.flattenEnv(env),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
updateConfig({
|
|
||||||
variableHandler,
|
|
||||||
convertUndefined,
|
|
||||||
useRadians,
|
|
||||||
}: IEnvConfig) {
|
|
||||||
if (convertUndefined !== undefined)
|
|
||||||
this.config.convertUndefined = convertUndefined
|
|
||||||
if (typeof variableHandler === 'function')
|
|
||||||
this.config.variableHandler = variableHandler
|
|
||||||
|
|
||||||
if (!!this.config.useRadians !== !!useRadians) {
|
|
||||||
this.env = Object.assign(this.env, standardEnv(!!useRadians))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected flattenEnv(
|
|
||||||
newEnv: Record<string, any>,
|
|
||||||
addKey = '',
|
|
||||||
current: any = {}
|
|
||||||
) {
|
|
||||||
for (let key in newEnv) {
|
|
||||||
if (key[1] === '.') {
|
|
||||||
switch (key[0]) {
|
|
||||||
case 'q':
|
|
||||||
key = 'query' + key.substring(1, key.length)
|
|
||||||
break
|
|
||||||
case 't':
|
|
||||||
key = 'temp' + key.substring(1, key.length)
|
|
||||||
break
|
|
||||||
case 'v':
|
|
||||||
key = 'variable' + key.substring(1, key.length)
|
|
||||||
break
|
|
||||||
case 'c':
|
|
||||||
key = 'context' + key.substring(1, key.length)
|
|
||||||
break
|
|
||||||
case 'f':
|
|
||||||
key = 'function' + key.substring(1, key.length)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (newEnv[key].__isContext) {
|
|
||||||
current[`${addKey}${key}`] = newEnv[key].env
|
|
||||||
} else if (
|
|
||||||
typeof newEnv[key] === 'object' &&
|
|
||||||
!Array.isArray(newEnv[key])
|
|
||||||
) {
|
|
||||||
this.flattenEnv(newEnv[key], `${addKey}${key}.`, current)
|
|
||||||
} else {
|
|
||||||
current[`${addKey}${key}`] = newEnv[key]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return current
|
|
||||||
}
|
|
||||||
|
|
||||||
setAt(lookup: string, value: unknown) {
|
|
||||||
if (lookup[1] === '.') {
|
|
||||||
switch (lookup[0]) {
|
|
||||||
case 'q':
|
|
||||||
lookup = 'query' + lookup.substring(1, lookup.length)
|
|
||||||
break
|
|
||||||
case 't':
|
|
||||||
lookup = 'temp' + lookup.substring(1, lookup.length)
|
|
||||||
break
|
|
||||||
case 'v':
|
|
||||||
lookup = 'variable' + lookup.substring(1, lookup.length)
|
|
||||||
break
|
|
||||||
case 'c':
|
|
||||||
lookup = 'context' + lookup.substring(1, lookup.length)
|
|
||||||
break
|
|
||||||
case 'f':
|
|
||||||
lookup = 'function' + lookup.substring(1, lookup.length)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (this.env[lookup] = value)
|
|
||||||
}
|
|
||||||
|
|
||||||
getFrom(lookup: string) {
|
|
||||||
if (lookup[1] === '.') {
|
|
||||||
switch (lookup[0]) {
|
|
||||||
case 'q':
|
|
||||||
lookup = 'query' + lookup.substring(1, lookup.length)
|
|
||||||
break
|
|
||||||
case 't':
|
|
||||||
lookup = 'temp' + lookup.substring(1, lookup.length)
|
|
||||||
break
|
|
||||||
case 'v':
|
|
||||||
lookup = 'variable' + lookup.substring(1, lookup.length)
|
|
||||||
break
|
|
||||||
case 'c':
|
|
||||||
lookup = 'context' + lookup.substring(1, lookup.length)
|
|
||||||
break
|
|
||||||
case 'f':
|
|
||||||
lookup = 'function' + lookup.substring(1, lookup.length)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const res =
|
|
||||||
this.env[lookup] ?? this.config.variableHandler?.(lookup, this.env)
|
|
||||||
return res === undefined && this.config.convertUndefined ? 0 : res
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class Context {
|
|
||||||
public readonly __isContext = true
|
|
||||||
constructor(public readonly env: any) {}
|
|
||||||
}
|
|
||||||
86
packages/molang/src/env/math.ts
vendored
86
packages/molang/src/env/math.ts
vendored
@@ -1,86 +0,0 @@
|
|||||||
const clamp = (value: number, min: number, max: number) => {
|
|
||||||
if (typeof value !== 'number' || Number.isNaN(value)) return min
|
|
||||||
else if (value > max) return max
|
|
||||||
else if (value < min) return min
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
const dieRoll = (sum: number, low: number, high: number) => {
|
|
||||||
let i = 0
|
|
||||||
let total = 0
|
|
||||||
while (i < sum) total += random(low, high)
|
|
||||||
return total
|
|
||||||
}
|
|
||||||
const dieRollInt = (sum: number, low: number, high: number) => {
|
|
||||||
let i = 0
|
|
||||||
let total = 0
|
|
||||||
while (i < sum) total += randomInt(low, high)
|
|
||||||
return total
|
|
||||||
}
|
|
||||||
const hermiteBlend = (value: number) => 3 * value ** 2 - 2 * value ** 3
|
|
||||||
const lerp = (start: number, end: number, amount: number) => {
|
|
||||||
if (amount < 0) amount = 0
|
|
||||||
else if (amount > 1) amount = 1
|
|
||||||
|
|
||||||
return start + (end - start) * amount
|
|
||||||
}
|
|
||||||
// Written by @JannisX11 (https://github.com/JannisX11/MolangJS/blob/master/molang.js#L383); modified for usage inside of this MoLang parser
|
|
||||||
const lerprotate = (start: number, end: number, amount: number) => {
|
|
||||||
const radify = (n: number) => (((n + 180) % 360) + 180) % 360
|
|
||||||
start = radify(start)
|
|
||||||
end = radify(end)
|
|
||||||
if (start > end) {
|
|
||||||
let tmp = start
|
|
||||||
start = end
|
|
||||||
end = tmp
|
|
||||||
}
|
|
||||||
|
|
||||||
if (end - start > 180) return radify(end + amount * (360 - (end - start)))
|
|
||||||
else return start + amount * (end - start)
|
|
||||||
}
|
|
||||||
const mod = (value: number, denominator: number) => value % denominator
|
|
||||||
const random = (low: number, high: number) => low + Math.random() * (high - low)
|
|
||||||
const randomInt = (low: number, high: number) =>
|
|
||||||
Math.round(low + Math.random() * (high - low))
|
|
||||||
|
|
||||||
const minAngle = (value: number) => {
|
|
||||||
value = value % 360
|
|
||||||
value = (value + 360) % 360
|
|
||||||
|
|
||||||
if (value > 179) value -= 360
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
export const MoLangMathLib = (useRadians: boolean) => {
|
|
||||||
const degRadFactor = useRadians ? 1 : Math.PI / 180
|
|
||||||
|
|
||||||
return {
|
|
||||||
'math.abs': Math.abs,
|
|
||||||
'math.acos': (x: number) => Math.acos(x) / degRadFactor,
|
|
||||||
'math.asin': (x: number) => Math.asin(x) / degRadFactor,
|
|
||||||
'math.atan': (x: number) => Math.atan(x) / degRadFactor,
|
|
||||||
'math.atan2': (y: number, x: number) => Math.atan2(y, x) / degRadFactor,
|
|
||||||
'math.ceil': Math.ceil,
|
|
||||||
'math.clamp': clamp,
|
|
||||||
'math.cos': (x: number) => Math.cos(x * degRadFactor),
|
|
||||||
'math.die_roll': dieRoll,
|
|
||||||
'math.die_roll_integer': dieRollInt,
|
|
||||||
'math.exp': Math.exp,
|
|
||||||
'math.floor': Math.floor,
|
|
||||||
'math.hermite_blend': hermiteBlend,
|
|
||||||
'math.lerp': lerp,
|
|
||||||
'math.lerp_rotate': lerprotate,
|
|
||||||
'math.ln': Math.log,
|
|
||||||
'math.max': Math.max,
|
|
||||||
'math.min': Math.min,
|
|
||||||
'math.min_angle': minAngle,
|
|
||||||
'math.mod': mod,
|
|
||||||
'math.pi': Math.PI,
|
|
||||||
'math.pow': Math.pow,
|
|
||||||
'math.random': random,
|
|
||||||
'math.random_integer': randomInt,
|
|
||||||
'math.round': Math.round,
|
|
||||||
'math.sin': (x: number) => Math.sin(x * degRadFactor),
|
|
||||||
'math.sqrt': Math.sqrt,
|
|
||||||
'math.trunc': Math.trunc,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
25
packages/molang/src/env/queries.ts
vendored
25
packages/molang/src/env/queries.ts
vendored
@@ -1,25 +0,0 @@
|
|||||||
const inRange = (value: number, min: number, max: number) => {
|
|
||||||
// Check that value, min and max are numbers
|
|
||||||
if (
|
|
||||||
typeof value !== 'number' ||
|
|
||||||
typeof min !== 'number' ||
|
|
||||||
typeof max !== 'number'
|
|
||||||
) {
|
|
||||||
console.error('"query.in_range": value, min and max must be numbers')
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return value >= min && value <= max
|
|
||||||
}
|
|
||||||
|
|
||||||
const all = (mustMatch: unknown, ...values: unknown[]) =>
|
|
||||||
values.every((v) => v === mustMatch)
|
|
||||||
|
|
||||||
const any = (mustMatch: unknown, ...values: unknown[]) =>
|
|
||||||
values.some((v) => v === mustMatch)
|
|
||||||
|
|
||||||
export const standardQueries = {
|
|
||||||
'query.in_range': inRange,
|
|
||||||
'query.all': all,
|
|
||||||
'query.any': any,
|
|
||||||
}
|
|
||||||
7
packages/molang/src/env/standardEnv.ts
vendored
7
packages/molang/src/env/standardEnv.ts
vendored
@@ -1,7 +0,0 @@
|
|||||||
import { MoLangMathLib } from './math'
|
|
||||||
import { standardQueries } from './queries'
|
|
||||||
|
|
||||||
export const standardEnv = (useRadians: boolean) => ({
|
|
||||||
...MoLangMathLib(useRadians),
|
|
||||||
...standardQueries,
|
|
||||||
})
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export * from './main'
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
import { TVariableHandler } from './env/env'
|
|
||||||
import { Tokenizer } from './tokenizer/Tokenizer'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* How the parser and interpreter should handle your MoLang expression
|
|
||||||
*/
|
|
||||||
|
|
||||||
export interface IParserConfig {
|
|
||||||
/**
|
|
||||||
* Whether a cache should be used to speed up executing MoLang.
|
|
||||||
* The cache saves an AST for every parsed expression.
|
|
||||||
* This allows us to skip the tokenization & parsing step before executing known MoLang expressions
|
|
||||||
*
|
|
||||||
* Default: true
|
|
||||||
*/
|
|
||||||
useCache: boolean
|
|
||||||
/**
|
|
||||||
* How many expressions can be cached. After reaching `maxCacheSize`, the whole cache is cleared automatically.
|
|
||||||
* Can be set to `Infinity` to remove the limit completely
|
|
||||||
*
|
|
||||||
* Default: 256
|
|
||||||
*/
|
|
||||||
maxCacheSize: number
|
|
||||||
/**
|
|
||||||
* The optimizer can drastically speed up parsing & executing MoLang.
|
|
||||||
* It enables skipping of unreachable statements, pre-evaluating static expressions and skipping of statements with no effect
|
|
||||||
* when used together with the `useAgressiveStaticOptimizer` option
|
|
||||||
*
|
|
||||||
* Default: true
|
|
||||||
*/
|
|
||||||
useOptimizer: boolean
|
|
||||||
/**
|
|
||||||
* Skip execution of statements with no effect
|
|
||||||
* when used together with the `useOptimizer` option
|
|
||||||
*
|
|
||||||
* Default: true
|
|
||||||
*/
|
|
||||||
useAgressiveStaticOptimizer: boolean
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This options makes early return statements skip all parsing work completely
|
|
||||||
*
|
|
||||||
* Default: true
|
|
||||||
*/
|
|
||||||
earlyReturnsSkipParsing: boolean
|
|
||||||
/**
|
|
||||||
* This options makes early return statements skip all tokenization work completely if earlyReturnsSkipParsing is set to true
|
|
||||||
*
|
|
||||||
* Default: true
|
|
||||||
*/
|
|
||||||
earlyReturnsSkipTokenization: boolean
|
|
||||||
/**
|
|
||||||
* Tokenizer to use for tokenizing the expression
|
|
||||||
*/
|
|
||||||
tokenizer: Tokenizer
|
|
||||||
/**
|
|
||||||
* Create expression instances for brackets ("()", "{}")
|
|
||||||
*
|
|
||||||
* This should only be set to true if you want to use the .toString() method of an expression
|
|
||||||
* or you want to iterate over the whole AST
|
|
||||||
*
|
|
||||||
* Default: false
|
|
||||||
*/
|
|
||||||
keepGroups: boolean
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whether to convert undefined variables to "0"
|
|
||||||
*
|
|
||||||
* Default: false
|
|
||||||
*/
|
|
||||||
convertUndefined: boolean
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Use radians instead of degrees for trigonometric functions
|
|
||||||
*
|
|
||||||
* Default: false
|
|
||||||
*/
|
|
||||||
useRadians: boolean
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolve undefined variables
|
|
||||||
*/
|
|
||||||
variableHandler: TVariableHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Tokenizer } from './tokenizer/Tokenizer'
|
|
||||||
export { IExpression } from './parser/expression'
|
|
||||||
export { CustomMoLang } from './custom/main'
|
|
||||||
export { MoLang } from './MoLang'
|
|
||||||
export * as expressions from './parser/expressions/index'
|
|
||||||
export { Context } from './env/env'
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
/**
|
|
||||||
* Interface that describes an AST Expression
|
|
||||||
*/
|
|
||||||
export interface IExpression {
|
|
||||||
readonly type: string
|
|
||||||
readonly isReturn?: boolean
|
|
||||||
readonly isBreak?: boolean
|
|
||||||
readonly isContinue?: boolean
|
|
||||||
readonly allExpressions: IExpression[]
|
|
||||||
|
|
||||||
setFunctionCall?: (value: boolean) => void
|
|
||||||
setPointer?: (value: unknown) => void
|
|
||||||
setExpressionAt(index: number, expr: IExpression): void
|
|
||||||
eval(): unknown
|
|
||||||
isStatic(): boolean
|
|
||||||
walk(cb: TIterateCallback): IExpression
|
|
||||||
iterate(cb: TIterateCallback, visited: Set<IExpression>): void
|
|
||||||
}
|
|
||||||
|
|
||||||
export abstract class Expression implements IExpression {
|
|
||||||
public abstract readonly type: string
|
|
||||||
|
|
||||||
abstract eval(): unknown
|
|
||||||
abstract isStatic(): boolean
|
|
||||||
|
|
||||||
toString() {
|
|
||||||
return `${this.eval()}`
|
|
||||||
}
|
|
||||||
|
|
||||||
abstract allExpressions: IExpression[]
|
|
||||||
abstract setExpressionAt(index: number, expr: IExpression): void
|
|
||||||
|
|
||||||
walk(cb: TIterateCallback, visited = new Set<IExpression>()): IExpression {
|
|
||||||
let expr = cb(this) ?? this
|
|
||||||
|
|
||||||
expr.iterate(cb, visited)
|
|
||||||
|
|
||||||
return expr
|
|
||||||
}
|
|
||||||
iterate(cb: TIterateCallback, visited: Set<IExpression>) {
|
|
||||||
for (let i = 0; i < this.allExpressions.length; i++) {
|
|
||||||
const originalExpr = this.allExpressions[i]
|
|
||||||
if (visited.has(originalExpr)) continue
|
|
||||||
else visited.add(originalExpr)
|
|
||||||
|
|
||||||
const expr = cb(originalExpr) ?? originalExpr
|
|
||||||
|
|
||||||
if (expr !== originalExpr && visited.has(expr)) continue
|
|
||||||
else visited.add(expr)
|
|
||||||
|
|
||||||
this.setExpressionAt(i, expr)
|
|
||||||
expr.iterate(cb, visited)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export type TIterateCallback = (expr: IExpression) => IExpression | undefined
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
import { Expression, IExpression } from '../expression'
|
|
||||||
|
|
||||||
export class ArrayAccessExpression extends Expression {
|
|
||||||
type = 'ArrayAccessExpression'
|
|
||||||
constructor(protected name: IExpression, protected lookup: IExpression) {
|
|
||||||
super()
|
|
||||||
}
|
|
||||||
|
|
||||||
get allExpressions() {
|
|
||||||
return [this.name, this.lookup]
|
|
||||||
}
|
|
||||||
setExpressionAt(index: number, expr: IExpression) {
|
|
||||||
if (index === 0) this.name = expr
|
|
||||||
else if (index === 1) this.lookup = expr
|
|
||||||
}
|
|
||||||
|
|
||||||
isStatic() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
setPointer(value: unknown) {
|
|
||||||
;(<any>this.name.eval())[<number>this.lookup.eval()] = value
|
|
||||||
}
|
|
||||||
|
|
||||||
eval() {
|
|
||||||
return (<any>this.name.eval())[<number>this.lookup.eval()]
|
|
||||||
}
|
|
||||||
|
|
||||||
toString() {
|
|
||||||
return `${this.name.toString()}[${this.lookup.toString()}]`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import { Expression } from '../expression'
|
|
||||||
|
|
||||||
export class BooleanExpression extends Expression {
|
|
||||||
type = 'BooleanExpression'
|
|
||||||
constructor(protected value: boolean) {
|
|
||||||
super()
|
|
||||||
}
|
|
||||||
|
|
||||||
get allExpressions() {
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
setExpressionAt() {}
|
|
||||||
|
|
||||||
isStatic() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
eval() {
|
|
||||||
return this.value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user