Compare commits
435 Commits
v0.10.1
...
v0.28.0-be
| Author | SHA1 | Date | |
|---|---|---|---|
| 1d26a1e318 | |||
| 5f5df3452d | |||
| fce3c1a284 | |||
| 21b35b0036 | |||
| 2b7588cf04 | |||
| 4435a239d4 | |||
| 4cc5e75f1d | |||
| 188641d57a | |||
| 9a25362140 | |||
| 54eaae96bd | |||
| 5bf4b1c09e | |||
| 54bea62735 | |||
| 0e4ae5d74f | |||
| bdad4136ec | |||
| a0866c1085 | |||
| afd3f91a3f | |||
| e70c78a255 | |||
| 9cfac1672a | |||
| 9126ec8035 | |||
| 23bc6068b5 | |||
| 27b428fbe2 | |||
| c07f1131c4 | |||
| 002f2c47c6 | |||
| 8633d9ea95 | |||
| 07a5d0c8de | |||
| dd76e563c8 | |||
| 7b85ff5b7c | |||
| 359aeb9d63 | |||
| 3901d9fb5f | |||
| c2867da047 | |||
| 65832c9fae | |||
| d9dffa704d | |||
| b39f29de6a | |||
| 56334c6f6e | |||
| 72673b2a67 | |||
| 597bdb721a | |||
| 6e0456d777 | |||
| fb67b06230 | |||
| 203560dcf2 | |||
| 3f58f5992c | |||
| ac16754c9c | |||
| 42d637dd63 | |||
| df0d246136 | |||
| e563e1b507 | |||
| 3b822c613a | |||
| 2967c2a1fe | |||
| 1c579c9789 | |||
| 2fe9bce2ea | |||
| 496d278a93 | |||
| bdf674b678 | |||
| 67fe13deac | |||
| 30846cdc87 | |||
| d8d03149df | |||
| b6d7847a79 | |||
| 58f59f8260 | |||
| f3fa14990f | |||
| 15d1f8392b | |||
| b5fac23c5c | |||
| 148f6c28c4 | |||
| 880065495e | |||
| 7fc70a92d5 | |||
| df6da12a8a | |||
| 082f2b8f73 | |||
| 7cd85f3f34 | |||
| 073cf6aaac | |||
| 43aa39b86f | |||
| cb58fbdb6c | |||
| 86aacf1a1f | |||
| 47413c6766 | |||
| 4ee8fc9a20 | |||
| 8d0484eefb | |||
| 579d89ae89 | |||
| 010f561766 | |||
| 848aacd991 | |||
| ab5559b26f | |||
| 46729b9cf0 | |||
| 83cad2f52e | |||
| a5cb084767 | |||
| 16ab108186 | |||
| a1df719dc9 | |||
| 41e5754492 | |||
| 866d1dd62c | |||
| 8056d3060d | |||
| b8440b83de | |||
| b55e662f81 | |||
| db526e9444 | |||
| 1b0ea9fa05 | |||
| 143c960da5 | |||
| 30fd065bc5 | |||
| f4c04829b1 | |||
| 6816e51239 | |||
| 5ed61829e1 | |||
| 72173b4778 | |||
| 4ee300a22b | |||
| 476d98b9c7 | |||
| cf9153c134 | |||
| b3fa8790e3 | |||
| 27dafe3307 | |||
| 53502e12cf | |||
| 774763be13 | |||
| cabf09e247 | |||
| 2fd10140cf | |||
| 7afea75454 | |||
| 8a2b0d7c2e | |||
| 586b6acbbc | |||
| def62e2940 | |||
| 18329f0a4c | |||
| 39612a1ff3 | |||
| ea1dd6f9ae | |||
| 66eaf6b8b0 | |||
| 157782b43e | |||
| 51fd13e734 | |||
| 293c69a605 | |||
| 88e59231da | |||
| 02dbf535bc | |||
| a4368cc9ba | |||
| dbe9657b26 | |||
| d486e2ab19 | |||
| 293b4e265b | |||
| bf34552321 | |||
| 4f41357953 | |||
| b2177683de | |||
| 081a934747 | |||
| 4f5c9bafa1 | |||
| 1ff3a5ae62 | |||
| 93f44e5a00 | |||
| 67aa4302e0 | |||
| df1646dc15 | |||
| 48cc6325b8 | |||
| f42d5d12ed | |||
| 6617171472 | |||
| f35c8cd3fb | |||
|
|
aa182fb169 | ||
| 8a15a5398f | |||
| ad85c3bc9b | |||
| a3cbe455a1 | |||
|
|
f7a228975f | ||
| 299a8e7791 | |||
| af1e64767a | |||
| f31726e98b | |||
| 4bb2337f39 | |||
| c5fac44362 | |||
|
|
d7e757bcf8 | ||
| c013d0eec5 | |||
| 7f5929bc87 | |||
| d769a9c8ca | |||
| c64d167893 | |||
| 0776d0ddeb | |||
| 3f101ca250 | |||
| 85f2bd5a10 | |||
| c172bcfad7 | |||
| 1d2a528bbb | |||
| d80e858a89 | |||
| 24fc6dc464 | |||
| e38666f12d | |||
| c7079dd82e | |||
| 0fea6b5537 | |||
| 00a84fb58a | |||
| 80fbc071ed | |||
| 14f20897d6 | |||
| a84b82d206 | |||
| 80111d5ada | |||
| fb7e27af82 | |||
| e9a2aa9745 | |||
| 4741e341b7 | |||
| 1b4b249859 | |||
| 78100e8696 | |||
| d0a0e2dd71 | |||
| 7962aa5da0 | |||
| 0667201605 | |||
| afd04ed972 | |||
| 9c137574f5 | |||
| 6597b261fd | |||
| 8432f7fbab | |||
| e731de2162 | |||
| b87fb08d1c | |||
| e7077b1315 | |||
| 05e9feee9b | |||
| af85703bd9 | |||
| 68a996f830 | |||
| 8f944e0b14 | |||
| 6910ea3e26 | |||
| d01938487a | |||
| 606f097989 | |||
| a3cf4fa476 | |||
| 3c1ff6ea41 | |||
| 2990cdc4aa | |||
| f301d130f9 | |||
| 0ae4764c85 | |||
| 8def6257df | |||
| f62d198166 | |||
| 0c71bc3582 | |||
| ea99cbea1d | |||
| b400ab81f0 | |||
| 63ff11def1 | |||
| b1a4c65adb | |||
| 9b28cd4de0 | |||
| e55d48d713 | |||
| 3ea72f0aac | |||
| fe1ee3883a | |||
| 083a01f29f | |||
| 0b0a3bb836 | |||
| 9bb8278477 | |||
| 92647fbea2 | |||
| 1928551023 | |||
| 018889b5eb | |||
| 05244f9bef | |||
| 36c9d4ad99 | |||
| 0bc513d580 | |||
| 678f4ca8a4 | |||
| f4aa568f0c | |||
| 1bb938dcbd | |||
| dc4e554a35 | |||
| 7c016f6ba6 | |||
| cfef52aecd | |||
| 53ee92e20d | |||
| 9b5a303c21 | |||
| 4c0a77ed23 | |||
| 46173ff549 | |||
| 2fb7ddd890 | |||
| e2505597ff | |||
| 17ed9d7d52 | |||
| 5a9e33e695 | |||
| b98409abe7 | |||
| 5420ad460c | |||
| 9587a748eb | |||
| ac2a4f3d6e | |||
| d888d9ab4e | |||
| 2582d51a98 | |||
| 843b65f13b | |||
| c2857a0566 | |||
| 684a033525 | |||
| 503ca79dab | |||
| 46768e4cdd | |||
| f61360f739 | |||
| 8fbf9ef29d | |||
| d6138bc6f4 | |||
| c37a7cb772 | |||
| 4e1a77cc50 | |||
| d614b3741e | |||
| 738bc50939 | |||
| 167abfe3d9 | |||
| aab5c86588 | |||
| 5cd02ac08a | |||
| 0b67ddce42 | |||
| 1e2c17456e | |||
| 8731f5d9ef | |||
| fb3803cae9 | |||
| 84e4052871 | |||
| 2dc662a4d4 | |||
| 2b017d9208 | |||
| 0ca8ae944c | |||
| 1e03b104df | |||
| 7ba34e7e01 | |||
| c016b1db34 | |||
| 3d1ed08473 | |||
| 34ee276556 | |||
| 53f20a9a8f | |||
| 76fd6b8318 | |||
| dfff666284 | |||
| 44fab858d3 | |||
| fea58a4dd6 | |||
| 71308a13a1 | |||
| 34f9b088c7 | |||
| 70929d7ceb | |||
| 2beca068a4 | |||
| e0ab8a5a7b | |||
| e6f9326ae3 | |||
| 58cbacdc85 | |||
| dcbdbcfcdc | |||
| 1662e8e0e9 | |||
| 73fa62a23e | |||
| ca79161505 | |||
| be4fe82588 | |||
| 8ec21a7f99 | |||
| 1431ce0a6e | |||
| e9c13e44b4 | |||
| 6b838ae55d | |||
| de99c0dd92 | |||
| b92cfccb84 | |||
| b03c311956 | |||
| a164f08e1e | |||
| d850c4a16f | |||
| 17fbfabff5 | |||
| e84882e076 | |||
| f224b417bb | |||
| f9458e66c1 | |||
| d22cb515f7 | |||
| 595e11ddfd | |||
| 328d93cd3f | |||
| ccaa268362 | |||
| b04f4899ca | |||
| 4677fba701 | |||
| cbfbc28504 | |||
| 2042b49e0d | |||
| aee0457d9f | |||
| 9b69b1221b | |||
| cbb73b451f | |||
| 5844ca9e7d | |||
| b6318cb8c1 | |||
| efd1e5bd62 | |||
| 5549bdd804 | |||
| 926fc3b17a | |||
| 9dae44278d | |||
| 2fb62b26a0 | |||
| a1e50285a9 | |||
| 25dbefef6f | |||
| 5ef16c5f21 | |||
| 5f0075272c | |||
| 38469741fd | |||
| bbc6058347 | |||
| 2254f22936 | |||
| 9de4038788 | |||
| 0f8243a7ad | |||
| 95ac5d1800 | |||
| 5132019ce6 | |||
| d7061c0c9d | |||
| f28a1e3c66 | |||
| cf3f840b3c | |||
| 12b3973b38 | |||
| b95b4f6928 | |||
| f821998801 | |||
| 27b5642047 | |||
| 85b3bba5d0 | |||
| 343f4ba04b | |||
| 00b27e8999 | |||
| 97877832c4 | |||
| 33d29271f9 | |||
| 9f0e732e37 | |||
| c2b3372d74 | |||
| 8a0fcfae8b | |||
| 08ca3db67b | |||
| 813f761e47 | |||
| 5728c48f16 | |||
| 106abc76e1 | |||
| 6a5b1598d4 | |||
| 0ade2b2855 | |||
| 6cf446e54b | |||
| da07acc6b0 | |||
| f7207d99ba | |||
| 57f2b37401 | |||
| 8f864222ae | |||
| c33b78b029 | |||
| b5b9d3f230 | |||
| 93fa3e2460 | |||
| c1ef761ec7 | |||
| 19e7692756 | |||
| 0fbccbc05f | |||
| b2a24943a4 | |||
| 063fc51f40 | |||
| 126789d49a | |||
| 21394a3b4b | |||
| 11c91600da | |||
| c13c4aefca | |||
| 4fa67549fb | |||
| 26f4c24659 | |||
| 82cf6e6f53 | |||
| e3f3f9ca4e | |||
| 24d77ea34d | |||
| b28da75420 | |||
| caa30083d3 | |||
| 2ddd8c3879 | |||
| 1eefb729d7 | |||
| b6f3a31eca | |||
| d1b6a4d4b2 | |||
| 81fa66684a | |||
| 0b6c174e42 | |||
| bf33381e30 | |||
| 44422d4dcf | |||
| 97b499c0b4 | |||
| 8ccfe499df | |||
| f6df0a2c47 | |||
| e2f32fd0bf | |||
| 1e00dc6530 | |||
| de491bdd62 | |||
| 30ec92fd65 | |||
| f869a524ff | |||
| 72627c08bc | |||
| 0595c3c046 | |||
| 2063a2484d | |||
| a0304183c4 | |||
| e442da5b3b | |||
| 54d12749dc | |||
| 7955f1663a | |||
| 032ef3e37d | |||
| d500546236 | |||
| c9d62cc617 | |||
| fb37d46acc | |||
| 5099430289 | |||
| 73690a2668 | |||
| 7ab3443351 | |||
| b60259c345 | |||
| 7b67dc7719 | |||
| 5a29133561 | |||
| c0106e941b | |||
| 736760b2ee | |||
| 83cc4b6a54 | |||
| 24013bf240 | |||
| a3cf7eb036 | |||
| 0012da9855 | |||
| 364463dc6a | |||
| 8e94683757 | |||
| e1530c49ee | |||
| 4c0290bf21 | |||
| 10cb22c510 | |||
| b939c7c891 | |||
| 032f4d98ae | |||
| ae1519ea4f | |||
| a96756e1ac | |||
| 35f2dbf162 | |||
| c153f9babb | |||
| 0c8d3a04bd | |||
| 0491e6fac9 | |||
| 7137325491 | |||
| 8f183d1ca3 | |||
| db800a4038 | |||
| a851bb543b | |||
| 81c76f4977 | |||
| 7ca81db573 | |||
| b0915648ea | |||
| 9121683e77 | |||
| 8f5882ff0a | |||
| 38bd2f5187 | |||
| 514ac27aca | |||
| 60f6a4e18d | |||
| 046c86681b | |||
| 5ea4b6bdaf | |||
| 500384326f | |||
| eb1bab7e76 | |||
| 928f73a4bf | |||
| c3522aea64 | |||
| e5bab5763c | |||
| 34c598e6d8 | |||
| d06321d9b5 | |||
| bee7e19fc3 |
12
.editorconfig
Normal file
12
.editorconfig
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
# 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
|
||||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,4 +1,4 @@
|
|||||||
|
.yarn*
|
||||||
|
.vscode
|
||||||
node_modules
|
node_modules
|
||||||
dist
|
dist
|
||||||
package-lock.json
|
|
||||||
yarn.lock
|
|
||||||
|
|||||||
10
.gitpod.Dockerfile
vendored
Normal file
10
.gitpod.Dockerfile
vendored
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
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/
|
||||||
5
.gitpod.yml
Normal file
5
.gitpod.yml
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
tasks:
|
||||||
|
- init: yarn && yarn bs && yarn build
|
||||||
|
command: yarn watch
|
||||||
|
# image:
|
||||||
|
# file: .gitpod.Dockerfile
|
||||||
35
README.MD
Normal file
35
README.MD
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
# MiaoScript implement
|
||||||
|
|
||||||
|
## MiaoScript JS 实现
|
||||||
|
|
||||||
|
项目 由 TypeScript 进行编写 然后编译至 `es5` 用于兼容 Java8 的 `Nashorn`
|
||||||
|
|
||||||
|
### Project Path
|
||||||
|
|
||||||
|
```txt
|
||||||
|
└─packages
|
||||||
|
├─api 全平台兼容的接口
|
||||||
|
├─core 核心代码 用于引导加载
|
||||||
|
├─common 公共类库代码 例如 http reflect 模块
|
||||||
|
├─compile 编译器相关功能
|
||||||
|
├─client NodeJS 的 Minecraft 客户端 已迁移至 ms-client
|
||||||
|
├─container IOC容器 用于注入具体实现
|
||||||
|
├─database 数据库相关功能
|
||||||
|
├─protocol 协议处理相关功能
|
||||||
|
├─service 服务相关功能
|
||||||
|
├─i18n 多语言环境相关支持
|
||||||
|
├─polyfill Nashorn 的一些自定义增强
|
||||||
|
├─nashorn Nashorn 的类型定义
|
||||||
|
├─nodejs NodeJS 的部分 Java 实现
|
||||||
|
├─bungee BungeeCordAPI 内部实现
|
||||||
|
├─bukkit BukkitAPI 内部实现
|
||||||
|
├─sponge SpongeAPI 内部实现
|
||||||
|
├─nukkit NukkitAPI 内部实现
|
||||||
|
├─molang MoLang 解析库
|
||||||
|
├─qrcode 二维码相关类库
|
||||||
|
├─plugin 插件管理器
|
||||||
|
├─websocket WebSocket 相关实现
|
||||||
|
| ├─client 基于 Netty 的 WebSocket 客户端
|
||||||
|
| └─server 基于 Netty 的 WebSocket 服务端
|
||||||
|
└─type 类型定义 已迁移到 @javatypes
|
||||||
|
```
|
||||||
11
doc/MCBBS.MD
Normal file
11
doc/MCBBS.MD
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
- 构建状态 [](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/)
|
||||||
|
- 当前版本 
|
||||||
|
- 下载地址 [](http://w.yumc.pw/free.html#MiaoScript-download)
|
||||||
|
- 更新日志 [](https://docs.yumc.pw/MiaoScript/CHANGELOG.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)
|
||||||
|
- 兼容服务端 Spigot CatServer Sponge BungeeCord Nukkit(没错 他还兼容Nukkit)
|
||||||
|
|
||||||
|
### 腐竹版本(开发中)
|
||||||
|
|
||||||
|
- 先上几张图
|
||||||
24
lerna.json
24
lerna.json
@@ -1,16 +1,12 @@
|
|||||||
{
|
{
|
||||||
"version": "0.0.0",
|
"version": "0.28.0-beta.7",
|
||||||
"useWorkspaces": true,
|
"npmClient": "pnpm",
|
||||||
"npmClient": "yarn",
|
"command": {
|
||||||
"packages": [
|
"run": {
|
||||||
"packages/*"
|
"stream": true
|
||||||
],
|
|
||||||
"command": {
|
|
||||||
"run": {
|
|
||||||
"stream": true
|
|
||||||
},
|
|
||||||
"publish": {
|
|
||||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
"publishConfig": {
|
||||||
|
"access": "public"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
33
package.json
33
package.json
@@ -6,15 +6,30 @@
|
|||||||
"author": "MiaoWoo <admin@yumc.pw>",
|
"author": "MiaoWoo <admin@yumc.pw>",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "npx lerna run clean",
|
"bs": "pnpm install",
|
||||||
"watch": "npx lerna run watch --parallel",
|
"clean": "lerna run clean",
|
||||||
"build": "npx lerna run build",
|
"watch": "lerna run watch --parallel",
|
||||||
"lp": "npx lerna publish"
|
"build": "lerna run build",
|
||||||
|
"ug": "pnpm up -r -i",
|
||||||
|
"np": "./script/push.sh",
|
||||||
|
"lsp": "npm login -scope=@ccms",
|
||||||
|
"lp": "lerna publish --force-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 --yes",
|
||||||
|
"sync": "./script/sync.sh",
|
||||||
|
"postpublish": "pnpm sync"
|
||||||
},
|
},
|
||||||
"workspaces": [
|
|
||||||
"packages/*"
|
|
||||||
],
|
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"lerna": "^3.16.4"
|
"@ccms/nashorn": "^0.28.0-beta.3",
|
||||||
|
"@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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
4
packages/api/.gitignore
vendored
4
packages/api/.gitignore
vendored
@@ -1,4 +0,0 @@
|
|||||||
/node_modules
|
|
||||||
/dist
|
|
||||||
/package-lock.json
|
|
||||||
/yarn.lock
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
src
|
|
||||||
test
|
|
||||||
typings
|
|
||||||
bundled
|
|
||||||
build
|
|
||||||
coverage
|
|
||||||
docs
|
|
||||||
wiki
|
|
||||||
gulpfile.js
|
|
||||||
bower.json
|
|
||||||
karma.conf.js
|
|
||||||
tsconfig.json
|
|
||||||
typings.json
|
|
||||||
CONTRIBUTING.md
|
|
||||||
ISSUE_TEMPLATE.md
|
|
||||||
PULL_REQUEST_TEMPLATE.md
|
|
||||||
tslint.json
|
|
||||||
wallaby.js
|
|
||||||
.travis.yml
|
|
||||||
.gitignore
|
|
||||||
.vscode
|
|
||||||
type_definitions
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/api",
|
"name": "@ccms/api",
|
||||||
"version": "0.0.0",
|
"version": "0.28.0-beta.7",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -12,22 +12,26 @@
|
|||||||
"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",
|
||||||
"publishConfig": {
|
"files": [
|
||||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
"dist/*.js",
|
||||||
},
|
"dist/*.ts",
|
||||||
|
"dist/*.map"
|
||||||
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "pnpm clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/common": "^0.0.0",
|
"@ccms/common": "^0.28.0-beta.7",
|
||||||
"@ms/container": "^0.0.0"
|
"@ccms/container": "^0.28.0-beta.7",
|
||||||
|
"@ccms/i18n": "^0.28.0-beta.7",
|
||||||
|
"@ccms/polyfill": "^0.28.0-beta.7",
|
||||||
|
"base64-js": "^1.5.1",
|
||||||
|
"source-map-builder": "^0.0.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"@types/base64-js": "^1.3.0"
|
||||||
"rimraf": "^3.0.0",
|
|
||||||
"typescript": "^3.6.2"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
66
packages/api/src/channel.ts
Normal file
66
packages/api/src/channel.ts
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import { injectable } from "@ccms/container"
|
||||||
|
|
||||||
|
export namespace channel {
|
||||||
|
/**
|
||||||
|
* handle plugin message
|
||||||
|
* @param data byte[]
|
||||||
|
*/
|
||||||
|
export type ChannelListener = (data: any, exts?: any) => void
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export abstract class Channel {
|
||||||
|
private listenerMap = [];
|
||||||
|
/**
|
||||||
|
* 注册通道
|
||||||
|
* @param plugin 插件
|
||||||
|
* @param channel 通道
|
||||||
|
* @param exec 执行器
|
||||||
|
*/
|
||||||
|
listen(plugin: any, channel: string, exec: ChannelListener) {
|
||||||
|
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!')
|
||||||
|
let name = plugin.description.name
|
||||||
|
let listener = this.register(channel, exec)
|
||||||
|
if (!this.listenerMap[name]) this.listenerMap[name] = []
|
||||||
|
let offExec = () => {
|
||||||
|
this.unregister(channel, listener)
|
||||||
|
console.debug(`[${name}] unregister channel ${channel}`)
|
||||||
|
}
|
||||||
|
var off = {
|
||||||
|
channel,
|
||||||
|
listener,
|
||||||
|
off: offExec
|
||||||
|
}
|
||||||
|
this.listenerMap[name].push(off)
|
||||||
|
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`)
|
||||||
|
return off
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 关闭插件注册的通道
|
||||||
|
* @param plugin 插件
|
||||||
|
*/
|
||||||
|
disable(plugin: any) {
|
||||||
|
var channelCache = this.listenerMap[plugin.description.name]
|
||||||
|
if (channelCache) {
|
||||||
|
channelCache.forEach(t => t.off())
|
||||||
|
delete this.listenerMap[plugin.description.name]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Send Channel Message
|
||||||
|
* @param player recover target
|
||||||
|
* @param channel ChannelName
|
||||||
|
* @param data byte[]
|
||||||
|
*/
|
||||||
|
abstract send(player: any, channel: string, data: any)
|
||||||
|
/**
|
||||||
|
* register channel
|
||||||
|
* @param channel ChannelName
|
||||||
|
*/
|
||||||
|
abstract register(channel: string, listener: ChannelListener): any
|
||||||
|
/**
|
||||||
|
* unregister channel
|
||||||
|
* @param channel ChannelName
|
||||||
|
*/
|
||||||
|
abstract unregister(channel: string, listener?: any): void
|
||||||
|
}
|
||||||
|
}
|
||||||
31
packages/api/src/chat.ts
Normal file
31
packages/api/src/chat.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
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,25 +1,125 @@
|
|||||||
import { injectable } from "@ms/container";
|
import i18n from '@ccms/i18n'
|
||||||
|
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 {
|
||||||
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
|
/**
|
||||||
var cmd = this.create(plugin, { name: name });
|
* first time script engine need optimize jit code
|
||||||
console.debug(`插件 ${plugin.description.name} 创建命令 ${name}(${cmd})...`)
|
* so ignore first slow exec notify
|
||||||
|
*/
|
||||||
|
private cacheSlowKeys = {};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册插件命令
|
||||||
|
* @param plugin 插件
|
||||||
|
* @param name 命令
|
||||||
|
* @param exec 执行器
|
||||||
|
*/
|
||||||
|
on(plugin: plugin.Plugin, name: string, exec: { cmd: Function, tab?: Function }) {
|
||||||
|
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 }))
|
||||||
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("CommandExec Must be a function... Input: " + 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.")
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* Create Server Command Object
|
* 取消命令注册
|
||||||
|
* @param plugin 插件
|
||||||
|
* @param name 命令
|
||||||
*/
|
*/
|
||||||
abstract create(plugin: object, opts: { name: string });
|
off(plugin: plugin.Plugin, name: string) {
|
||||||
abstract onCommand(plugin: object, command: any, opts: { name: string });
|
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
|
||||||
abstract onTabComplete(plugin: object, command: any, opts: { name: string });
|
this.remove(plugin, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract create(plugin: plugin.Plugin, command: string): any
|
||||||
|
protected abstract remove(plugin: plugin.Plugin, command: string): void
|
||||||
|
protected abstract onCommand(plugin: plugin.Plugin, command: any, executor: Function)
|
||||||
|
protected abstract onTabComplete(plugin: plugin.Plugin, command: any, tabCompleter: Function)
|
||||||
|
protected setExecutor(plugin: plugin.Plugin, command: any, executor: Function) {
|
||||||
|
return (sender: any, _: any, command: string, args: string[]) => {
|
||||||
|
try {
|
||||||
|
let time = Date.now()
|
||||||
|
let result = executor(sender, command, Java.from(args))
|
||||||
|
this.checkSlow(Date.now() - time,
|
||||||
|
"ms.api.command.execute.slow",
|
||||||
|
plugin, command, sender, args)
|
||||||
|
return result
|
||||||
|
} catch (ex: any) {
|
||||||
|
this.printError(ex, "ms.api.command.execute.error",
|
||||||
|
plugin, command, sender, args)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
protected setTabCompleter(plugin: plugin.Plugin, command: any, tabCompleter: Function) {
|
||||||
|
return (sender: any, _: any, command: string, args: string[]) => {
|
||||||
|
try {
|
||||||
|
let time = Date.now()
|
||||||
|
var token = args[args.length - 1]
|
||||||
|
var complete = tabCompleter(sender, command, Java.from(args)) || []
|
||||||
|
let result = this.copyPartialMatches(complete, token)
|
||||||
|
this.checkSlow(Date.now() - time,
|
||||||
|
"ms.api.command.tab.completer.slow",
|
||||||
|
plugin, command, sender, args)
|
||||||
|
return result
|
||||||
|
} 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[] {
|
||||||
|
if (!token) { return complete }
|
||||||
|
complete.forEach(function (e) {
|
||||||
|
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
|
||||||
|
array.push(e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
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)])
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,148 +1,260 @@
|
|||||||
let Arrays = Java.type('java.util.Arrays');
|
import i18m from '@ccms/i18n'
|
||||||
let Level = Java.type('java.util.logging.Level');
|
import { SourceMapBuilder } from 'source-map-builder'
|
||||||
let ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.'];
|
import * as base64 from 'base64-js'
|
||||||
|
|
||||||
|
const Arrays = Java.type('java.util.Arrays')
|
||||||
|
const Level = Java.type('java.util.logging.Level')
|
||||||
|
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']
|
||||||
|
|
||||||
|
enum LogLevel {
|
||||||
|
ALL,
|
||||||
|
TRACE,
|
||||||
|
DEBUG,
|
||||||
|
INFO,
|
||||||
|
WARN,
|
||||||
|
ERROR,
|
||||||
|
FATAL,
|
||||||
|
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) {
|
||||||
|
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: NodeJS.ConsoleConstructor;
|
Console: any
|
||||||
|
memory: any
|
||||||
|
|
||||||
private _name: 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) {
|
||||||
|
this._level = LogLevel.DEBUG
|
||||||
|
}
|
||||||
|
if (global.level?.toUpperCase() === "TRACE") {
|
||||||
|
this._level = LogLevel.TRACE
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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}] `
|
||||||
// noinspection JSUnusedGlobalSymbols
|
this.prefix = `§6[§cMS§6][§b${name}§6]§r `
|
||||||
this.prefix = `§6[§cMS§6][§b${name}§6]§r `;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log(...args): void {
|
|
||||||
this.logger.info(this.name + args.join(' '));
|
log(...args: any[]): void {
|
||||||
|
this.logger.info(this.name + args.join(' '))
|
||||||
}
|
}
|
||||||
info(...args) {
|
info(...args: any[]) {
|
||||||
this.logger.info(this.name + args.join(' '));
|
this.logger.info(this.name + args.join(' '))
|
||||||
};
|
}
|
||||||
warn(...args) {
|
warn(...args: any[]) {
|
||||||
this.logger.warning(this.name + args.join(' '));
|
this.logger.warning(this.name + args.join(' '))
|
||||||
};
|
}
|
||||||
error(...args) {
|
error(...args: any[]) {
|
||||||
this.logger.log(Level.SEVERE, this.name + args.join(' '));
|
this.logger.log(Level.SEVERE, this.name + args.join(' '))
|
||||||
};
|
}
|
||||||
debug(...args) {
|
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 {
|
||||||
|
if (this._level <= LogLevel.TRACE) {
|
||||||
|
this.logger.info(this.name + '[TRACE] ' + args.join(' '))
|
||||||
|
}
|
||||||
|
}
|
||||||
sender(...args) {
|
sender(...args) {
|
||||||
this.info(args)
|
this.info(args)
|
||||||
}
|
}
|
||||||
console(...args) {
|
console(...args) {
|
||||||
this.info(args)
|
this.info(args)
|
||||||
}
|
}
|
||||||
|
i18n(name: string, param?: { [key: string]: any }) {
|
||||||
|
this.console(i18m.translate(name, param))
|
||||||
|
}
|
||||||
object(obj) {
|
object(obj) {
|
||||||
for (var i in obj) {
|
for (const i in obj) {
|
||||||
this.logger(i, '=>', obj[i])
|
this.info(i, '=>', obj[i])
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
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 | any): string[] {
|
stack(ex: Error, color: boolean = true): string[] {
|
||||||
var stack = ex.getStackTrace();
|
return jsconsole.getStackTrace(ex, color)
|
||||||
var cache = ['§4' + ex];
|
|
||||||
if (stack.class) {
|
|
||||||
stack = Arrays.asList(stack)
|
|
||||||
}
|
|
||||||
stack.forEach(function(trace) {
|
|
||||||
if (trace.className.startsWith('<')) {
|
|
||||||
var fileName = trace.fileName
|
|
||||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
|
||||||
if (fileName.startsWith('/runtime')) { fileName = fileName.split('/runtime')[1] }
|
|
||||||
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${trace.lineNumber}`)
|
|
||||||
} else {
|
|
||||||
var className = trace.className;
|
|
||||||
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
|
||||||
className = className.substr(className.lastIndexOf('$') + 1)
|
|
||||||
} else {
|
|
||||||
for (var prefix in ignoreLogPrefix) {
|
|
||||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${trace.fileName}:${trace.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?: NodeJS.InspectOptions): void {
|
dir(obj: any, options?: any): 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.")
|
||||||
}
|
|
||||||
trace(message?: any, ...optionalParams: any[]): void {
|
|
||||||
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.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
38
packages/api/src/constants.ts
Normal file
38
packages/api/src/constants.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
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 const Method = {
|
||||||
|
getServerConnection: [
|
||||||
|
/*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 = {
|
||||||
|
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'
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export enum ServerType {
|
||||||
|
Bukkit = 'bukkit',
|
||||||
|
Sponge = 'sponge',
|
||||||
|
Nukkit = 'nukkit',
|
||||||
|
Bungee = 'bungee',
|
||||||
|
Spring = 'spring'
|
||||||
|
}
|
||||||
|
}
|
||||||
56
packages/api/src/database.ts
Normal file
56
packages/api/src/database.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,150 +1,205 @@
|
|||||||
'use strict';
|
|
||||||
/**
|
/**
|
||||||
* MiaoScript Event处理类
|
* MiaoScript Event处理类
|
||||||
*/
|
*/
|
||||||
import '@ms/core'
|
import i18n from '@ccms/i18n'
|
||||||
import '@ms/nashorn'
|
import { injectable, unmanaged } from '@ccms/container'
|
||||||
import { injectable } from '@ms/container'
|
|
||||||
|
|
||||||
const Thread = Java.type("java.lang.Thread");
|
const Thread = Java.type('java.lang.Thread')
|
||||||
|
|
||||||
export namespace event {
|
export namespace event {
|
||||||
|
/**
|
||||||
|
* 事件监听优先级
|
||||||
|
*/
|
||||||
|
export enum EventPriority {
|
||||||
|
LOWEST = "LOWEST",
|
||||||
|
LOW = "LOW",
|
||||||
|
NORMAL = "NORMAL",
|
||||||
|
HIGH = "HIGH",
|
||||||
|
HIGHEST = "HIGHEST",
|
||||||
|
MONITOR = "MONITOR",
|
||||||
|
}
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class Event {
|
export abstract class Event {
|
||||||
private mapEvent = [];
|
// export EventPriority to blockly
|
||||||
private listenerMap = [];
|
public EventPriority = EventPriority;
|
||||||
private baseEventDir = '';
|
|
||||||
|
|
||||||
constructor(baseEventDir: string) {
|
private mapEvent = [];
|
||||||
this.baseEventDir = baseEventDir;
|
private pluginEventMap = [];
|
||||||
|
private cacheSlowEventKey = {};
|
||||||
|
|
||||||
|
protected baseEventDir = '';
|
||||||
|
|
||||||
|
constructor(@unmanaged() baseEventDir: string) {
|
||||||
|
this.baseEventDir = baseEventDir
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 扫描包 org.bukkit.event 下的所有事件
|
* abstract event map function
|
||||||
* 映射简写名称 org.bukkit.event.player.PlayerLoginEvent => playerloginevent
|
* ig: org.bukkit.event.player.PlayerLoginEvent => playerloginevent
|
||||||
|
* org.spongepowered.api.event.game.GameRegistryEvent.Register => gameregistryevent$register
|
||||||
*/
|
*/
|
||||||
mapEventName() {
|
mapEventName() {
|
||||||
if (this.baseEventDir === "") {
|
if (this.baseEventDir === "") { throw new Error(i18n.translate('ms.api.event.empty.event.dir')) }
|
||||||
throw new Error("事件基础包名为空 无法进行事件映射!");
|
let count = 0
|
||||||
}
|
let jar = this.getJarFile(this.baseEventDir)
|
||||||
var count = 0;
|
let entries = jar.entries()
|
||||||
var dirs = Thread.currentThread().getContextClassLoader().getResources(this.baseEventDir);
|
while (entries.hasMoreElements()) {
|
||||||
while (dirs.hasMoreElements()) {
|
let entry = entries.nextElement()
|
||||||
var url = dirs.nextElement();
|
let name = entry.name
|
||||||
var protocol = url.protocol;
|
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
|
||||||
if (protocol === "jar") {
|
// replace name to qualifiedName
|
||||||
// noinspection JSUnresolvedVariable
|
let qualifiedName = name.replaceAll('/', '.')
|
||||||
var jar = url.openConnection().jarFile;
|
try {
|
||||||
var entries = jar.entries();
|
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6))
|
||||||
while (entries.hasMoreElements()) {
|
if (this.isValidEvent(clazz)) {
|
||||||
var entry = entries.nextElement();
|
let simpleName = this.class2Name(clazz).toLowerCase()
|
||||||
var name = entry.name;
|
console.trace(i18n.translate("ms.api.event.mapping", { canonicalName: clazz.canonicalName, simpleName }))
|
||||||
// 以 org/bukkit/event 开头 并且以 .class 结尾
|
this.mapEvent[simpleName] = clazz
|
||||||
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
|
count++
|
||||||
var i = name.replaceAll('/', '.');
|
|
||||||
try {
|
|
||||||
var clz = base.getClass(i.substring(0, i.length - 6));
|
|
||||||
// 继承于 org.bukkit.event.Event 访问符为Public
|
|
||||||
if (this.isValidEvent(clz)) {
|
|
||||||
var simpleName = this.class2Name(clz).toLowerCase();
|
|
||||||
console.debug(`Mapping Event [${clz.canonicalName}] => ${simpleName}`);
|
|
||||||
this.mapEvent[simpleName] = clz;
|
|
||||||
count++;
|
|
||||||
}
|
|
||||||
} catch (ex) {
|
|
||||||
//ignore already loaded class
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
} catch (ex: any) {
|
||||||
|
//ignore already loaded class
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return count;
|
return count
|
||||||
};
|
}
|
||||||
|
|
||||||
class2Name(clazz) {
|
getJarFile(resource: string, loader?: any) {
|
||||||
return clazz.simpleName;
|
let dirs = (loader || Thread.currentThread().getContextClassLoader()).getResources(resource)
|
||||||
};
|
if (dirs.hasMoreElements()) {
|
||||||
|
let url = dirs.nextElement()
|
||||||
|
if (url.protocol === "jar") { return url.openConnection().jarFile }
|
||||||
|
}
|
||||||
|
throw new Error(i18n.translate("ms.api.event.resource.not.found", { resource }))
|
||||||
|
}
|
||||||
|
|
||||||
name2Class(name, event) {
|
class2Name(clazz: any) {
|
||||||
var eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
|
return clazz.simpleName
|
||||||
|
}
|
||||||
|
|
||||||
|
name2Class(name: any, event: string) {
|
||||||
|
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event']
|
||||||
if (!eventCls) {
|
if (!eventCls) {
|
||||||
try {
|
try {
|
||||||
eventCls = base.getClass(eventCls);
|
eventCls = base.getClass(event)
|
||||||
this.mapEvent[event] = eventCls;
|
this.mapEvent[event] = eventCls
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
console.console(`§6插件 §b${name} §6注册事件 §c${event} §6失败 §4事件未找到!`);
|
console.i18n("ms.api.event.not.found", { name, event })
|
||||||
console.ex(new Error(`插件 ${name} 注册事件 ${event} 失败 事件未找到!`));
|
return
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return eventCls;
|
return eventCls
|
||||||
};
|
}
|
||||||
|
|
||||||
execute(name, exec, eventCls) {
|
/**
|
||||||
return (...args) => {
|
* 创建命令执行器
|
||||||
|
* @param name 插件名称
|
||||||
|
* @param exec 执行方法
|
||||||
|
* @param eventCls 事件类
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
createExecute(name, exec, eventCls) {
|
||||||
|
return (...args: any[]) => {
|
||||||
|
let event = args[args.length - 1]
|
||||||
try {
|
try {
|
||||||
var time = new Date().getTime()
|
if (!eventCls.isAssignableFrom(event.getClass())) { return }
|
||||||
exec(args[args.length - 1]);
|
let time = Date.now(); exec(event); let cost = Date.now() - time
|
||||||
var cost = new Date().getTime() - time;
|
if (cost > global.ScriptSlowExecuteTime && !event.async) {
|
||||||
if (cost > 20) {
|
let eventKey = `${name}-${this.class2Name(eventCls)}`
|
||||||
console.console(`§c注意! §6插件 §b${name} §6处理 §d${this.class2Name(eventCls)} §6事件 §c耗时 §4${cost}ms !`)
|
if (!this.cacheSlowEventKey[eventKey]) { return this.cacheSlowEventKey[eventKey] = cost }
|
||||||
|
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
|
||||||
}
|
}
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
console.console(`§6插件 §b${name} §6处理 §d${this.class2Name(eventCls)} §6事件时发生异常 §4${ex}`);
|
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
|
||||||
console.ex(ex);
|
console.ex(ex)
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 添加事件监听
|
* 添加事件监听
|
||||||
* @param jsp
|
* @param plugin {any} 插件
|
||||||
* @param event
|
* @param event {string} 事件名称
|
||||||
* @param exec {function}
|
* @param exec {function} 事件执行器
|
||||||
* @param priority [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
|
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR] 优先级
|
||||||
* @param ignoreCancel
|
* @param ignoreCancel 是否忽略已取消事件
|
||||||
*/
|
*/
|
||||||
listen(jsp, event, exec, priority, ignoreCancel) {
|
listen(plugin: any, event: string, exec: (event: any) => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
|
||||||
if (!jsp || !jsp.description || !jsp.description.name) throw new TypeError('插件名称为空 请检查传入参数!');
|
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"))
|
||||||
var name = jsp.description.name;
|
var name = plugin.description.name
|
||||||
var eventCls = this.name2Class(name, event);
|
var eventCls = this.name2Class(name, event)
|
||||||
if (!eventCls) { return; }
|
if (!eventCls) { return () => { console.warn('event ' + event + ' not found ignore off listener.') } }
|
||||||
if (typeof priority === 'boolean') {
|
if (typeof priority === 'boolean') {
|
||||||
ignoreCancel = priority;
|
ignoreCancel = priority
|
||||||
priority = 'NORMAL';
|
priority = EventPriority.NORMAL
|
||||||
}
|
}
|
||||||
priority = priority || 'NORMAL';
|
priority = priority || EventPriority.NORMAL
|
||||||
ignoreCancel = ignoreCancel || false;
|
ignoreCancel = ignoreCancel || false
|
||||||
|
// @ts-ignore
|
||||||
|
let executor = exec.name || exec.executor || '[anonymous]'
|
||||||
// noinspection JSUnusedGlobalSymbols
|
// noinspection JSUnusedGlobalSymbols
|
||||||
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel);
|
let listener = this.register(
|
||||||
var listenerMap = this.listenerMap;
|
eventCls,
|
||||||
// 添加到缓存 用于关闭插件的时候关闭事件
|
this.createExecute(name, exec, eventCls),
|
||||||
if (!listenerMap[name]) listenerMap[name] = [];
|
priority,
|
||||||
var offExec = () => {
|
ignoreCancel
|
||||||
this.unregister(eventCls, listener);
|
)
|
||||||
console.debug(`插件 ${name} 注销事件 ${this.class2Name(eventCls)}`);
|
// add to cache Be used for close plugin to close event
|
||||||
};
|
if (!this.pluginEventMap[name]) this.pluginEventMap[name] = []
|
||||||
var off = {
|
let off = () => {
|
||||||
event: eventCls,
|
if (off['offed']) return
|
||||||
listener: listener,
|
off['offed'] = true
|
||||||
off: offExec
|
this.unregister(eventCls, listener)
|
||||||
};
|
console.debug(i18n.translate("ms.api.event.unregister", {
|
||||||
listenerMap[name].push(off);
|
name,
|
||||||
|
event: this.class2Name(eventCls),
|
||||||
|
exec: executor
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
this.pluginEventMap[name].push(off)
|
||||||
// noinspection JSUnresolvedVariable
|
// noinspection JSUnresolvedVariable
|
||||||
console.debug(`插件 ${name} 注册事件 ${this.class2Name(eventCls)} => ${exec.name || '匿名方法'}`);
|
console.debug(i18n.translate("ms.api.event.register", {
|
||||||
return off;
|
name,
|
||||||
|
event: this.class2Name(eventCls),
|
||||||
|
exec: executor,
|
||||||
|
priority,
|
||||||
|
ignore: ignoreCancel
|
||||||
|
}))
|
||||||
|
return off
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭插件监听任务
|
||||||
|
* @param plugin 插件
|
||||||
|
*/
|
||||||
disable(plugin: any) {
|
disable(plugin: any) {
|
||||||
var eventCache = this.listenerMap[plugin.description.name];
|
var eventCache = this.pluginEventMap[plugin.description.name]
|
||||||
if (eventCache) {
|
if (eventCache) {
|
||||||
eventCache.forEach(t => t.off());
|
eventCache.forEach((off: () => any) => off())
|
||||||
delete this.listenerMap[plugin.description.name];
|
delete this.pluginEventMap[plugin.description.name]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract isValidEvent(clazz: any): boolean;
|
/**
|
||||||
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any;
|
* 判断
|
||||||
abstract unregister(event: any, listener: any): void;
|
* @param clazz 事件类
|
||||||
|
*/
|
||||||
|
abstract isValidEvent(clazz: any): boolean
|
||||||
|
/**
|
||||||
|
* 注册事件
|
||||||
|
* @param eventCls 事件类
|
||||||
|
* @param exec 执行器
|
||||||
|
* @param priority 优先级
|
||||||
|
* @param ignoreCancel 是否忽略已取消的事件
|
||||||
|
*/
|
||||||
|
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any
|
||||||
|
/**
|
||||||
|
* 取消监听事件
|
||||||
|
* @param event 事件
|
||||||
|
* @param listener 监听器
|
||||||
|
*/
|
||||||
|
abstract unregister(event: any, listener: any): void
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,16 @@
|
|||||||
import './typings/global'
|
import "@ccms/nashorn"
|
||||||
|
|
||||||
|
export * from './chat'
|
||||||
|
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 './command'
|
export * from './command'
|
||||||
export * from './interfaces'
|
export * from './database'
|
||||||
|
export * from './particle'
|
||||||
|
export * from './constants'
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
export * from './plugin'
|
|
||||||
export * from './server'
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
import { Container } from "inversify";
|
|
||||||
|
|
||||||
export namespace plugin {
|
|
||||||
/**
|
|
||||||
* MiaoScript Plugin
|
|
||||||
*/
|
|
||||||
export const Plugin = Symbol("Plugin");
|
|
||||||
/**
|
|
||||||
* Runtime Plugin Instance
|
|
||||||
*/
|
|
||||||
export const PluginInstance = Symbol("PluginInstance");
|
|
||||||
/**
|
|
||||||
* MiaoScript Plugin Manager
|
|
||||||
*/
|
|
||||||
export const PluginManager = Symbol("PluginManager");
|
|
||||||
/**
|
|
||||||
* MiaoScript Plugin Manager
|
|
||||||
*/
|
|
||||||
export interface PluginManager {
|
|
||||||
scan(folder: string): void;
|
|
||||||
load(container: Container): void;
|
|
||||||
enable(): void;
|
|
||||||
disable(): void;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
export namespace server {
|
|
||||||
export const ServerType = Symbol("ServerType");
|
|
||||||
export const Console = Symbol("Console");
|
|
||||||
}
|
|
||||||
20
packages/api/src/item.ts
Normal file
20
packages/api/src/item.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
507
packages/api/src/particle.ts
Normal file
507
packages/api/src/particle.ts
Normal file
@@ -0,0 +1,507 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
202
packages/api/src/plugin.ts
Normal file
202
packages/api/src/plugin.ts
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
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 build(): void
|
||||||
|
abstract loadFromFile(file: string, ext?: any): Plugin
|
||||||
|
abstract load(...args: any[]): void
|
||||||
|
abstract enable(...args: any[]): void
|
||||||
|
abstract disable(...args: any[]): void
|
||||||
|
abstract reload(...args: any[]): void
|
||||||
|
abstract getPlugin(name: string): plugin.Plugin
|
||||||
|
abstract getPlugins(): Map<string, plugin.Plugin>
|
||||||
|
}
|
||||||
|
export const PluginScanner = Symbol("PluginScanner")
|
||||||
|
/**
|
||||||
|
* 插件加载元信息
|
||||||
|
*/
|
||||||
|
export interface PluginLoadMetadata {
|
||||||
|
/**
|
||||||
|
* 插件加载类型
|
||||||
|
*/
|
||||||
|
type: string
|
||||||
|
/**
|
||||||
|
* 插件文件
|
||||||
|
*/
|
||||||
|
file?: 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
|
||||||
|
/**
|
||||||
|
* Reload 阶段
|
||||||
|
* @param plugin 插件
|
||||||
|
*/
|
||||||
|
reload?(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
|
||||||
|
}
|
||||||
|
}
|
||||||
161
packages/api/src/proxy.ts
Normal file
161
packages/api/src/proxy.ts
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
229
packages/api/src/server.ts
Normal file
229
packages/api/src/server.ts
Normal file
@@ -0,0 +1,229 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
197
packages/api/src/task.ts
Normal file
197
packages/api/src/task.ts
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
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 {
|
||||||
|
@injectable()
|
||||||
|
export abstract class 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('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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建任务
|
||||||
|
* @param func 任务内容
|
||||||
|
*/
|
||||||
|
create(func: Function, plugin?: plugin.Plugin): 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 执行内容
|
||||||
|
*/
|
||||||
|
abstract callSyncMethod(func: Function): any
|
||||||
|
/**
|
||||||
|
* 关闭任务管理器
|
||||||
|
*/
|
||||||
|
disable(plugin?: plugin.Plugin) {
|
||||||
|
if (plugin) { return this.pluginDisable(plugin) }
|
||||||
|
this.disable0()
|
||||||
|
}
|
||||||
|
protected abstract create0(owner: plugin.Plugin, func: Function, id: number): task.Task
|
||||||
|
protected abstract disable0()
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 任务抽象
|
||||||
|
*/
|
||||||
|
export abstract class Task extends EventEmitter implements Cancelable {
|
||||||
|
protected func: Function
|
||||||
|
protected isAsync: boolean = false;
|
||||||
|
protected laterTime: number = 0;
|
||||||
|
protected interval: number = 0;
|
||||||
|
protected owner: plugin.Plugin
|
||||||
|
protected taskId: number
|
||||||
|
protected innerTask: any
|
||||||
|
|
||||||
|
private cancelled: boolean = false
|
||||||
|
|
||||||
|
constructor(owner: plugin.Plugin, func: Function, id: number) {
|
||||||
|
super()
|
||||||
|
this.owner = owner
|
||||||
|
this.func = func
|
||||||
|
this.taskId = id
|
||||||
|
}
|
||||||
|
|
||||||
|
getOwner() {
|
||||||
|
return this.owner
|
||||||
|
}
|
||||||
|
|
||||||
|
getTaskId() {
|
||||||
|
return this.taskId
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置任务异步执行
|
||||||
|
* @param isAsync 是否异步
|
||||||
|
*/
|
||||||
|
async(isAsync: boolean = true): task.Task {
|
||||||
|
this.isAsync = isAsync
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置任务延时执行
|
||||||
|
* @param tick 延时 Tick
|
||||||
|
*/
|
||||||
|
later(tick: number): task.Task {
|
||||||
|
this.laterTime = tick
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置任务循环执行
|
||||||
|
* @param tick 循环时间 Tick
|
||||||
|
*/
|
||||||
|
timer(tick: number): task.Task {
|
||||||
|
this.interval = tick
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消任务
|
||||||
|
*/
|
||||||
|
cancel(): boolean {
|
||||||
|
let result = this.cancel0()
|
||||||
|
this.finish()
|
||||||
|
this.cancelled = true
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
protected run(...args: any[]): void {
|
||||||
|
try {
|
||||||
|
this.emit('before', this)
|
||||||
|
if (this.cancelled) { return }
|
||||||
|
this.func(...args)
|
||||||
|
this.emit('after', this)
|
||||||
|
} 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() {
|
||||||
|
process.emit('task.finish', this)
|
||||||
|
this.emit('finish', this)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交任务
|
||||||
|
* @param args 任务参数
|
||||||
|
*/
|
||||||
|
submit(...args: any[]): task.Task {
|
||||||
|
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 {
|
||||||
|
cancel(): boolean
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
declare global {
|
|
||||||
namespace NodeJS {
|
|
||||||
interface Global {
|
|
||||||
logger: any;
|
|
||||||
debug: boolean;
|
|
||||||
noop: Function;
|
|
||||||
console: Console;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var root: string;
|
|
||||||
var base: Core;
|
|
||||||
var ScriptEngineContextHolder: any;
|
|
||||||
function engineLoad(str: string): any;
|
|
||||||
interface Core {
|
|
||||||
getClass(name: String);
|
|
||||||
}
|
|
||||||
interface Console {
|
|
||||||
ex(err: Error): void;
|
|
||||||
stack(err: Error): string[];
|
|
||||||
sender(...args: any): void;
|
|
||||||
console(...args: any): void;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export { }
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
export interface CommandInfo {
|
|
||||||
aliases: string[];
|
|
||||||
description: string;
|
|
||||||
}
|
|
||||||
export interface PluginInfo {
|
|
||||||
description: PluginDescription;
|
|
||||||
}
|
|
||||||
export interface PluginDescription {
|
|
||||||
name: string;
|
|
||||||
version: string;
|
|
||||||
author: string;
|
|
||||||
commands: { [key: string]: CommandInfo };
|
|
||||||
}
|
|
||||||
4
packages/bukkit/.gitignore
vendored
4
packages/bukkit/.gitignore
vendored
@@ -1,4 +0,0 @@
|
|||||||
/node_modules
|
|
||||||
/dist
|
|
||||||
/package-lock.json
|
|
||||||
/yarn.lock
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
src
|
|
||||||
test
|
|
||||||
typings
|
|
||||||
bundled
|
|
||||||
build
|
|
||||||
coverage
|
|
||||||
docs
|
|
||||||
wiki
|
|
||||||
gulpfile.js
|
|
||||||
bower.json
|
|
||||||
karma.conf.js
|
|
||||||
tsconfig.json
|
|
||||||
typings.json
|
|
||||||
CONTRIBUTING.md
|
|
||||||
ISSUE_TEMPLATE.md
|
|
||||||
PULL_REQUEST_TEMPLATE.md
|
|
||||||
tslint.json
|
|
||||||
wallaby.js
|
|
||||||
.travis.yml
|
|
||||||
.gitignore
|
|
||||||
.vscode
|
|
||||||
type_definitions
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/bukkit",
|
"name": "@ccms/bukkit",
|
||||||
"version": "0.0.0",
|
"version": "0.28.0-beta.7",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript bukkit package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
"minecraft",
|
"minecraft",
|
||||||
@@ -12,23 +12,23 @@
|
|||||||
"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",
|
||||||
"publishConfig": {
|
"files": [
|
||||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
"dist/*.js",
|
||||||
},
|
"dist/*.ts",
|
||||||
|
"dist/*.map"
|
||||||
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "pnpm clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"@javatypes/spigot-api": "^0.0.3"
|
||||||
"rimraf": "^3.0.0",
|
|
||||||
"typescript": "^3.6.2"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/api": "^0.0.0",
|
"@ccms/api": "^0.28.0-beta.7",
|
||||||
"@ms/common": "^0.0.0",
|
"@ccms/common": "^0.28.0-beta.7",
|
||||||
"@ms/container": "^0.0.0"
|
"@ccms/container": "^0.28.0-beta.7"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
54
packages/bukkit/src/channel.ts
Normal file
54
packages/bukkit/src/channel.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
import { channel, plugin } from '@ccms/api'
|
||||||
|
import { inject, provideSingleton } from '@ccms/container'
|
||||||
|
|
||||||
|
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
|
const PluginMessageListener = Java.type("org.bukkit.plugin.messaging.PluginMessageListener")
|
||||||
|
const Messenger = Bukkit.getMessenger()
|
||||||
|
|
||||||
|
@provideSingleton(channel.Channel)
|
||||||
|
export class BukkitChannel extends channel.Channel {
|
||||||
|
@inject(plugin.PluginInstance)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册通道监听器
|
||||||
|
* @param channel 通道
|
||||||
|
* @param listener 监听器
|
||||||
|
*/
|
||||||
|
register(channel: string, listener: channel.ChannelListener) {
|
||||||
|
if (!this.cacheChannel.has(channel)) this.cacheChannel.set(channel, [])
|
||||||
|
this.cacheChannel.get(channel).push(listener)
|
||||||
|
let pluginMessageListener = new PluginMessageListener({
|
||||||
|
onPluginMessageReceived: (/**String */ channel, /**Player */ player, /**byte[] */data) => {
|
||||||
|
try {
|
||||||
|
listener(data, { channel, player, data })
|
||||||
|
} catch (error: any) {
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, pluginMessageListener)
|
||||||
|
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel)
|
||||||
|
return pluginMessageListener
|
||||||
|
}
|
||||||
|
unregister(channel: string, listener: any) {
|
||||||
|
if (!this.cacheChannel.has(channel)) return
|
||||||
|
let cacheListener = this.cacheChannel.get(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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
26
packages/bukkit/src/chat.ts
Normal file
26
packages/bukkit/src/chat.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
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,92 +1,53 @@
|
|||||||
import '@ms/nashorn'
|
import '@ccms/nashorn'
|
||||||
|
|
||||||
import { command, plugin } from '@ms/api'
|
import { command, plugin } from '@ccms/api'
|
||||||
import * as reflect from '@ms/common/dist/reflect'
|
import { provideSingleton, postConstruct, inject } from '@ccms/container'
|
||||||
import { injectable, postConstruct, inject } from '@ms/container'
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
|
||||||
let Bukkit = Java.type("org.bukkit.Bukkit");
|
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
let Arrays = Java.type('java.util.Arrays');
|
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');
|
|
||||||
|
|
||||||
@injectable()
|
@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.pluginManager).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) {
|
||||||
enable(jsp) {
|
var cmd = this.commandMap.getCommand(command)
|
||||||
var commands = jsp.description.commands;
|
if (cmd instanceof PluginCommand) { return cmd };
|
||||||
if (commands) {
|
cmd = reflect.on(PluginCommand).create(command, this.pluginInstance).get()
|
||||||
var pluginCommands = [];
|
this.commandMap.register(plugin.description.name, cmd)
|
||||||
for (var name in commands) {
|
return cmd
|
||||||
var command = commands[name];
|
}
|
||||||
if (typeof command !== 'object') continue;
|
remove(plugin: any, command: string) {
|
||||||
command.name = name;
|
var cmd = this.commandMap.getCommand(command)
|
||||||
var newCmd = this.create(jsp, command);
|
if (cmd instanceof PluginCommand) {
|
||||||
if (command.description) newCmd.setDescription(command.description);
|
cmd.unregister(this.commandMap)
|
||||||
if (command.usage) newCmd.setUsage(command.usage);
|
this.knownCommands.remove(command)
|
||||||
if (command.aliases) newCmd.setAliases(Arrays.asList(command.aliases));
|
|
||||||
if (command.permission) newCmd.setPermission(command.permission);
|
|
||||||
if (command['permission-message']) newCmd.setPermissionMessage(command['permission-message']);
|
|
||||||
pluginCommands.push(newCmd);
|
|
||||||
console.debug(`插件 ${jsp.description.name} 注册命令 ${name} ...`);
|
|
||||||
}
|
|
||||||
this.commandMap.registerAll(jsp.description.name, Arrays.asList(pluginCommands));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
tabComplete(sender: any, input: string, index?: number): string[] {
|
||||||
disable(jsp) {
|
return Java.from(this.commandMap.tabComplete(sender, input))
|
||||||
var commands = jsp.description.commands;
|
|
||||||
if (commands) {
|
|
||||||
for (var name in commands) {
|
|
||||||
//TODO 删除插件命令
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
onCommand(plugin: any, command: any, executor: Function) {
|
||||||
create(jsp, command) {
|
|
||||||
var cmd = this.commandMap.getCommand(command.name)
|
|
||||||
if (cmd && cmd instanceof PluginCommand) { return cmd };
|
|
||||||
cmd = reflect.on(PluginCommand).create(command.name, this.pluginInstance).get();
|
|
||||||
this.commandMap.register(jsp.description.name, cmd);
|
|
||||||
return cmd;
|
|
||||||
}
|
|
||||||
|
|
||||||
onCommand(jsp, c, cmd) {
|
|
||||||
// 必须指定需要实现的接口类型 否则MOD服会报错
|
// 必须指定需要实现的接口类型 否则MOD服会报错
|
||||||
c.setExecutor(new CommandExecutor({
|
command.setExecutor(new CommandExecutor({
|
||||||
onCommand: function(sender, _, command, args) {
|
onCommand: super.setExecutor(plugin, command, executor)
|
||||||
try {
|
}))
|
||||||
return cmd(sender, command, Java.from(args));
|
|
||||||
} catch (ex) {
|
|
||||||
console.console(`§6玩家 §a${sender.name} §6执行 §b${jsp.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6命令时发生异常 §4${ex}`);
|
|
||||||
console.ex(ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
|
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||||
onTabComplete(jsp, c, tab) {
|
|
||||||
// 必须指定需要实现的接口类型 否则MOD服会报错
|
// 必须指定需要实现的接口类型 否则MOD服会报错
|
||||||
// noinspection JSUnusedGlobalSymbols
|
command.setTabCompleter(new TabCompleter({
|
||||||
c.setTabCompleter(new TabCompleter({
|
onTabComplete: super.setTabCompleter(plugin, command, tabCompleter)
|
||||||
onTabComplete: function(sender, _, command, args) {
|
}))
|
||||||
try {
|
|
||||||
var token = args[args.length - 1];
|
|
||||||
var complete = tab(sender, command, Java.from(args)) || [];
|
|
||||||
return Arrays.asList(complete.copyPartialMatches(token, []));
|
|
||||||
} catch (ex) {
|
|
||||||
console.console(`§6玩家 §a${sender.name} §6执行 §b${jsp.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6补全时发生异常 §4${ex}`);
|
|
||||||
console.ex(ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,20 @@
|
|||||||
import { MiaoScriptConsole } from '@ms/api'
|
import { MiaoScriptConsole } from '@ccms/api'
|
||||||
|
|
||||||
let Bukkit = Java.type("org.bukkit.Bukkit");
|
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
let CommandSender = Java.type("org.bukkit.command.CommandSender");
|
|
||||||
|
|
||||||
export class BukkitConsole extends MiaoScriptConsole {
|
export class BukkitConsole extends MiaoScriptConsole {
|
||||||
sender(sender, ...args) {
|
sender(sender, ...args) {
|
||||||
if (!(sender instanceof CommandSender)) {
|
if (!(sender instanceof Java.type('org.bukkit.command.CommandSender'))) {
|
||||||
this.error("第一个参数未实现 org.bukkit.command.CommandSender 无法发送消息!")
|
this.error(`First parameter ${sender} not instanceof org.bukkit.command.CommandSender can't send message!`)
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
if (args[0].toString() === "[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): void {
|
console(...args: string[]): void {
|
||||||
this.sender(Bukkit.consoleSender, args.join(' '));
|
this.sender(Bukkit.getConsoleSender(), args.join(' '))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
57
packages/bukkit/src/event.ts
Normal file
57
packages/bukkit/src/event.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import { event, plugin } from '@ccms/api'
|
||||||
|
import { inject, provideSingleton } from '@ccms/container'
|
||||||
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
|
||||||
|
const URL = Java.type('java.net.URL')
|
||||||
|
const Bukkit = Java.type("org.bukkit.Bukkit")
|
||||||
|
const Event = Java.type("org.bukkit.event.Event")
|
||||||
|
const Modifier = Java.type("java.lang.reflect.Modifier")
|
||||||
|
const Listener = Java.type("org.bukkit.event.Listener")
|
||||||
|
const EventPriority = Java.type("org.bukkit.event.EventPriority")
|
||||||
|
const EventExecutor = Java.type("org.bukkit.plugin.EventExecutor")
|
||||||
|
|
||||||
|
@provideSingleton(event.Event)
|
||||||
|
export class BukkitEvent extends event.Event {
|
||||||
|
@inject(plugin.PluginInstance)
|
||||||
|
private pluginInstance: any
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super('org/bukkit/event')
|
||||||
|
}
|
||||||
|
|
||||||
|
getJarFile(resource: string) {
|
||||||
|
try {
|
||||||
|
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 {
|
||||||
|
// 继承于 org.bukkit.event.Event
|
||||||
|
return Event.class.isAssignableFrom(clazz) &&
|
||||||
|
// 访问符为Public
|
||||||
|
Modifier.isPublic(clazz.getModifiers()) &&
|
||||||
|
// 不是抽象类
|
||||||
|
!Modifier.isAbstract(clazz.getModifiers())
|
||||||
|
}
|
||||||
|
register(eventCls: any, exec: Function, priority: event.EventPriority, ignoreCancel: boolean) {
|
||||||
|
let listener = new Listener({})
|
||||||
|
Bukkit.pluginManager.registerEvent(
|
||||||
|
eventCls,
|
||||||
|
listener,
|
||||||
|
EventPriority[priority],
|
||||||
|
new EventExecutor({
|
||||||
|
execute: exec
|
||||||
|
}),
|
||||||
|
this.pluginInstance,
|
||||||
|
ignoreCancel)
|
||||||
|
return listener
|
||||||
|
}
|
||||||
|
unregister(event: any, listener: any): void {
|
||||||
|
reflect.on(event).call('getHandlerList').get().unregister(listener)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +1,20 @@
|
|||||||
import { server, plugin, command } from '@ms/api'
|
/// <reference types="@javatypes/spigot-api" />
|
||||||
import { DefaultContainer as container } from '@ms/container'
|
|
||||||
|
import { server } from '@ccms/api'
|
||||||
|
import { Container } from '@ccms/container'
|
||||||
|
|
||||||
import { BukkitConsole } from './console'
|
import { BukkitConsole } from './console'
|
||||||
import { BukkitCommand } from './command';
|
import './item'
|
||||||
|
import './chat'
|
||||||
|
import './task'
|
||||||
|
import './event'
|
||||||
|
import './server'
|
||||||
|
import { BukkitNativePluginManager } from './plugin'
|
||||||
|
import './command'
|
||||||
|
import './channel'
|
||||||
|
import './particle'
|
||||||
|
|
||||||
let BukkitServerType = 'bukkit';
|
export default function BukkitImpl(container: Container) {
|
||||||
let Bukkit = Java.type("org.bukkit.Bukkit");
|
container.bind(server.Console).toConstantValue(BukkitConsole)
|
||||||
|
container.rebind(server.NativePluginManager).toConstantValue(new BukkitNativePluginManager())
|
||||||
container.bind(server.Console).toConstantValue(BukkitConsole);
|
}
|
||||||
container.bind(server.ServerType).toConstantValue(BukkitServerType);
|
|
||||||
container.bind(plugin.PluginInstance).toConstantValue(Bukkit.pluginManager.getPlugin('MiaoScript'));
|
|
||||||
|
|
||||||
container.bind(command.Command).to(BukkitCommand).inSingletonScope();
|
|
||||||
|
|||||||
206
packages/bukkit/src/internal/chat.ts
Normal file
206
packages/bukkit/src/internal/chat.ts
Normal file
@@ -0,0 +1,206 @@
|
|||||||
|
/*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, origin: string, test: string, params: any) {
|
||||||
|
try {
|
||||||
|
return clazz.getMethod(origin, params)
|
||||||
|
} catch (ex: any) {
|
||||||
|
if (this.RemapUtils) {
|
||||||
|
return clazz.getMethod(this.RemapUtils.mapMethod(clazz, origin, params), params)
|
||||||
|
} else {
|
||||||
|
return clazz.getMethod(test, params)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
remapFieldName(clazz: any, origin: string, test: string) {
|
||||||
|
try {
|
||||||
|
return clazz.getField(origin)
|
||||||
|
} catch (ex: any) {
|
||||||
|
if (this.RemapUtils) {
|
||||||
|
return clazz.getField(this.RemapUtils.mapFieldName(clazz, origin))
|
||||||
|
} else {
|
||||||
|
return clazz.getField(test)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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', 'func_179290_a', this.getPacketClass()).getName()
|
||||||
|
}
|
||||||
|
getNmsChatSerializerMethodName(nmsChatSerializerClass: any) {
|
||||||
|
let nmsChatSerializerMethod = this.remapMethod(nmsChatSerializerClass, '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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 >= 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
|
||||||
2270
packages/bukkit/src/internal/item.ts
Normal file
2270
packages/bukkit/src/internal/item.ts
Normal file
File diff suppressed because it is too large
Load Diff
128
packages/bukkit/src/item.ts
Normal file
128
packages/bukkit/src/item.ts
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
33
packages/bukkit/src/particle.ts
Normal file
33
packages/bukkit/src/particle.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
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())
|
||||||
|
}
|
||||||
|
}
|
||||||
52
packages/bukkit/src/plugin.ts
Normal file
52
packages/bukkit/src/plugin.ts
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
62
packages/bukkit/src/server.ts
Normal file
62
packages/bukkit/src/server.ts
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import { server } from '@ccms/api'
|
||||||
|
import { provideSingleton } from '@ccms/container'
|
||||||
|
|
||||||
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
|
||||||
|
const Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
|
|
||||||
|
@provideSingleton(server.Server)
|
||||||
|
export class BukkitServer extends server.ReflectServer {
|
||||||
|
private pluginsFolder: string
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super()
|
||||||
|
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath()
|
||||||
|
}
|
||||||
|
|
||||||
|
getPlayer(name: string) {
|
||||||
|
return Bukkit.getPlayerExact(name)
|
||||||
|
}
|
||||||
|
getVersion(): string {
|
||||||
|
return Bukkit.getVersion()
|
||||||
|
}
|
||||||
|
getOnlinePlayers() {
|
||||||
|
return Bukkit.getOnlinePlayers()
|
||||||
|
}
|
||||||
|
getConsoleSender() {
|
||||||
|
return Bukkit.getConsoleSender()
|
||||||
|
}
|
||||||
|
getService(service: string) {
|
||||||
|
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 {
|
||||||
|
if (typeof sender === 'string') {
|
||||||
|
sender = this.getPlayer(sender)
|
||||||
|
}
|
||||||
|
return Bukkit.dispatchCommand(sender, command)
|
||||||
|
}
|
||||||
|
dispatchConsoleCommand(command: string): boolean {
|
||||||
|
return Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)
|
||||||
|
}
|
||||||
|
getPluginsFolder(): string {
|
||||||
|
return this.pluginsFolder
|
||||||
|
}
|
||||||
|
getNativePluginManager() {
|
||||||
|
return Bukkit.getPluginManager() as any
|
||||||
|
}
|
||||||
|
getDedicatedServer() {
|
||||||
|
return reflect.on(Bukkit.getServer()).get('console').get()
|
||||||
|
}
|
||||||
|
getNettyPipeline() {
|
||||||
|
return this.pipeline
|
||||||
|
}
|
||||||
|
getRootLogger() {
|
||||||
|
return this.rootLogger
|
||||||
|
}
|
||||||
|
}
|
||||||
31
packages/bukkit/src/task.ts
Normal file
31
packages/bukkit/src/task.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { task, plugin } from '@ccms/api'
|
||||||
|
import { provideSingleton } from '@ccms/container'
|
||||||
|
|
||||||
|
const Bukkit = Java.type('org.bukkit.Bukkit')
|
||||||
|
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable')
|
||||||
|
const Callable = Java.type('java.util.concurrent.Callable')
|
||||||
|
|
||||||
|
@provideSingleton(task.TaskManager)
|
||||||
|
export class BukkitTaskManager extends task.TaskManager {
|
||||||
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
|
return new BukkitTask(owner, func, id)
|
||||||
|
}
|
||||||
|
callSyncMethod(func: Function): any {
|
||||||
|
return Bukkit.getScheduler().callSyncMethod(base.getInstance(), new Callable({ call: () => func() })).get()
|
||||||
|
}
|
||||||
|
disable0() {
|
||||||
|
Bukkit.getScheduler().cancelTasks(base.getInstance())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BukkitTask extends task.Task {
|
||||||
|
submit0(...args: any[]): task.Cancelable {
|
||||||
|
let run = new BukkitRunnable({ run: () => this.run(...args) })
|
||||||
|
let suffix = this.isAsync ? 'Asynchronously' : ''
|
||||||
|
if (this.interval) {
|
||||||
|
return run[`runTaskTimer${suffix}`](base.getInstance(), this.laterTime, this.interval)
|
||||||
|
} else {
|
||||||
|
return run[`runTaskLater${suffix}`](base.getInstance(), this.laterTime)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
"extends": "../../tsconfig.json",
|
"extends": "../../tsconfig.json",
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"baseUrl": "src",
|
"baseUrl": "src",
|
||||||
"outDir": "dist"
|
"outDir": "dist",
|
||||||
|
"resolveJsonModule": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
34
packages/bungee/package.json
Normal file
34
packages/bungee/package.json
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
{
|
||||||
|
"name": "@ccms/bungee",
|
||||||
|
"version": "0.28.0-beta.7",
|
||||||
|
"description": "MiaoScript bungee 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/bungee-api": "^0.0.3"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@ccms/api": "^0.28.0-beta.7",
|
||||||
|
"@ccms/common": "^0.28.0-beta.7",
|
||||||
|
"@ccms/container": "^0.28.0-beta.7"
|
||||||
|
}
|
||||||
|
}
|
||||||
25
packages/bungee/src/channel.ts
Normal file
25
packages/bungee/src/channel.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { channel, event } from '@ccms/api'
|
||||||
|
import { provideSingleton, inject } from '@ccms/container'
|
||||||
|
|
||||||
|
const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||||
|
|
||||||
|
@provideSingleton(channel.Channel)
|
||||||
|
export class BungeeChannel extends channel.Channel {
|
||||||
|
@inject(event.Event)
|
||||||
|
private eventManager: event.Event
|
||||||
|
|
||||||
|
send(player: any, channel: string, data: any) {
|
||||||
|
throw new Error("Method not implemented.")
|
||||||
|
}
|
||||||
|
register(channel: string, listener: channel.ChannelListener) {
|
||||||
|
Bungee.registerChannel(channel)
|
||||||
|
// 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) => {
|
||||||
|
listener(event.getData(), event)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
unregister(channel: string, off: any) {
|
||||||
|
Bungee.unregisterChannel(channel)
|
||||||
|
off()
|
||||||
|
}
|
||||||
|
}
|
||||||
65
packages/bungee/src/command.ts
Normal file
65
packages/bungee/src/command.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import { command, plugin } from "@ccms/api";
|
||||||
|
import { inject, provideSingleton } from "@ccms/container";
|
||||||
|
|
||||||
|
const Arrays = Java.type('java.util.Arrays')
|
||||||
|
const Command = Java.extend(Java.type('net.md_5.bungee.api.plugin.Command'), Java.type('net.md_5.bungee.api.plugin.TabExecutor'));
|
||||||
|
const createCommand = eval(`
|
||||||
|
function(cls, name, exec, tab){
|
||||||
|
return new cls(name) {
|
||||||
|
execute: exec,
|
||||||
|
onTabComplete: tab
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`)
|
||||||
|
|
||||||
|
@provideSingleton(command.Command)
|
||||||
|
export class BungeeCommand extends command.Command {
|
||||||
|
@inject(plugin.PluginInstance)
|
||||||
|
private pluginInstance: any;
|
||||||
|
private pluginManager: net.md_5.bungee.api.plugin.PluginManager = base.getInstance().getProxy().getPluginManager();
|
||||||
|
private commandMapping: any[] = [];
|
||||||
|
|
||||||
|
create(plugin: any, command: string) {
|
||||||
|
let commandKey = this.getCommandKey(plugin, command);
|
||||||
|
let commandCallable = new SimpleCommand(command);
|
||||||
|
this.pluginManager.registerCommand(this.pluginInstance, commandCallable.callable)
|
||||||
|
this.commandMapping[commandKey] = commandCallable.callable;
|
||||||
|
return commandCallable;
|
||||||
|
}
|
||||||
|
remove(plugin: any, command: string) {
|
||||||
|
var commandKey = this.getCommandKey(plugin, command);
|
||||||
|
if (this.commandMapping[commandKey]) {
|
||||||
|
this.pluginManager.unregisterCommand(this.commandMapping[commandKey])
|
||||||
|
delete this.commandMapping[commandKey];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onCommand(plugin: any, command: any, executor: Function) {
|
||||||
|
command.setExecutor(super.setExecutor(plugin, command, executor));
|
||||||
|
}
|
||||||
|
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
|
||||||
|
command.setTabComplete(super.setTabCompleter(plugin, command, tabCompleter))
|
||||||
|
}
|
||||||
|
|
||||||
|
private getCommandKey(plugin: any, command: string) {
|
||||||
|
return plugin.description.name.toLowerCase() + ":" + command;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SimpleCommand {
|
||||||
|
public callable: any;
|
||||||
|
private name: string;
|
||||||
|
private executor: Function;
|
||||||
|
private tabComplete: Function = () => [];
|
||||||
|
|
||||||
|
constructor(command: string) {
|
||||||
|
this.name = command;
|
||||||
|
this.callable = createCommand(Command, command,
|
||||||
|
(sender, args) => this.executor(sender, '', command, args),
|
||||||
|
(sender, args) => Arrays.asList(this.tabComplete(sender, '', command, args))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
setExecutor = (executor: Function) => this.executor = executor;
|
||||||
|
setTabComplete = (tabComplete: Function) => this.tabComplete = tabComplete;
|
||||||
|
toString = () => `Bungee SimpleCommand(${this.name})`
|
||||||
|
}
|
||||||
27
packages/bungee/src/console.ts
Normal file
27
packages/bungee/src/console.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import '@ccms/nashorn'
|
||||||
|
import { plugin, MiaoScriptConsole } from '@ccms/api'
|
||||||
|
import { inject, injectable } from "@ccms/container";
|
||||||
|
|
||||||
|
let CommandSender = Java.type("net.md_5.bungee.api.CommandSender")
|
||||||
|
|
||||||
|
@injectable()
|
||||||
|
export class BungeeConsole extends MiaoScriptConsole {
|
||||||
|
@inject(plugin.PluginInstance)
|
||||||
|
private pluginInstance: any
|
||||||
|
private proxyServer: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
||||||
|
|
||||||
|
sender(sender, ...args) {
|
||||||
|
if (!(sender instanceof CommandSender)) {
|
||||||
|
this.error('第一个参数未实现 net.md_5.bungee.api.CommandSender 无法发送消息!')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (Object.prototype.toString.call(args[0]) === '[object Array]') {
|
||||||
|
args[0].forEach(line => sender.sendMessage(this.prefix + line))
|
||||||
|
} else {
|
||||||
|
sender.sendMessage(this.prefix + args.join(' '));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console(...args): void {
|
||||||
|
this.sender(this.proxyServer.getConsole(), args.join(' '));
|
||||||
|
}
|
||||||
|
}
|
||||||
117
packages/bungee/src/event.ts
Normal file
117
packages/bungee/src/event.ts
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
import { event } from '@ccms/api'
|
||||||
|
import { provideSingleton, postConstruct } from '@ccms/container'
|
||||||
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
|
||||||
|
const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
||||||
|
const Event = Java.type("net.md_5.bungee.api.plugin.Event");
|
||||||
|
const Modifier = Java.type("java.lang.reflect.Modifier");
|
||||||
|
const ProxyClass = Java.type(base.getProxyClass().name);
|
||||||
|
const ProxyMethod = reflect.on(base.getProxyClass()).method("method");
|
||||||
|
const HashMap = Java.type('java.util.HashMap');
|
||||||
|
const ReflectMethodArray = Java.type('java.lang.reflect.Method[]');
|
||||||
|
|
||||||
|
const Byte = Java.type('java.lang.Byte');
|
||||||
|
const EventPriority = [];
|
||||||
|
EventPriority[event.EventPriority.LOWEST] = Byte.valueOf(-64);
|
||||||
|
EventPriority[event.EventPriority.LOW] = -Byte.valueOf(32);
|
||||||
|
EventPriority[event.EventPriority.NORMAL] = Byte.valueOf(0);
|
||||||
|
EventPriority[event.EventPriority.HIGH] = Byte.valueOf(32);
|
||||||
|
EventPriority[event.EventPriority.HIGHEST] = Byte.valueOf(64);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bungee Event Impl
|
||||||
|
*/
|
||||||
|
@provideSingleton(event.Event)
|
||||||
|
export class BungeeEvent extends event.Event {
|
||||||
|
private pluginManager = Bungee.getPluginManager()
|
||||||
|
|
||||||
|
// EventBus
|
||||||
|
private eventBus: any;
|
||||||
|
// private final Lock lock = new ReentrantLock();
|
||||||
|
private lock: any;
|
||||||
|
// private final Map<Class<?>, Map<Byte, Map<Object, Method[]>>> byListenerAndPriority = new HashMap<>();
|
||||||
|
private byListenerAndPriority: any;
|
||||||
|
// bakeHandlers(Class<?> eventClass)
|
||||||
|
private bakeHandlers: any;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super('net/md_5/bungee/api/event');
|
||||||
|
}
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
|
init() {
|
||||||
|
this.eventBus = reflect.on(this.pluginManager).get('eventBus').get();
|
||||||
|
this.lock = reflect.on(this.eventBus).get('lock').get()
|
||||||
|
this.byListenerAndPriority = reflect.on(this.eventBus).get('byListenerAndPriority').get();
|
||||||
|
this.bakeHandlers = reflect.accessible(reflect.on(this.eventBus).method("bakeHandlers"));
|
||||||
|
}
|
||||||
|
|
||||||
|
isValidEvent(clazz: any): boolean {
|
||||||
|
//继承于 net.md_5.bungee.api.plugin.Event
|
||||||
|
return Event.class.isAssignableFrom(clazz) &&
|
||||||
|
// 访问符为Public
|
||||||
|
Modifier.isPublic(clazz.getModifiers()) &&
|
||||||
|
// 不是抽象类
|
||||||
|
!Modifier.isAbstract(clazz.getModifiers());
|
||||||
|
}
|
||||||
|
|
||||||
|
register(eventCls: any, exec: Function, priority: event.EventPriority = event.EventPriority.NORMAL, ignoreCancel: boolean = true) {
|
||||||
|
this.lock.lock()
|
||||||
|
try {
|
||||||
|
// private final Map<类, Map<优先级, Map<监听器, 方法[]>>> byListenerAndPriority = new HashMap<>();
|
||||||
|
// this.byListenerAndPriority.put(eventCls)
|
||||||
|
// Map<优先级, Map<监听器, 方法[]>>
|
||||||
|
let prioritiesMap = this.byListenerAndPriority.get(eventCls);
|
||||||
|
if (prioritiesMap == null) {
|
||||||
|
prioritiesMap = new HashMap();
|
||||||
|
this.byListenerAndPriority.put(eventCls, prioritiesMap);
|
||||||
|
}
|
||||||
|
// Map<监听器, 方法[]>
|
||||||
|
let currentPriorityMap = prioritiesMap.get(EventPriority[priority]);
|
||||||
|
if (currentPriorityMap == null) {
|
||||||
|
currentPriorityMap = new HashMap();
|
||||||
|
prioritiesMap.put(EventPriority[priority], currentPriorityMap);
|
||||||
|
}
|
||||||
|
let listener = new ProxyClass(ScriptEngineContextHolder.getEngine(), "exec(args)", { exec, priority: EventPriority[priority] })
|
||||||
|
// 方法[]
|
||||||
|
let methods = new ReflectMethodArray(1);
|
||||||
|
methods[0] = ProxyMethod;
|
||||||
|
currentPriorityMap.put(listener, methods);
|
||||||
|
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
||||||
|
return listener;
|
||||||
|
} catch (ex: any) {
|
||||||
|
console.ex(ex)
|
||||||
|
} finally {
|
||||||
|
this.lock.unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unregister(eventCls: any, listener: any): void {
|
||||||
|
this.lock.lock()
|
||||||
|
try {
|
||||||
|
// private final Map<类, Map<优先级, Map<监听器, 方法[]>>> byListenerAndPriority = new HashMap<>();
|
||||||
|
// Map<优先级, Map<监听器, 方法[]>>
|
||||||
|
let prioritiesMap = this.byListenerAndPriority.get(eventCls);
|
||||||
|
if (prioritiesMap != null) {
|
||||||
|
let bindings = reflect.on(listener).get("bindings").get();
|
||||||
|
let priority = bindings["priority"];
|
||||||
|
// Map<监听器, 方法[]>
|
||||||
|
let currentPriorityMap = prioritiesMap.get(priority);
|
||||||
|
if (currentPriorityMap != null) {
|
||||||
|
currentPriorityMap.remove(listener);
|
||||||
|
if (currentPriorityMap.isEmpty()) {
|
||||||
|
prioritiesMap.remove(priority);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (prioritiesMap.isEmpty()) {
|
||||||
|
this.byListenerAndPriority.remove(eventCls);
|
||||||
|
}
|
||||||
|
this.bakeHandlers.invoke(this.eventBus, eventCls);
|
||||||
|
}
|
||||||
|
} catch (ex: any) {
|
||||||
|
console.ex(ex)
|
||||||
|
} finally {
|
||||||
|
this.lock.unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
17
packages/bungee/src/index.ts
Normal file
17
packages/bungee/src/index.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
/// <reference types="@javatypes/bungee-api" />
|
||||||
|
|
||||||
|
import { server } from '@ccms/api'
|
||||||
|
import { Container } from '@ccms/container'
|
||||||
|
|
||||||
|
import { BungeeConsole } from './console'
|
||||||
|
import './task'
|
||||||
|
import './event'
|
||||||
|
import './server'
|
||||||
|
import { BungeeNativePluginManager } from './plugin'
|
||||||
|
import './command'
|
||||||
|
import './channel'
|
||||||
|
|
||||||
|
export default function BungeeImpl(container: Container) {
|
||||||
|
container.bind(server.Console).toConstantValue(BungeeConsole)
|
||||||
|
container.rebind(server.NativePluginManager).toConstantValue(new BungeeNativePluginManager())
|
||||||
|
}
|
||||||
36
packages/bungee/src/plugin.ts
Normal file
36
packages/bungee/src/plugin.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
88
packages/bungee/src/server.ts
Normal file
88
packages/bungee/src/server.ts
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
import { server, task } from '@ccms/api'
|
||||||
|
import { provideSingleton, inject, postConstruct } from '@ccms/container'
|
||||||
|
|
||||||
|
import * as reflect from '@ccms/common/dist/reflect'
|
||||||
|
|
||||||
|
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||||
|
|
||||||
|
@provideSingleton(server.Server)
|
||||||
|
export class BungeeServer implements server.Server {
|
||||||
|
private pluginsFolder: string
|
||||||
|
private pipeline: any
|
||||||
|
private rootLogger: any
|
||||||
|
|
||||||
|
@inject(task.TaskManager)
|
||||||
|
private task: task.TaskManager
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.pluginsFolder = Bungee.getPluginsFolder().getCanonicalPath()
|
||||||
|
}
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
|
initialize() {
|
||||||
|
let count = 0
|
||||||
|
let wait = this.task.create(() => {
|
||||||
|
try {
|
||||||
|
// @ts-ignore
|
||||||
|
this.pipeline = reflect.on(base.getInstance().getProxy()).get('listeners').get().toArray()[0].pipeline()
|
||||||
|
wait.cancel()
|
||||||
|
} catch (ex: any) {
|
||||||
|
count++
|
||||||
|
if (count > 50) {
|
||||||
|
console.error('Reflect BungeeCord netty channel pipeline error time > 50times. Err: ' + ex)
|
||||||
|
wait.cancel()
|
||||||
|
} else {
|
||||||
|
console.warn('Wait BungeeCord start ready to get netty channel pipeline. Err: ' + ex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}).later(10).timer(20).submit()
|
||||||
|
try {
|
||||||
|
this.rootLogger = Bungee.getLogger()
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error("Can't found rootLogger!")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getPlayer(name: string) {
|
||||||
|
return Bungee.getPlayer(name)
|
||||||
|
}
|
||||||
|
getVersion(): string {
|
||||||
|
return Bungee.getVersion()
|
||||||
|
}
|
||||||
|
getOnlinePlayers() {
|
||||||
|
return Bungee.getPlayers()
|
||||||
|
}
|
||||||
|
getConsoleSender() {
|
||||||
|
return Bungee.getConsole()
|
||||||
|
}
|
||||||
|
getService(service: string) {
|
||||||
|
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 {
|
||||||
|
if (typeof sender === 'string') {
|
||||||
|
sender = this.getPlayer(sender)
|
||||||
|
}
|
||||||
|
return Bungee.getPluginManager().dispatchCommand(sender, command)
|
||||||
|
}
|
||||||
|
dispatchConsoleCommand(command: string): boolean {
|
||||||
|
return Bungee.getPluginManager().dispatchCommand(Bungee.getConsole(), command)
|
||||||
|
}
|
||||||
|
getPluginsFolder(): string {
|
||||||
|
return this.pluginsFolder
|
||||||
|
}
|
||||||
|
getNativePluginManager() {
|
||||||
|
return Bungee.getPluginManager() as any
|
||||||
|
}
|
||||||
|
getNettyPipeline() {
|
||||||
|
return this.pipeline
|
||||||
|
}
|
||||||
|
getRootLogger() {
|
||||||
|
return this.rootLogger
|
||||||
|
}
|
||||||
|
}
|
||||||
32
packages/bungee/src/task.ts
Normal file
32
packages/bungee/src/task.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { task, plugin } from '@ccms/api'
|
||||||
|
import { inject, provideSingleton } from '@ccms/container'
|
||||||
|
|
||||||
|
var Runnable = Java.type('java.lang.Runnable')
|
||||||
|
let TimeUnit = Java.type('java.util.concurrent.TimeUnit')
|
||||||
|
|
||||||
|
@provideSingleton(task.TaskManager)
|
||||||
|
export class BungeeTaskManager extends task.TaskManager {
|
||||||
|
create0(owner: plugin.Plugin, func: Function, id: number): task.Task {
|
||||||
|
return new BungeeTask(owner, func, id)
|
||||||
|
}
|
||||||
|
callSyncMethod(func: Function): any {
|
||||||
|
return func()
|
||||||
|
}
|
||||||
|
disable0() {
|
||||||
|
base.getInstance().getProxy().getScheduler().cancel(base.getInstance())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BungeeTask extends task.Task {
|
||||||
|
submit0(...args: any[]): task.Cancelable {
|
||||||
|
let run = new Runnable({ run: () => this.run(...args) })
|
||||||
|
if (this.isAsync) {
|
||||||
|
return base.getInstance().getProxy().getScheduler().runAsync(base.getInstance(), run)
|
||||||
|
}
|
||||||
|
if (this.interval) {
|
||||||
|
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
|
||||||
|
} else {
|
||||||
|
return base.getInstance().getProxy().getScheduler().schedule(base.getInstance(), run, this.laterTime * 50, TimeUnit.MILLISECONDS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
8
packages/bungee/tsconfig.json
Normal file
8
packages/bungee/tsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"extends": "../../tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": "src",
|
||||||
|
"outDir": "dist",
|
||||||
|
"allowJs": true
|
||||||
|
}
|
||||||
|
}
|
||||||
4
packages/common/.gitignore
vendored
4
packages/common/.gitignore
vendored
@@ -1,4 +0,0 @@
|
|||||||
/node_modules
|
|
||||||
/dist
|
|
||||||
/package-lock.json
|
|
||||||
/yarn.lock
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
src
|
|
||||||
test
|
|
||||||
typings
|
|
||||||
bundled
|
|
||||||
build
|
|
||||||
coverage
|
|
||||||
docs
|
|
||||||
wiki
|
|
||||||
gulpfile.js
|
|
||||||
bower.json
|
|
||||||
karma.conf.js
|
|
||||||
tsconfig.json
|
|
||||||
typings.json
|
|
||||||
CONTRIBUTING.md
|
|
||||||
ISSUE_TEMPLATE.md
|
|
||||||
PULL_REQUEST_TEMPLATE.md
|
|
||||||
tslint.json
|
|
||||||
wallaby.js
|
|
||||||
.travis.yml
|
|
||||||
.gitignore
|
|
||||||
.vscode
|
|
||||||
type_definitions
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/common",
|
"name": "@ccms/common",
|
||||||
"version": "0.0.0",
|
"version": "0.28.0-beta.7",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript common package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
"minecraft",
|
"minecraft",
|
||||||
@@ -12,21 +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",
|
||||||
"publishConfig": {
|
"files": [
|
||||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
"dist/*.js",
|
||||||
},
|
"dist/*.ts",
|
||||||
|
"dist/*.map"
|
||||||
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "pnpm clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"@ccms/nashorn": "^0.28.0-beta.7",
|
||||||
"rimraf": "^3.0.0",
|
"@javatypes/jdk": "^0.0.3"
|
||||||
"typescript": "^3.6.2"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||||
"@ms/nashorn": "^0.0.0"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import '@ms/nashorn'
|
import '@ccms/nashorn'
|
||||||
|
|
||||||
/*global Java, base, module, exports, require, __FILE__*/
|
/*global Java, base, module, exports, require, __FILE__*/
|
||||||
const Path = Java.type("java.nio.file.Path");
|
const Path = Java.type("java.nio.file.Path");
|
||||||
@@ -12,8 +12,8 @@ const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
|
|||||||
/**
|
/**
|
||||||
* 用文件分割符合并路径
|
* 用文件分割符合并路径
|
||||||
*/
|
*/
|
||||||
export function concat() {
|
export function concat(...args: string[]) {
|
||||||
return Array.prototype.join.call(arguments, separatorChar);
|
return args.join(separatorChar);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -23,12 +23,10 @@ export function concat() {
|
|||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
export function file(...opts: any[]): any {
|
export function file(...opts: any[]): any {
|
||||||
if (!arguments[0]) {
|
if (!opts[0]) { throw new Error("文件名称不得为 undefined 或者 null !") }
|
||||||
console.warn("文件名称不得为 undefined 或者 null !");
|
switch (opts.length) {
|
||||||
}
|
|
||||||
switch (arguments.length) {
|
|
||||||
case 1:
|
case 1:
|
||||||
var f = arguments[0];
|
var f = opts[0];
|
||||||
if (f instanceof File) {
|
if (f instanceof File) {
|
||||||
return f;
|
return f;
|
||||||
}
|
}
|
||||||
@@ -40,7 +38,7 @@ export function file(...opts: any[]): any {
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
return new File(file(arguments[0]), arguments[1]);
|
return new File(file(opts[0]), opts[1]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,7 +46,7 @@ export function file(...opts: any[]): any {
|
|||||||
* 创建目录
|
* 创建目录
|
||||||
* @param path
|
* @param path
|
||||||
*/
|
*/
|
||||||
export function mkdirs(path) {
|
export function mkdirs(path: any) {
|
||||||
// noinspection JSUnresolvedVariable
|
// noinspection JSUnresolvedVariable
|
||||||
file(path).parentFile.mkdirs();
|
file(path).parentFile.mkdirs();
|
||||||
}
|
}
|
||||||
@@ -57,7 +55,7 @@ export function mkdirs(path) {
|
|||||||
* 创建文件
|
* 创建文件
|
||||||
* @param file
|
* @param file
|
||||||
*/
|
*/
|
||||||
export function create(path) {
|
export function create(path: any) {
|
||||||
var f = file(path);
|
var f = file(path);
|
||||||
if (!f.exists()) {
|
if (!f.exists()) {
|
||||||
mkdirs(f);
|
mkdirs(f);
|
||||||
@@ -70,7 +68,7 @@ export function create(path) {
|
|||||||
* @param file
|
* @param file
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
export function path(f) {
|
export function path(f: any) {
|
||||||
return file(f).canonicalPath;
|
return file(f).canonicalPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,7 +78,7 @@ export function path(f) {
|
|||||||
* @param target 目标文件
|
* @param target 目标文件
|
||||||
* @param override 是否覆盖
|
* @param override 是否覆盖
|
||||||
*/
|
*/
|
||||||
export function copy(inputStream, target, override) {
|
export function copy(inputStream: any, target: any, override: any) {
|
||||||
Files.copy(inputStream, target.toPath(), StandardCopyOption[override ? 'REPLACE_EXISTING' : 'ATOMIC_MOVE']);
|
Files.copy(inputStream, target.toPath(), StandardCopyOption[override ? 'REPLACE_EXISTING' : 'ATOMIC_MOVE']);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,7 +141,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,155 +1,78 @@
|
|||||||
'use strict';
|
import * as querystring from 'querystring'
|
||||||
/**
|
|
||||||
* HTTP 网络类
|
|
||||||
* Created by 蒋天蓓 on 2017/2/9 0009.
|
|
||||||
*/
|
|
||||||
|
|
||||||
/*global Java, base, module, exports, require, __FILE__*/
|
const URL = Java.type('java.net.URL')
|
||||||
|
const Paths = Java.type('java.nio.file.Paths')
|
||||||
|
const Files = Java.type('java.nio.file.Files')
|
||||||
|
const StandardCopyOption = Java.type('java.nio.file.StandardCopyOption')
|
||||||
|
|
||||||
var URL = Java.type("java.net.URL");
|
export type Method =
|
||||||
var UUID = Java.type("java.util.UUID");
|
| 'get' | 'GET'
|
||||||
var System = Java.type("java.lang.System");
|
| 'delete' | 'DELETE'
|
||||||
var Files = Java.type("java.nio.file.Files");
|
| 'head' | 'HEAD'
|
||||||
var Paths = Java.type("java.nio.file.Paths");
|
| 'options' | 'OPTIONS'
|
||||||
var JavaString = Java.type("java.lang.String");
|
| 'post' | 'POST'
|
||||||
var SecureRandom = Java.type("java.security.SecureRandom");
|
| 'put' | 'PUT'
|
||||||
|
| 'patch' | 'PATCH'
|
||||||
|
|
||||||
var SSLContext = Java.type("javax.net.ssl.SSLContext");
|
interface RequestConfig {
|
||||||
var HttpsURLConnection = Java.type("javax.net.ssl.HttpsURLConnection");
|
url?: string
|
||||||
|
method?: Method
|
||||||
|
headers?: { [key: string]: string }
|
||||||
|
params?: { [key: string]: string }
|
||||||
|
data?: any,
|
||||||
|
connectTimeout?: number,
|
||||||
|
readTimeout?: number,
|
||||||
|
}
|
||||||
|
|
||||||
var HostnameVerifier = Java.type("javax.net.ssl.HostnameVerifier");
|
function request(config: RequestConfig) {
|
||||||
var X509TrustManager = Java.type("javax.net.ssl.X509TrustManager");
|
// @ts-ignore XMLHttpRequest class only exist nashorn polyfill
|
||||||
|
let xhr = new XMLHttpRequest()
|
||||||
// noinspection JSUnusedGlobalSymbols,JSUnusedLocalSymbols
|
if (config.connectTimeout) {
|
||||||
var TrustAnyHostnameVerifier = new HostnameVerifier({
|
xhr.connectTimeout = config.connectTimeout
|
||||||
verify: function(hostname, session) {
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
});
|
if (config.readTimeout) {
|
||||||
|
xhr.readTimeout = config.readTimeout
|
||||||
var SSLSocketFactory = function initSSLSocketFactory() {
|
|
||||||
var sslContext = SSLContext.getInstance("TLS");
|
|
||||||
// noinspection JSUnusedGlobalSymbols
|
|
||||||
sslContext.init(null, [new X509TrustManager({
|
|
||||||
getAcceptedIssuers: function() {
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
checkClientTrusted: function(chain, authType) {
|
|
||||||
},
|
|
||||||
checkServerTrusted: function(chain, authType) {
|
|
||||||
}
|
|
||||||
})], new SecureRandom());
|
|
||||||
return sslContext.getSocketFactory();
|
|
||||||
}();
|
|
||||||
|
|
||||||
var config = {
|
|
||||||
Charset: 'UTF-8',
|
|
||||||
ConnectTimeout: 10000,
|
|
||||||
ReadTimeout: 10000,
|
|
||||||
Debug: false
|
|
||||||
};
|
|
||||||
|
|
||||||
function open(url, method, header) {
|
|
||||||
// conn.setRequestProperty
|
|
||||||
var conn = new URL(url).openConnection();
|
|
||||||
if (conn instanceof HttpsURLConnection) {
|
|
||||||
conn.setHostnameVerifier(TrustAnyHostnameVerifier);
|
|
||||||
conn.setSSLSocketFactory(SSLSocketFactory);
|
|
||||||
}
|
}
|
||||||
conn.setRequestMethod(method);
|
xhr.open(config.method, config.url, false)
|
||||||
conn.setDoOutput(true);
|
for (const header in config.headers) {
|
||||||
conn.setDoInput(true);
|
xhr.setRequestHeader(header, config.headers[header])
|
||||||
conn.setConnectTimeout(config.ConnectTimeout);
|
}
|
||||||
conn.setReadTimeout(config.ReadTimeout);
|
let body = config.data
|
||||||
if (header) {
|
if (body && typeof body !== "string") {
|
||||||
for (var key in header) {
|
switch (config.headers['Content-Type']) {
|
||||||
// noinspection JSUnfilteredForInLoop
|
case "application/json":
|
||||||
conn.setRequestProperty(key, header[key]);
|
body = JSON.stringify(body)
|
||||||
|
break
|
||||||
|
case "application/x-www-form-urlencoded":
|
||||||
|
body = querystring.encode(body)
|
||||||
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return conn;
|
xhr.send(body)
|
||||||
}
|
if (xhr.getResponseHeader("Content-Type").indexOf('application/json') != -1) {
|
||||||
|
xhr.responseType = "json"
|
||||||
function buildUrl(url, params) {
|
|
||||||
if (params && Object.keys(params).length > 0) {
|
|
||||||
var queryStart = url.indexOf('?');
|
|
||||||
if (queryStart === -1) {
|
|
||||||
url += '?';
|
|
||||||
}
|
|
||||||
return url += object2URLSearchParams(params);
|
|
||||||
}
|
}
|
||||||
return url;
|
// @ts-ignore get only exist nashorn polyfill
|
||||||
|
return xhr.get()
|
||||||
}
|
}
|
||||||
|
|
||||||
function request(config) {
|
function download(url: string, target: string) {
|
||||||
var conn = open(buildUrl(config.url, config.query), config.method, config.header);
|
console.debug(`Start Download file ${target} from ${url}....`)
|
||||||
try {
|
Files.copy(new URL(url).openStream(), Paths.get(target), StandardCopyOption.REPLACE_EXISTING)
|
||||||
conn.connect();
|
console.debug(`File ${target} Download Complate...`)
|
||||||
var data = config.data;
|
}
|
||||||
if (data) {
|
|
||||||
var out = conn.getOutputStream();
|
function _proxy(method: Method) {
|
||||||
if (typeof data === "object") {
|
return function (url: string, data?: any, config: RequestConfig = {}) {
|
||||||
var type = config.header['Content-Type'];
|
if (!config.headers) { config.headers = {} }
|
||||||
switch (type) {
|
config.headers['Content-Type'] = config.headers['Content-Type'] ?? 'application/json'
|
||||||
case "application/x-www-form-urlencoded":
|
return request({ url, method, data, ...config })
|
||||||
data = object2URLSearchParams(data);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
data = JSON.stringify(data)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out.write(new JavaString(data).getBytes(config.Charset));
|
|
||||||
out.flush();
|
|
||||||
out.close();
|
|
||||||
}
|
|
||||||
return response(conn);
|
|
||||||
} finally {
|
|
||||||
conn.disconnect();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function response(conn) {
|
export default {
|
||||||
var temp = Paths.get(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
|
get: _proxy('GET'),
|
||||||
Files.copy(conn.getInputStream(), temp);
|
post: _proxy('POST'),
|
||||||
var result = new JavaString(Files.readAllBytes(temp), config.Charset);
|
request,
|
||||||
var tempFile = temp.toFile();
|
download
|
||||||
tempFile.delete() || tempFile.deleteOnExit();
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function object2URLSearchParams(params) {
|
|
||||||
var temp: string[] = [];
|
|
||||||
for (var key in params) {
|
|
||||||
temp.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
|
|
||||||
}
|
|
||||||
return temp.join('&')
|
|
||||||
}
|
|
||||||
|
|
||||||
var http = {
|
|
||||||
config: config,
|
|
||||||
request: request
|
|
||||||
};
|
|
||||||
|
|
||||||
['GET', 'DELETE', 'HEAD', 'OPTIONS'].forEach(function(method) {
|
|
||||||
http[method.toLowerCase()] = function __likeGet__(url, data, config = {}) {
|
|
||||||
return this.request({
|
|
||||||
...config,
|
|
||||||
url: url,
|
|
||||||
method: method,
|
|
||||||
query: data
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
['POST', 'PUT', 'PATCH'].forEach(function(method) {
|
|
||||||
http[method.toLowerCase()] = function __likePost__(url, data, config) {
|
|
||||||
return this.request({
|
|
||||||
...config,
|
|
||||||
url: url,
|
|
||||||
method: method,
|
|
||||||
data: data
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
export = http;
|
|
||||||
|
|||||||
1243
packages/common/src/qrcode.ts
Normal file
1243
packages/common/src/qrcode.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,186 +1,202 @@
|
|||||||
import '@ms/core'
|
/// <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 蒋天蓓 on 2017/2/9 0009.
|
* Created by MiaoWoo on 2017/2/9 0009.
|
||||||
*/
|
*/
|
||||||
var JavaClass = Java.type('java.lang.Class');
|
|
||||||
var JavaObject = Java.type('java.lang.Object')
|
|
||||||
var NoSuchFieldException = Java.type('java.lang.NoSuchFieldException');
|
|
||||||
var methodCache = [];
|
|
||||||
|
|
||||||
class Reflect {
|
class Reflect {
|
||||||
private obj: any;
|
private obj: java.lang.Object
|
||||||
private class: any
|
private class: java.lang.Class<any>
|
||||||
|
|
||||||
constructor(obj: any) {
|
constructor(obj: any) {
|
||||||
|
// 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
|
||||||
this.class = obj.class;
|
if (obj !== null && obj !== undefined && obj.class) {
|
||||||
|
this.class = obj.class
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
method(...args: any[]) {
|
method(name: string, ...args: java.lang.Class<any>[]) {
|
||||||
return declaredMethod(this.class, args[0], types(args.slice(1)));
|
return declaredMethod(this.class, name, ...args)
|
||||||
}
|
}
|
||||||
|
|
||||||
methods() {
|
methods() {
|
||||||
return Java.from(declaredMethods(this.class));
|
return Java.from(declaredMethods(this.class))
|
||||||
}
|
}
|
||||||
|
|
||||||
field(name) {
|
field(nameOrIndex: string | java.lang.String | number, declared = false): java.lang.reflect.Field {
|
||||||
try {
|
if (nameOrIndex == undefined || nameOrIndex == null) throw new Error(`reflect field name can't be ${nameOrIndex} from ${this.class.getName()}!`)
|
||||||
// Try getting a public field
|
let key = this.class.getName() + ':' + nameOrIndex + ':' + declared
|
||||||
var field = this.class.field(name);
|
if (fieldCache.has(key)) {
|
||||||
return on(field.get(this.obj));
|
return fieldCache.get(key)
|
||||||
} 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") {
|
||||||
fields(declared) {
|
field = this.fields(declared)[nameOrIndex]
|
||||||
return Java.from(declared ? this.class.declaredFields : this.class.fields);
|
} 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
values(declared) {
|
fields(declared = false): java.lang.reflect.Field[] {
|
||||||
var cache = {};
|
return Java.from(declared ? this.class.getDeclaredFields() : this.class.getFields())
|
||||||
var feds = declared ? this.class.declaredFields : this.class.fields;
|
|
||||||
Java.from(feds).forEach(function(fed) {
|
|
||||||
cache[fed.name] = this.field(fed.name).get();
|
|
||||||
}.bind(this))
|
|
||||||
return cache;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
call(...args) {
|
values(declared = false) {
|
||||||
var params = args.slice(1);
|
return this.fields(declared).reduce((cache, field) => { return cache[field.getName()] = this.get(field.getName()).get() }, {}) as any
|
||||||
var method = declaredMethod(this.class, args[0], types(params));
|
}
|
||||||
return on(method.invoke(this.get(), params));
|
|
||||||
};
|
|
||||||
|
|
||||||
get(...args) {
|
call(...args: any[]): Reflect {
|
||||||
return args.length === 1 ? this.field(args[0]) : this.obj;
|
let params = args.slice(1)
|
||||||
};
|
let method = accessible(declaredMethod(this.class, args[0], ...types(params)))
|
||||||
|
let result = method.invoke(this.get(), params)
|
||||||
|
return result && on(result)
|
||||||
|
}
|
||||||
|
|
||||||
// noinspection JSUnusedGlobalSymbols
|
get(): any
|
||||||
set(name, value) {
|
get(index: number, declared?: boolean): Reflect
|
||||||
accessible(declaredField(this.class, name)).set(this.obj, value);
|
get(prop: string): Reflect
|
||||||
return this;
|
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))
|
||||||
|
}
|
||||||
|
|
||||||
create(...args) {
|
set(param: string | number, value: any, declared: boolean = true): Reflect {
|
||||||
return on(declaredConstructor(this.class, args).newInstance(args));
|
this.field(param, declared).set(this.obj, value)
|
||||||
};
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
create(...args): Reflect {
|
||||||
|
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, def?) {
|
function types(values: any[], def?: any) {
|
||||||
if (values === null) {
|
if (values === null) {
|
||||||
return [];
|
return []
|
||||||
}
|
}
|
||||||
var result = [];
|
let result: java.lang.Class<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(accessible) {
|
function accessible<T extends java.lang.reflect.AccessibleObject>(accessible: T): T {
|
||||||
if (accessible === null) {
|
if (!accessible?.isAccessible()) {
|
||||||
return null;
|
accessible.setAccessible(true)
|
||||||
}
|
}
|
||||||
if (!accessible.isAccessible()) {
|
return accessible
|
||||||
accessible.setAccessible(true);
|
|
||||||
}
|
|
||||||
return accessible;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredConstructor(clazz, param) {
|
function declaredConstructor(clazz, param) {
|
||||||
var constructor;
|
let constructor
|
||||||
try {
|
try {
|
||||||
constructor = clazz.getDeclaredConstructor(types(param));
|
constructor = clazz.getDeclaredConstructor(types(param))
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
try {
|
try {
|
||||||
constructor = clazz.getDeclaredConstructor(types(param, true));
|
constructor = clazz.getDeclaredConstructor(types(param, true))
|
||||||
} catch (ex) {
|
} catch (ex: any) {
|
||||||
constructor = clazz.getDeclaredConstructors()[0];
|
constructor = clazz.getDeclaredConstructors()[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return accessible(constructor);
|
return accessible(constructor)
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredField(clazz, name) {
|
function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.String) {
|
||||||
var field = null;
|
if (!clazz) { throw Error(`target class can't be ${clazz}!`) }
|
||||||
|
let target = clazz
|
||||||
|
let field = null
|
||||||
// noinspection JSUnresolvedVariable
|
// noinspection JSUnresolvedVariable
|
||||||
while (clazz !== JavaObject.class) {
|
while (target !== JavaObject.class) {
|
||||||
|
console.debug(`reflect field ${name} from ${target.getName()}`)
|
||||||
try {
|
try {
|
||||||
field = clazz.getDeclaredField(name);
|
field = target.getDeclaredField(name)
|
||||||
if (field !== null) {
|
if (field !== null) { break }
|
||||||
break;
|
} catch (error: any) {
|
||||||
}
|
if (target === undefined) { break }
|
||||||
} catch (e) {
|
target = target.getSuperclass()
|
||||||
clazz = clazz.getSuperclass();
|
console.debug(`switch to super class: ${target.getName()}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (field === null) {
|
if (field === null) {
|
||||||
throw new NoSuchFieldException(name + " is not found in " + clazz.name);
|
throw new NoSuchFieldException(name + " is not found in " + clazz.getName())
|
||||||
}
|
}
|
||||||
return field;
|
return field
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredMethod(clazz, name, clazzs) {
|
function declaredMethod(clazz: java.lang.Class<any>, nameOrIndex: string | number, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
|
||||||
var key = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
|
let key = clazz.getName() + '.' + nameOrIndex + ':' + (clazzs || []).map(c => c.getName()).join(':')
|
||||||
if (!methodCache[key]) {
|
if (methodCache.has(key)) { return methodCache.get(key) }
|
||||||
try {
|
let target = clazz
|
||||||
methodCache[key] = clazz.getMethod(name, clazzs);
|
if (typeof nameOrIndex === "number") {
|
||||||
} catch (ex) {
|
methodCache.set(key, declaredMethods(clazz)[nameOrIndex])
|
||||||
methodCache[key] = clazz.getDeclaredMethod(name, clazzs);
|
} else {
|
||||||
|
while (target !== JavaObject.class && !methodCache.has(key)) {
|
||||||
|
try {
|
||||||
|
console.debug(`reflect method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${target.getName()}`)
|
||||||
|
try {
|
||||||
|
methodCache.set(key, target.getMethod(nameOrIndex, clazzs as any))
|
||||||
|
} catch (ex: any) {
|
||||||
|
try {
|
||||||
|
methodCache.set(key, target.getDeclaredMethod(nameOrIndex, clazzs as any))
|
||||||
|
} 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()}`)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return methodCache[key];
|
if (!methodCache.has(key)) throw new Error(`can't reflect method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${clazz.getName()}!`)
|
||||||
|
return methodCache.get(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredMethods(clazz) {
|
function declaredMethods(clazz: java.lang.Class<any>) {
|
||||||
return clazz.declaredMethods;
|
return clazz.getDeclaredMethods()
|
||||||
}
|
}
|
||||||
|
|
||||||
var classMethodsCache = [];
|
|
||||||
|
|
||||||
function mapToObject(javaObj) {
|
function mapToObject(javaObj) {
|
||||||
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
if (!Java.isJavaObject(javaObj)) { throw new TypeError(`argument ${javaObj} is not a java object.`) }
|
||||||
var target = {};
|
let target = Proxy.newProxy(javaObj, {
|
||||||
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t));
|
apply: (target, name, args) => { return args ? javaObj[name](args) : javaObj[name]() }
|
||||||
return target;
|
})
|
||||||
}
|
return target
|
||||||
|
|
||||||
function getJavaObjectMethods(javaObj) {
|
|
||||||
var className = javaObj.class.name;
|
|
||||||
if (!classMethodsCache[className]) {
|
|
||||||
var names = [];
|
|
||||||
var methods = javaObj.class.methods;
|
|
||||||
for (var i in methods) {
|
|
||||||
names.push(methods[i].name);
|
|
||||||
}
|
|
||||||
classMethodsCache[className] = names;
|
|
||||||
}
|
|
||||||
return classMethodsCache[className];
|
|
||||||
}
|
|
||||||
|
|
||||||
function mapMethod(target, source, name) {
|
|
||||||
target[name] = function __SimpleDynamicMethod__(...args) {
|
|
||||||
if (args.length > 0) {
|
|
||||||
return source[name](args);
|
|
||||||
} else {
|
|
||||||
return source[name]();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function on(obj) {
|
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 = {
|
||||||
@@ -188,4 +204,4 @@ export = {
|
|||||||
accessible,
|
accessible,
|
||||||
declaredMethods,
|
declaredMethods,
|
||||||
mapToObject
|
mapToObject
|
||||||
};
|
}
|
||||||
|
|||||||
113
packages/common/src/tellraw.ts
Normal file
113
packages/common/src/tellraw.ts
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
class ChatMessagePart {
|
||||||
|
private internal: any = {}
|
||||||
|
|
||||||
|
get text() {
|
||||||
|
return this.internal.text
|
||||||
|
}
|
||||||
|
set text(text: string) {
|
||||||
|
this.internal.text = text
|
||||||
|
}
|
||||||
|
|
||||||
|
click(action: string, value: string) {
|
||||||
|
this.internal.clickEvent = { action, value }
|
||||||
|
}
|
||||||
|
|
||||||
|
hover(action: string, value: string) {
|
||||||
|
this.internal.hoverEvent = { action, value }
|
||||||
|
}
|
||||||
|
|
||||||
|
convert() {
|
||||||
|
return this.internal
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Tellraw {
|
||||||
|
static duplicateChar = '§卐'
|
||||||
|
static create() {
|
||||||
|
return new Tellraw().then(Tellraw.duplicateChar)
|
||||||
|
}
|
||||||
|
|
||||||
|
private cache: string = '';
|
||||||
|
private parts = [new ChatMessagePart()];
|
||||||
|
|
||||||
|
then(part: ChatMessagePart | string) {
|
||||||
|
if (typeof part === "string") {
|
||||||
|
var newPart = new ChatMessagePart()
|
||||||
|
newPart.text = part
|
||||||
|
this.then(newPart)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
var last = this.latest()
|
||||||
|
if (!last.text) {
|
||||||
|
last.text = part.text
|
||||||
|
} else {
|
||||||
|
this.parts.push(part)
|
||||||
|
}
|
||||||
|
this.cache = null
|
||||||
|
}
|
||||||
|
|
||||||
|
text(text: string) {
|
||||||
|
this.latest().text = text
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
tip(texts: string) {
|
||||||
|
return this.hover(texts)
|
||||||
|
}
|
||||||
|
|
||||||
|
hover(texts: string) {
|
||||||
|
this.latest().hover("show_text", texts)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
item(item: string) {
|
||||||
|
this.latest().hover("show_item", item)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
command(command: string) {
|
||||||
|
this.latest().click("run_command", command)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
suggest(url: string) {
|
||||||
|
this.latest().click("suggest_command", url)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
file(path: string) {
|
||||||
|
this.latest().click("open_file", path)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
link(url: string) {
|
||||||
|
this.latest().click("open_url", url)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
latest() {
|
||||||
|
return this.parts[this.parts.length - 1]
|
||||||
|
}
|
||||||
|
|
||||||
|
json() {
|
||||||
|
if (!this.cache) {
|
||||||
|
var temp = []
|
||||||
|
this.parts.forEach(t => {
|
||||||
|
temp.push(t.convert())
|
||||||
|
})
|
||||||
|
this.cache = JSON.stringify(temp)
|
||||||
|
console.trace(this.cache)
|
||||||
|
}
|
||||||
|
return this.cache
|
||||||
|
}
|
||||||
|
|
||||||
|
string() {
|
||||||
|
var temp = ''
|
||||||
|
this.parts.forEach(t => {
|
||||||
|
temp += t.text
|
||||||
|
})
|
||||||
|
return temp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Tellraw
|
||||||
@@ -1,25 +1,30 @@
|
|||||||
function Template(tpl: string) {
|
class Template {
|
||||||
var match: RegExpExecArray;
|
private renderFunc: Function;
|
||||||
var code = ['var r=[];'];
|
|
||||||
var re = /\{\{\s*([a-zA-Z\.\_0-9()]+)\s*\}\}/m;
|
constructor(tpl: string) {
|
||||||
function addLine(text: string) {
|
var match: RegExpExecArray;
|
||||||
code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
|
var code = ['var r=[];'];
|
||||||
};
|
var re = /\{\{\s*([a-zA-Z\.\_0-9()]+)\s*\}\}/m;
|
||||||
while (match = re.exec(tpl)) {
|
|
||||||
if (match.index > 0) {
|
while (match = re.exec(tpl)) {
|
||||||
addLine(tpl.slice(0, match.index));
|
if (match.index > 0) {
|
||||||
|
this.addLine(code, tpl.slice(0, match.index));
|
||||||
|
}
|
||||||
|
code.push('r.push(this.' + match[1] + ');');
|
||||||
|
tpl = tpl.substring(match.index + match[0].length);
|
||||||
}
|
}
|
||||||
code.push('r.push(this.' + match[1] + ');');
|
this.addLine(code, tpl);
|
||||||
tpl = tpl.substring(match.index + match[0].length);
|
code.push('return r.join(\'\');');
|
||||||
|
// 创建函数:
|
||||||
|
this.renderFunc = new Function(code.join('\n'));
|
||||||
|
}
|
||||||
|
addLine(code: string[], text: string) {
|
||||||
|
code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
|
||||||
}
|
}
|
||||||
addLine(tpl);
|
|
||||||
code.push('return r.join(\'\');');
|
|
||||||
// 创建函数:
|
|
||||||
var fn = new Function(code.join('\n'));
|
|
||||||
// 用render()调用函数并绑定this参数:
|
// 用render()调用函数并绑定this参数:
|
||||||
this.render = function(model) {
|
render(model: object) {
|
||||||
return fn.apply(model);
|
return this.renderFunc.apply(model);
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export = {
|
export = {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import '@ms/nashorn'
|
import '@ccms/nashorn'
|
||||||
|
|
||||||
let Files = Java.type("java.nio.file.Files");
|
let Files = Java.type("java.nio.file.Files");
|
||||||
let Paths = Java.type("java.nio.file.Paths");
|
let Paths = Java.type("java.nio.file.Paths");
|
||||||
|
|||||||
32
packages/common/src/thread-pool.ts
Normal file
32
packages/common/src/thread-pool.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
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()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
35
packages/common/src/version.ts
Normal file
35
packages/common/src/version.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@
|
|||||||
"extends": "../../tsconfig.json",
|
"extends": "../../tsconfig.json",
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"baseUrl": "src",
|
"baseUrl": "src",
|
||||||
"outDir": "dist",
|
"outDir": "dist"
|
||||||
"declaration": true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
46
packages/compile/package.json
Normal file
46
packages/compile/package.json
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
{
|
||||||
|
"name": "@ccms/compile",
|
||||||
|
"version": "0.28.0-beta.7",
|
||||||
|
"description": "MiaoScript compile 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": {
|
||||||
|
"@ccms/api": "^0.28.0-beta.7",
|
||||||
|
"@ccms/bukkit": "^0.28.0-beta.7",
|
||||||
|
"@ccms/bungee": "^0.28.0-beta.7",
|
||||||
|
"@ccms/common": "^0.28.0-beta.7",
|
||||||
|
"@ccms/container": "^0.28.0-beta.7",
|
||||||
|
"@ccms/core": "^0.28.0-beta.7",
|
||||||
|
"@ccms/database": "^0.28.0-beta.7",
|
||||||
|
"@ccms/i18n": "^0.28.0-beta.7",
|
||||||
|
"@ccms/molang": "^0.28.0-beta.7",
|
||||||
|
"@ccms/nashorn": "^0.28.0-beta.7",
|
||||||
|
"@ccms/nodejs": "^0.28.0-beta.7",
|
||||||
|
"@ccms/nukkit": "^0.28.0-beta.7",
|
||||||
|
"@ccms/plugin": "^0.28.0-beta.7",
|
||||||
|
"@ccms/polyfill": "^0.28.0-beta.7",
|
||||||
|
"@ccms/protocol": "^0.28.0-beta.7",
|
||||||
|
"@ccms/qrcode": "^0.28.0-beta.7",
|
||||||
|
"@ccms/sponge": "^0.28.0-beta.7",
|
||||||
|
"@ccms/websocket": "^0.28.0-beta.7"
|
||||||
|
}
|
||||||
|
}
|
||||||
5
packages/compile/src/index.ts
Normal file
5
packages/compile/src/index.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import * as ts from 'typescript'
|
||||||
|
|
||||||
|
let scan = ts.createScanner(ts.ScriptTarget.ES5, true, ts.LanguageVariant.Standard)
|
||||||
|
scan.setText('let a = 1')
|
||||||
|
scan.tryScan(() => { })
|
||||||
7
packages/compile/tsconfig.json
Normal file
7
packages/compile/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"extends": "../../tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": "src",
|
||||||
|
"outDir": "dist"
|
||||||
|
}
|
||||||
|
}
|
||||||
4
packages/container/.gitignore
vendored
4
packages/container/.gitignore
vendored
@@ -1,4 +0,0 @@
|
|||||||
/node_modules
|
|
||||||
/dist
|
|
||||||
/package-lock.json
|
|
||||||
/yarn.lock
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
src
|
|
||||||
test
|
|
||||||
typings
|
|
||||||
bundled
|
|
||||||
build
|
|
||||||
coverage
|
|
||||||
docs
|
|
||||||
wiki
|
|
||||||
gulpfile.js
|
|
||||||
bower.json
|
|
||||||
karma.conf.js
|
|
||||||
tsconfig.json
|
|
||||||
typings.json
|
|
||||||
CONTRIBUTING.md
|
|
||||||
ISSUE_TEMPLATE.md
|
|
||||||
PULL_REQUEST_TEMPLATE.md
|
|
||||||
tslint.json
|
|
||||||
wallaby.js
|
|
||||||
.travis.yml
|
|
||||||
.gitignore
|
|
||||||
.vscode
|
|
||||||
type_definitions
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/container",
|
"name": "@ccms/container",
|
||||||
"version": "0.0.0",
|
"version": "0.28.0-beta.7",
|
||||||
"description": "MiaoScript container package",
|
"description": "MiaoScript container package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -12,21 +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",
|
||||||
"publishConfig": {
|
"files": [
|
||||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
"dist/*.js",
|
||||||
},
|
"dist/*.ts",
|
||||||
|
"dist/*.map"
|
||||||
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "pnpm clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"@ccms/nashorn": "^0.28.0-beta.7"
|
||||||
"rimraf": "^3.0.0",
|
|
||||||
"typescript": "^3.6.2"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"inversify": "^6.0.1",
|
||||||
"inversify-binding-decorators": "^4.0.0"
|
"inversify-binding-decorators": "^4.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
7
packages/container/src/constants.ts
Normal file
7
packages/container/src/constants.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
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,93 +1,64 @@
|
|||||||
import { interfaces, Container } from "inversify";
|
import { interfaces, Container } from "inversify"
|
||||||
|
import { _proxyGetter } from "./utils"
|
||||||
|
|
||||||
let _container: Container;
|
let _container: Container
|
||||||
|
|
||||||
const CONTAINER = Symbol.for("@ms/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() {
|
|
||||||
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(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(CONTAINER, container, Reflect);
|
Reflect.defineMetadata(ContainerInstance, container, Reflect)
|
||||||
_container = container;
|
return _container = container
|
||||||
}
|
}
|
||||||
|
|
||||||
function getContainer(): Container {
|
function getContainer(): Container {
|
||||||
return _container || Reflect.getMetadata(CONTAINER, Reflect)
|
return _container || initContainer(new Container())
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
||||||
@@ -97,8 +68,9 @@ let lazyMultiInject = makePropertyMultiInjectDecorator(doCache)
|
|||||||
export {
|
export {
|
||||||
initContainer,
|
initContainer,
|
||||||
getContainer,
|
getContainer,
|
||||||
|
ContainerInstance,
|
||||||
lazyInject,
|
lazyInject,
|
||||||
lazyInjectNamed,
|
lazyInjectNamed,
|
||||||
lazyInjectTagged,
|
lazyInjectTagged,
|
||||||
lazyMultiInject
|
lazyMultiInject
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,23 +1,180 @@
|
|||||||
import "reflect-metadata";
|
/// <reference types="@ccms/nashorn" />
|
||||||
import { interfaces, Container } from 'inversify';
|
|
||||||
import { fluentProvide } from 'inversify-binding-decorators';
|
|
||||||
|
|
||||||
const provideNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
|
import "reflect-metadata"
|
||||||
return fluentProvide(identifier).whenTargetNamed(name).done();
|
import { initContainer, getContainer } from './decorators'
|
||||||
};
|
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();
|
/**
|
||||||
|
* 注册一个单例对象
|
||||||
|
* @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
|
|
||||||
};
|
|
||||||
|
|||||||
30
packages/container/src/utils.ts
Normal file
30
packages/container/src/utils.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
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
|
||||||
|
})
|
||||||
|
}
|
||||||
4
packages/core/.gitignore
vendored
4
packages/core/.gitignore
vendored
@@ -1,4 +0,0 @@
|
|||||||
/node_modules
|
|
||||||
/dist
|
|
||||||
/package-lock.json
|
|
||||||
/yarn.lock
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
src
|
|
||||||
test
|
|
||||||
typings
|
|
||||||
bundled
|
|
||||||
build
|
|
||||||
coverage
|
|
||||||
docs
|
|
||||||
wiki
|
|
||||||
gulpfile.js
|
|
||||||
bower.json
|
|
||||||
karma.conf.js
|
|
||||||
tsconfig.json
|
|
||||||
typings.json
|
|
||||||
CONTRIBUTING.md
|
|
||||||
ISSUE_TEMPLATE.md
|
|
||||||
PULL_REQUEST_TEMPLATE.md
|
|
||||||
tslint.json
|
|
||||||
wallaby.js
|
|
||||||
.travis.yml
|
|
||||||
.gitignore
|
|
||||||
.vscode
|
|
||||||
type_definitions
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/core",
|
"name": "@ccms/core",
|
||||||
"version": "0.0.0",
|
"version": "0.28.0-beta.7",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript core package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
"minecraft",
|
"minecraft",
|
||||||
@@ -12,22 +12,28 @@
|
|||||||
"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",
|
||||||
"publishConfig": {
|
"files": [
|
||||||
"registry": "https://repo.yumc.pw/repository/npm/"
|
"dist/*.js",
|
||||||
},
|
"dist/*.ts",
|
||||||
|
"dist/*.map"
|
||||||
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "npx tsc --watch",
|
"watch": "pnpm rollup -c rollup.config.js --watch",
|
||||||
"build": "yarn clean && npx tsc",
|
"build": "pnpm clean && pnpm rollup -c rollup.config.js",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"@rollup/plugin-typescript": "^11.1.5",
|
||||||
"rimraf": "^3.0.0",
|
"rollup": "^2.79.1",
|
||||||
"typescript": "^3.6.2"
|
"rollup-obfuscator": "^3.0.2",
|
||||||
|
"rollup-plugin-peer-deps-external": "^2.2.4"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/container": "^0.0.0",
|
"@ccms/api": "^0.28.0-beta.7",
|
||||||
"@ms/plugin": "^0.0.0"
|
"@ccms/common": "^0.28.0-beta.7",
|
||||||
}
|
"@ccms/container": "^0.28.0-beta.7",
|
||||||
|
"js-yaml": "^4.1.0"
|
||||||
|
},
|
||||||
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
|
|||||||
49
packages/core/rollup.config.js
Normal file
49
packages/core/rollup.config.js
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
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
Normal file
1
packages/core/src/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
script
|
||||||
@@ -1,28 +1,182 @@
|
|||||||
import '@ms/nashorn'
|
let containerStartTime = Date.now()
|
||||||
|
console.i18n("ms.core.ioc.initialize", { scope: global.scope })
|
||||||
|
import { plugin, server, task, constants, console as jsconsole } from '@ccms/api'
|
||||||
|
import { DefaultContainer as container, provideSingleton, ContainerInstance, buildProviderModule, Autowired } from '@ccms/container'
|
||||||
|
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'
|
||||||
|
import { VersionUtils } from '@ccms/common/dist/version'
|
||||||
|
|
||||||
import { plugin, server } from '@ms/api'
|
const UUID = Java.type('java.util.UUID')
|
||||||
import { DefaultContainer as container } from '@ms/container'
|
const MiaoScriptAPI = Java.type('pw.yumc.MiaoScript.api.MiaoScriptAPI')
|
||||||
import { PluginManagerImpl } from '@ms/plugin'
|
|
||||||
|
|
||||||
try {
|
@provideSingleton(MiaoScriptCore)
|
||||||
Java.type("org.bukkit.Bukkit");
|
class MiaoScriptCore {
|
||||||
require('@ms/bukkit');
|
@Autowired(server.Console)
|
||||||
} catch (ex) {
|
private Console: Console
|
||||||
|
@Autowired(plugin.PluginFolder)
|
||||||
|
private pluginFolder: string
|
||||||
|
@Autowired()
|
||||||
|
private taskManager: task.TaskManager
|
||||||
|
@Autowired()
|
||||||
|
private pluginManager: plugin.PluginManager
|
||||||
|
|
||||||
|
enable() {
|
||||||
|
process.emit('core.before.enable')
|
||||||
|
this.loadServerConsole()
|
||||||
|
try {
|
||||||
|
MiaoScriptAPI.setPluginManager(this.pluginManager)
|
||||||
|
} catch (error) {
|
||||||
|
}
|
||||||
|
this.loadPlugins()
|
||||||
|
process.emit('core.after.enable')
|
||||||
|
console.i18n("ms.core.engine.completed", {
|
||||||
|
loader: base.version,
|
||||||
|
version: 'v' + global.ScriptEngineVersion,
|
||||||
|
time: (Date.now() - global.ScriptEngineStartTime) / 1000
|
||||||
|
})
|
||||||
|
return () => this.disable()
|
||||||
|
}
|
||||||
|
|
||||||
|
loadServerConsole() {
|
||||||
|
process.emit('core.before.load.console')
|
||||||
|
//@ts-ignore
|
||||||
|
global.setGlobal('console', new this.Console(), { writable: false, configurable: false })
|
||||||
|
process.emit('core.after.load.console')
|
||||||
|
}
|
||||||
|
|
||||||
|
loadPlugins() {
|
||||||
|
process.emit('core.before.load.plugins')
|
||||||
|
let loadPluginStartTime = new Date().getTime()
|
||||||
|
console.i18n("ms.core.plugin.initialize")
|
||||||
|
this.pluginManager.scan(this.pluginFolder)
|
||||||
|
this.pluginManager.build()
|
||||||
|
this.pluginManager.load(this.pluginManager.getPlugins())
|
||||||
|
this.pluginManager.enable(this.pluginManager.getPlugins())
|
||||||
|
console.i18n("ms.core.plugin.completed", { time: (new Date().getTime() - loadPluginStartTime) / 1000 })
|
||||||
|
process.emit('core.after.load.plugins')
|
||||||
|
}
|
||||||
|
|
||||||
|
disable() {
|
||||||
|
process.emit('core.before.disable')
|
||||||
|
let disableStartTime = Date.now()
|
||||||
|
console.i18n("ms.core.engine.disable")
|
||||||
|
this.pluginManager.disable(this.pluginManager.getPlugins())
|
||||||
|
this.taskManager.disable()
|
||||||
|
process.emit('core.after.disable')
|
||||||
|
loadCoreScript('exit')
|
||||||
|
process.emit('core.before.exit')
|
||||||
|
process.exit(0)
|
||||||
|
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')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
function detectServer(): constants.ServerType {
|
||||||
Java.type("org.spongepowered.api.Sponge");
|
try {
|
||||||
require('@ms/sponge');
|
Java.type("org.bukkit.Bukkit")
|
||||||
} catch (ex) {
|
return constants.ServerType.Bukkit
|
||||||
|
} catch (ex: any) {
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Java.type("org.spongepowered.api.Sponge")
|
||||||
|
return constants.ServerType.Sponge
|
||||||
|
} catch (ex: any) {
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Java.type("cn.nukkit.Nukkit")
|
||||||
|
return constants.ServerType.Nukkit
|
||||||
|
} catch (ex: any) {
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Java.type("net.md_5.bungee.api.ProxyServer")
|
||||||
|
return constants.ServerType.Bungee
|
||||||
|
} catch (ex: any) {
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Java.type("org.springframework.boot.SpringApplication")
|
||||||
|
return constants.ServerType.Spring
|
||||||
|
} catch (ex: any) {
|
||||||
|
}
|
||||||
|
throw Error('Unknow Server Type...')
|
||||||
}
|
}
|
||||||
|
|
||||||
let Console = container.get(server.Console);
|
function loadCoreScript(name) {
|
||||||
//@ts-ignore
|
try {
|
||||||
global.console = new Console();
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
container.bind(plugin.PluginManager).to(PluginManagerImpl).inSingletonScope();
|
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
|
||||||
|
}
|
||||||
|
|
||||||
let manager = container.get<plugin.PluginManager>(plugin.PluginManager);
|
function createCore() {
|
||||||
manager.scan('plugins');
|
let corePackageStartTime = new Date().getTime()
|
||||||
manager.load(container);
|
container.bind(ContainerInstance).toConstantValue(container)
|
||||||
manager.enable();
|
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() {
|
||||||
|
process.emit('core.before.initialize')
|
||||||
|
loadMiaoScriptConfig()
|
||||||
|
global.ScriptEngineVersion = require('../package.json').version
|
||||||
|
global.setGlobal('loadCoreScript', loadCoreScript)
|
||||||
|
loadCoreScript('initialize')
|
||||||
|
try {
|
||||||
|
let core = createCore()
|
||||||
|
return VersionUtils.isGreaterOrEqual(base.version, '0.22.0') ? core : core.enable()
|
||||||
|
} catch (error: any) {
|
||||||
|
let core = { enable: () => () => console.i18n('ms.core.engine.disable.abnormal') }
|
||||||
|
console.i18n("core.initialize.error", { error })
|
||||||
|
jsconsole.getStackTrace(error, false).forEach(line => console.log(line))
|
||||||
|
process.emit('core.initialize.error')
|
||||||
|
return VersionUtils.isGreaterOrEqual(base.version, '0.22.0') ? core : core.enable()
|
||||||
|
} finally {
|
||||||
|
process.emit('core.after.initialize')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default initialize()
|
||||||
|
|||||||
33
packages/database/package.json
Normal file
33
packages/database/package.json
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
{
|
||||||
|
"name": "@ccms/database",
|
||||||
|
"version": "0.28.0-beta.7",
|
||||||
|
"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": "^0.28.0-beta.7",
|
||||||
|
"@ccms/container": "^0.28.0-beta.7"
|
||||||
|
}
|
||||||
|
}
|
||||||
3
packages/database/src/constants.ts
Normal file
3
packages/database/src/constants.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export const METADATA_KEY = {
|
||||||
|
|
||||||
|
}
|
||||||
111
packages/database/src/database.ts
Normal file
111
packages/database/src/database.ts
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
12
packages/database/src/index.ts
Normal file
12
packages/database/src/index.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
/// <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'
|
||||||
82
packages/database/src/manager.ts
Normal file
82
packages/database/src/manager.ts
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
7
packages/database/tsconfig.json
Normal file
7
packages/database/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"extends": "../../tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": "src",
|
||||||
|
"outDir": "dist"
|
||||||
|
}
|
||||||
|
}
|
||||||
55
packages/i18n/languages/en.yml
Normal file
55
packages/i18n/languages/en.yml
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
ms.i18n.completed: "Internationalization component initialization completed. Current Language: English"
|
||||||
|
ms.polyfill.initialize: "Initialization Java Nashorn polyfill. Please wait..."
|
||||||
|
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.completed: "MiaoScript IOC Container {scope}/container loading completed({time}s)!"
|
||||||
|
ms.core.initialize.detect: "Detect Compatible Server set ServerType to {type} ..."
|
||||||
|
ms.core.initialize.error: "MiaoScript Engine Initialization Error: {error} ..."
|
||||||
|
ms.core.package.initialize: "Initialization MiaoScript Package {scope}/core {scope}/{type} {scope}/plugin. Please wait..."
|
||||||
|
ms.core.package.completed: "MiaoScript Package {scope}/core {scope}/{type} {scope}/plugin loading completed({time}s)!"
|
||||||
|
ms.core.plugin.initialize: "Initialization MiaoScript Plugin System. Please wait..."
|
||||||
|
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.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.api.event.resource.not.found: "Can't Mapping Event Because not found Resources {resource}!"
|
||||||
|
ms.api.event.empty.event.dir: "base event dir is empty, can't map event name !"
|
||||||
|
ms.api.event.mapping: "Mapping Event [{canonicalName}] => {simpleName}"
|
||||||
|
ms.api.event.not.found: "§6Plugin §b{name} §6register {event} error. event not found!"
|
||||||
|
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.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.unregister: "[{name}] unregister event {event}"
|
||||||
|
|
||||||
|
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.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.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.plugin.initialize: "Initialization MiaoScript Plugin System: Plugin: {plugin} Loader: {loader}..."
|
||||||
|
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: "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.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.error: "§6Plugin §b{plugin} §6exec §d{executor} §6function error §4{error}"
|
||||||
|
ms.plugin.manager.stage.load: "Loading"
|
||||||
|
ms.plugin.manager.stage.enable: "Enabling"
|
||||||
|
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.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.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..."
|
||||||
55
packages/i18n/languages/zh_cn.yml
Normal file
55
packages/i18n/languages/zh_cn.yml
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
ms.i18n.completed: "国际化组件 初始化完成 当前语言: 简体中文"
|
||||||
|
ms.polyfill.initialize: "加载 Java Nashorn 补丁. 请稍候..."
|
||||||
|
ms.polyfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
|
||||||
|
|
||||||
|
ms.core.ioc.initialize: "初始化 MiaoScript IOC 容器 {scope}/container. 请稍候..."
|
||||||
|
ms.core.ioc.completed: "MiaoScript IOC 容器 {scope}/container 加载完成 耗时({time}s)"
|
||||||
|
ms.core.initialize.detect: "检测到兼容的服务器类型. 设置 ServerType 值 {type} ..."
|
||||||
|
ms.core.initialize.error: "§4MiaoScript 系统初始化失败 §c{error} ..."
|
||||||
|
ms.core.package.initialize: "初始化 MiaoScript 扩展 {scope}/core {scope}/{type} {scope}/plugin. 请稍候..."
|
||||||
|
ms.core.package.completed: "MiaoScript 扩展 {scope}/core {scope}/{type} {scope}/plugin 加载完成 耗时({time}s)"
|
||||||
|
ms.core.plugin.initialize: "MiaoScript 开始引导插件系统. 请稍候..."
|
||||||
|
ms.core.plugin.completed: "MiaoScript 插件加载完毕 耗时({time}s)!"
|
||||||
|
ms.core.engine.completed: "MiaoScript 框架 {loader} 引擎 {version} 加载完毕... 耗时({time}s)!"
|
||||||
|
ms.core.engine.disable: "MiaoScript 关闭脚本引擎 请稍候..."
|
||||||
|
ms.core.engine.disable.finish: "MiaoScript 框架 {loader} 引擎 {version} 关闭完成... 耗时({time}s)!"
|
||||||
|
ms.core.engine.disable.abnormal: "引擎异常启动或初始化未完成 跳过关闭流程..."
|
||||||
|
|
||||||
|
ms.api.event.resource.not.found: "无法映射事件 未找到资源文件 {resource}!"
|
||||||
|
ms.api.event.empty.event.dir: "事件基础目录为空, 无法映射事件!"
|
||||||
|
ms.api.event.mapping: "映射事件 [{canonicalName}] => {simpleName}"
|
||||||
|
ms.api.event.not.found: "§6插件 §b{name} §6注册事件 §c{event} §6失败. §4事件未找到!"
|
||||||
|
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.listen.plugin.name.empty: "插件名称为空 请检查传入参数!"
|
||||||
|
ms.api.event.register: "[{name}] 注册事件 {event} => 执行器 {exec} 优先级 {priority} 忽略取消 {ignore}"
|
||||||
|
ms.api.event.unregister: "[{name}] 注销事件 {event} => 执行器 {exec}"
|
||||||
|
|
||||||
|
ms.api.command.register.input.error: "CommandExec 必须为一个函数... 输入: {exec}"
|
||||||
|
ms.api.command.register: "[{plugin}] 注册命令 {name}({cmd})..."
|
||||||
|
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.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.plugin.initialize: "初始化 MiaoScript 插件系统: 实例: {plugin} 加载器: {loader}..."
|
||||||
|
ms.plugin.event.map: "映射 {type} 事件 成功 总计 {count} 个 {type} 事件..."
|
||||||
|
ms.plugin.event.map.error: "映射 {type} 事件 异常 将无法使用事件简称. Error: {error}"
|
||||||
|
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.stage: "{stage} {plugin} 版本 {version} 作者 {author}"
|
||||||
|
ms.plugin.manager.stage.exec: "[{plugin}] 执行 {stage} 阶段函数 {name} 匹配类型 {servers}..."
|
||||||
|
ms.plugin.manager.stage.exec.error: "§6插件 §b{plugin} §6执行 §d{executor} §6函数发生异常 错误: §4{error}"
|
||||||
|
ms.plugin.manager.stage.load: "加载"
|
||||||
|
ms.plugin.manager.stage.enable: "启用"
|
||||||
|
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.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
|
||||||
|
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} 不存在. 从默认值自动创建保存..."
|
||||||
35
packages/i18n/package.json
Normal file
35
packages/i18n/package.json
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"name": "@ccms/i18n",
|
||||||
|
"version": "0.28.0-beta.7",
|
||||||
|
"description": "MiaoScript i18n 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",
|
||||||
|
"languages"
|
||||||
|
],
|
||||||
|
"scripts": {
|
||||||
|
"clean": "rimraf dist",
|
||||||
|
"watch": "tsc --watch",
|
||||||
|
"build": "pnpm clean && tsc",
|
||||||
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@ccms/nashorn": "^0.28.0-beta.7",
|
||||||
|
"@types/js-yaml": "^4.0.5"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"js-yaml": "^4.1.0"
|
||||||
|
},
|
||||||
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
|
}
|
||||||
70
packages/i18n/src/index.ts
Normal file
70
packages/i18n/src/index.ts
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
/// <reference types="@ccms/nashorn" />
|
||||||
|
import * as yaml from 'js-yaml'
|
||||||
|
|
||||||
|
const File = Java.type("java.io.File")
|
||||||
|
const separatorChar = File.separatorChar
|
||||||
|
type TranslateParam = { [key: string]: any }
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Console {
|
||||||
|
i18n(name: string, param?: TranslateParam)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type TranslateContent = {
|
||||||
|
langMap: TranslateParam,
|
||||||
|
fallbackMap?: TranslateParam
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Translate {
|
||||||
|
private root = '';
|
||||||
|
private langMap = {};
|
||||||
|
private fallbackMap = {};
|
||||||
|
|
||||||
|
constructor(root: string | TranslateContent) {
|
||||||
|
if (typeof root == 'string') {
|
||||||
|
this.root = root
|
||||||
|
} else {
|
||||||
|
this.langMap = root.langMap
|
||||||
|
this.fallbackMap = root.fallbackMap || {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
translate(name: string, param?: TranslateParam) {
|
||||||
|
let langText: string = this.langMap[name] || this.fallbackMap[name]
|
||||||
|
if (!langText) { return '[WARN] @ccms/i18n miss lang translate: ' + name }
|
||||||
|
for (const key in param) {
|
||||||
|
langText = langText.replace(new RegExp("{" + key + "}", 'gm'), param[key])
|
||||||
|
}
|
||||||
|
return langText
|
||||||
|
}
|
||||||
|
|
||||||
|
initialize(lang: string = 'zh_cn', fallback: string = 'zh_cn') {
|
||||||
|
this.langMap = this.readYamlFile(this.root, lang) || this.readYamlFile(this.concat(__dirname, '..'), lang)
|
||||||
|
this.fallbackMap = this.readYamlFile(this.root, fallback) || this.readYamlFile(this.concat(__dirname, '..'), fallback)
|
||||||
|
console.i18n = (name: string, param?: TranslateParam) => {
|
||||||
|
console.log(this.translate(name, param))
|
||||||
|
}
|
||||||
|
console.i18n('ms.i18n.completed')
|
||||||
|
}
|
||||||
|
|
||||||
|
readYamlFile(dir: string, name: string) {
|
||||||
|
let langFile = this.concat(dir, 'languages', name + '.yml')
|
||||||
|
return this.exists(langFile) && yaml.load(base.read(langFile))
|
||||||
|
}
|
||||||
|
|
||||||
|
concat(...args: string[]) {
|
||||||
|
return args.join(separatorChar)
|
||||||
|
}
|
||||||
|
|
||||||
|
exists(path: string) {
|
||||||
|
return new File(path).exists()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let systemTranslate = new Translate(root)
|
||||||
|
|
||||||
|
export default {
|
||||||
|
initialize: systemTranslate.initialize.bind(systemTranslate),
|
||||||
|
translate: systemTranslate.translate.bind(systemTranslate)
|
||||||
|
}
|
||||||
7
packages/i18n/tsconfig.json
Normal file
7
packages/i18n/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"extends": "../../tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": "src",
|
||||||
|
"outDir": "dist"
|
||||||
|
}
|
||||||
|
}
|
||||||
6
packages/molang/.gitignore
vendored
Normal file
6
packages/molang/.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
node_modules
|
||||||
|
perf/*
|
||||||
|
|
||||||
|
|
||||||
|
tsconfig.tsbuildinfo
|
||||||
|
.DS_STORE
|
||||||
31
packages/molang/package.json
Normal file
31
packages/molang/package.json
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"name": "@ccms/molang",
|
||||||
|
"version": "0.28.0-beta.7",
|
||||||
|
"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.17.15"
|
||||||
|
}
|
||||||
|
}
|
||||||
129
packages/molang/src/MoLang.ts
Normal file
129
packages/molang/src/MoLang.ts
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user