Compare commits
146 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d50506ab9d | |||
| c34d3027e4 | |||
| edf8410cd1 | |||
| b0b4bbcc2b | |||
| e68689c560 | |||
| 58353cb5b8 | |||
| 8c6b75ff10 | |||
| d53287fc51 | |||
| 13a3611ebd | |||
| 6d90980726 | |||
| 42de3700ba | |||
| 5991662764 | |||
| 1c98c19e37 | |||
| c596280d8d | |||
| 77301e0130 | |||
| 90878fc7df | |||
| a0a4c13e7b | |||
| 0e92a9c795 | |||
| 0c69462bb4 | |||
| 78a5ed31b3 | |||
| f4e9b2627d | |||
| 9dd7abe6fd | |||
| 12743bbbe0 | |||
| d9a2ea9c78 | |||
| c505cda10b | |||
| 100ccbcde3 | |||
| c6575ed481 | |||
| 83359d8cb9 | |||
| cca4979f16 | |||
| 251c9366f5 | |||
| 8f01dcc8e8 | |||
| c25a616dba | |||
| aa9169b043 | |||
| d87e152f3b | |||
| 2fcadeda4e | |||
| b7927830ae | |||
| 2dbd2182c2 | |||
| 01df79eaf1 | |||
| 16fe9ba9bd | |||
| 950ce69b83 | |||
| fa8e44d838 | |||
| b7af785273 | |||
| 6c9f7bbcf6 | |||
| c4c4c7f301 | |||
| 6538c4b7bb | |||
| a4e6d1660d | |||
| 511b042eba | |||
| 6f0b5a5572 | |||
| e9ac46487c | |||
| 9371823d30 | |||
| c86f0d9ec1 | |||
| c2d94ef104 | |||
| 6ada3e41d0 | |||
| 8c12319dc9 | |||
| 395d2d8816 | |||
| 6f628a3d7e | |||
| 2232e82c36 | |||
| 291b5010e7 | |||
| 3595294444 | |||
| e38358ef98 | |||
| 4c418c33c0 | |||
| 65d112be09 | |||
| 15a75dffe2 | |||
| 7b8e693a03 | |||
| 5426023adb | |||
| 73b91c417e | |||
| 2693a22bf0 | |||
| 2322de1e40 | |||
| 2320736a92 | |||
| e8d5d10d44 | |||
| a9996ba297 | |||
| 68380ddbba | |||
| 0baf8f3cab | |||
| a2bce715f3 | |||
| 3c55df03d8 | |||
| f6526e79fc | |||
| f4c2294c06 | |||
| cf9508ba31 | |||
| e0f4c5e77d | |||
| e4a87095ce | |||
| 950575edbc | |||
| c2a71b9a7a | |||
| 068ac7b76e | |||
| 05cbd85828 | |||
| ea28d20aa1 | |||
| d3f33f50e0 | |||
| d004ba17e6 | |||
| 7a25dd8b3b | |||
| dedc8393da | |||
| 8d344492d9 | |||
| 81a76af7be | |||
| b458da7a6e | |||
| 45cb6fa667 | |||
| 9c4543df30 | |||
| 512bdb22c5 | |||
| f6e39c131c | |||
| 73d4dad7f6 | |||
| de4a22362f | |||
| 5fde2e5554 | |||
| 6a6765e5c3 | |||
| 4a1f25ee6a | |||
| 5999567ee3 | |||
| fad4e27a7f | |||
| b477938e4f | |||
| 7cbd91826a | |||
| 6797761a2f | |||
| be114e6d1b | |||
| 3e40934339 | |||
| 3e6c7b2d8c | |||
| 6c0bb75561 | |||
| a47896a97f | |||
| 1d97bbc9ce | |||
| b1f1f9837e | |||
| 99dee28fd4 | |||
| c7f66d8252 | |||
| 8c4f266356 | |||
| 39e899211b | |||
| da72a0dac6 | |||
| 9984787202 | |||
| 4493d35786 | |||
| e1aad59eeb | |||
| 849393492f | |||
| 1ff33702d8 | |||
| e68005fd6f | |||
| 17269b50f4 | |||
| 363d0c164a | |||
| 13a0b62103 | |||
| cb4e152800 | |||
| fb83acfcc8 | |||
| 7263fbb437 | |||
| 23868a58b9 | |||
| effa7f70ec | |||
| eef0baa740 | |||
| 4d0c0122c7 | |||
| aa581afbe5 | |||
| 1425c473fd | |||
| 53e4f6c658 | |||
| 73db4a9169 | |||
| a2efd878db | |||
| 4e6cda0545 | |||
| 859a3a9171 | |||
| 96481032c5 | |||
| f950c3dae8 | |||
| 9248294cb3 | |||
| 53873d7b63 | |||
| be59ae480b |
10
.gitpod.Dockerfile
vendored
10
.gitpod.Dockerfile
vendored
@@ -1,10 +0,0 @@
|
|||||||
FROM gitpod/workspace-full
|
|
||||||
|
|
||||||
USER gitpod
|
|
||||||
|
|
||||||
# Install custom tools, runtime, etc. using apt-get
|
|
||||||
# For example, the command below would install "bastet" - a command line tetris clone:
|
|
||||||
#
|
|
||||||
# RUN sudo apt-get -q update && # sudo apt-get install -yq bastet && # sudo rm -rf /var/lib/apt/lists/*
|
|
||||||
#
|
|
||||||
# More information: https://www.gitpod.io/docs/config-docker/
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
tasks:
|
|
||||||
- init: yarn && yarn bs && yarn build
|
|
||||||
command: yarn watch
|
|
||||||
# image:
|
|
||||||
# file: .gitpod.Dockerfile
|
|
||||||
@@ -20,4 +20,3 @@ wallaby.js
|
|||||||
.vscode
|
.vscode
|
||||||
.theia
|
.theia
|
||||||
type_definitions
|
type_definitions
|
||||||
tsconfig.tsbuildinfo
|
|
||||||
|
|||||||
483
doc/MCBBS.MD
483
doc/MCBBS.MD
@@ -1,11 +1,478 @@
|
|||||||
- 构建状态 [](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/)
|
- 构建状态 [](https://ci.yumc.pw/job/Minecraft/job/MiaoScript/)
|
||||||
- 当前版本 
|
- 当前版本 
|
||||||
- 下载地址 [](http://w.yumc.pw/free.html#MiaoScript-download)
|
- 下载地址 [](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)
|
|
||||||
|
|
||||||
### 腐竹版本(开发中)
|
### 更新日志
|
||||||
|
|
||||||
- 先上几张图
|
- 2020-03-03
|
||||||
|
- 发布 `v0.3.1` 版本
|
||||||
|
- 2020-03-02
|
||||||
|
- 杂项 更新文档以及示例插件
|
||||||
|
- 2020-03-01
|
||||||
|
- 修复 多个包之间的循环依赖问题
|
||||||
|
- 优化 `@ms/types` 的引用逻辑
|
||||||
|
- 2020-02-29
|
||||||
|
- 更新 `TypeScript` 版本为 `3.8.3`
|
||||||
|
- 新增 `@ms/common` 的 `http` 下载功能
|
||||||
|
- 2020-02-27
|
||||||
|
- 发布 `v0.3.0` 版本
|
||||||
|
- 新增 `@ms/i18n` 国际化包的支持
|
||||||
|
- 修复 `@ms/plugin` 对 `servers` 相关处理异常
|
||||||
|
- 优化 `@ms/api` 的 `Channel` 处理增加 扩展原始数据
|
||||||
|
- 2020-02-26
|
||||||
|
- 优化 `@ms/container` 使用 `autoProvide` 自动注入依赖
|
||||||
|
- 2020-02-25
|
||||||
|
- 修复 `@ms/api` 对 `evnet` 的类型处理异常
|
||||||
|
- 2020-02-24
|
||||||
|
- 发布 `v0.2.1` 版本
|
||||||
|
- 完善 对 `Nukkit` 端的支持
|
||||||
|
- 新增 `@ms/api` 通道相关的支持
|
||||||
|
- 2020-02-23
|
||||||
|
- 新增 `@ms/nukkit` 包 对 `Nukkit` 端的支持
|
||||||
|
- 新增 `@ms/type` 的 `nukkit` 类型自动补全
|
||||||
|
- 2020-02-22
|
||||||
|
- 发布 `v0.2.0` 版本
|
||||||
|
- 新增 `@ms/plugin` 的 `@config` 注解 目前支持 `json` `yml` 格式的配置
|
||||||
|
- 2020-02-15
|
||||||
|
- 新增 `SourceMap` 的支持 用于跟踪源代码行数
|
||||||
|
- 2020-02-09
|
||||||
|
- 新增 `core-js` 用于支持大部分新ES语法
|
||||||
|
- 2020-01-31
|
||||||
|
- 优化 `@ms/ployfill` 全局处理
|
||||||
|
- 2020-01-15
|
||||||
|
- 新增 `@ms/bungee` 包 对 `BungeeCord` 端的支持
|
||||||
|
- 2020-01-14
|
||||||
|
- 新增 `@ms/type` 的 `bungee` 类型自动补全
|
||||||
|
- 2019-11-10
|
||||||
|
- 新增 `WebSocket` 的注入支持
|
||||||
|
- 2019-11-07
|
||||||
|
- 新增 `@ms/type` 的 `jdk` 类型自动补全
|
||||||
|
- 2019-09-27
|
||||||
|
- 新增 `CatServer` MOD端的支持
|
||||||
|
- 2019-09-25
|
||||||
|
- 新增 `@ms/type` 的 `sponge` 类型自动补全
|
||||||
|
- 2019-09-24
|
||||||
|
- 新增 `@ms/type` 的 `bukkit` 类型自动补全
|
||||||
|
|
||||||
|
## 插件简介
|
||||||
|
|
||||||
|
- 此插件可以实现跨端使用 `TypeScript` 开发 脚本插件
|
||||||
|
- 目前已经兼容 `Spigot` `Sponge` `Paper` `CatServer` `BungeeCord` `Nukkit`
|
||||||
|
- 后续计划兼容 暂无
|
||||||
|
|
||||||
|
## 起源 (可以略过)
|
||||||
|
|
||||||
|
### 简介
|
||||||
|
|
||||||
|
> 这个坑是我自己刨的 但是发现坑太大 需要更多的人一起填
|
||||||
|
|
||||||
|
### 起源
|
||||||
|
|
||||||
|
- 诞生于 `2016年08月25日` 这是 Git 上的第一个提交 具体啥时候我也忘了
|
||||||
|
- 起初 `MiaoScript` 只是用于服务器其他插件的变量执行 并且依赖于PAPI(不知道是啥的自己百度)
|
||||||
|
- 比如 [`MiaoMenu`](http://w.yumc.pw/zc/MiaoMenu.html) 的部分复杂脚本
|
||||||
|
- 比如 [`MiaoChat`](http://mcbbs.net/thread-631240-1-1.html) 的聊天变量
|
||||||
|
- 突然有一天 圈内的大佬 `QSB` @qiu1995 过来找我 说能不能用脚本监听玩家的事件
|
||||||
|
- PS: 这货自从用过 `DeluxeMenu` 之后就喜欢上了用JS写菜单
|
||||||
|
- 当初感觉没啥问题 就出了第一个简易的 `MiaoScript` 版本 还是用 yml 做的配置文件
|
||||||
|
- 但是由于设计 BukkitAPI 等内容 对Java要求太高 后来 邱也弃坑了 我也弃坑了
|
||||||
|
|
||||||
|
### 刨坑
|
||||||
|
|
||||||
|
- 时隔多年(也就一年) 看到了Sponge的兴起 (估摸着是MCPC系列的MOD端都弃坑了)
|
||||||
|
- 同时 这期间 收到很多腐竹的单子 但是又是非常基础的东西
|
||||||
|
- 比如 开服给玩家发一条消息啦
|
||||||
|
- 比如 修改玩家某些数据啦
|
||||||
|
- 这些东西实际上也就几行代码的事情
|
||||||
|
- 同时 很多想入坑 插件开发 但是又有一些被卡死在环境搭建上
|
||||||
|
- 比如 `Bukkit` 需要 `BukkitAPI`
|
||||||
|
- `Sponge` 需要 `SpongeAPI` 如果涉及 `MOD` 还要 `Forge` 环境
|
||||||
|
- 再或者 BungeeCord 的插件开发 我也是经常懒得搞
|
||||||
|
- 当然 最主要的是 某个 咕咕咕的群 天天有人问我 喵系插件能不能支持 Sponge
|
||||||
|
- 内心当然是拒绝的 现在要上班养老婆孩子(咳咳 不要以为我是大叔 我也才刚毕业而已) 那里还有时间免费给你们写插件
|
||||||
|
- 于是乎 我又想起了当初的 `MiaoScript`
|
||||||
|
- 突发奇想 一个插件的雏形出现在我的脑海中
|
||||||
|
- 可以兼容多种服务器
|
||||||
|
- 不需要开发环境 有记事本就可以开发
|
||||||
|
- 语法要简单 比如 JavaScript
|
||||||
|
- 能够自动搜索安装依赖(毕竟很多人天天问我为何喵系插件跑不起来 都是缺少PAPI)
|
||||||
|
- 能够不重启更新插件(当然得保证代码安全的前提下)
|
||||||
|
- 在 2017年9月14号(距离 第一个版本正式版发布(2016-09-21) 相差一年整)
|
||||||
|
- 一个全新的 `MiaoScript` 诞生了
|
||||||
|
- Java部分代码 只有一个启动类
|
||||||
|
- 核心全部由 JS 编写
|
||||||
|
- 兼容 `CommonJS` 规范
|
||||||
|
- 实时重载
|
||||||
|
- 2019年9月14号 emm 咸鱼2年之后
|
||||||
|
- TypeScript 重构版本横空出世
|
||||||
|
- 只保留 基础Java启动类 三个环境初始化js
|
||||||
|
- 完整的服务端Java类自动补全
|
||||||
|
- 全新的 IOC容器 注入功能
|
||||||
|
- 注解式 注册命令 注册事件
|
||||||
|
- 2020年3月2日 发布0.3.0版本
|
||||||
|
- 支持 Bukkit Nukkit BungeeCord Sponge
|
||||||
|
|
||||||
|
### 进展
|
||||||
|
|
||||||
|
- [项目发布](https://git.yumc.pw/502647092/MiaoScript/releases)
|
||||||
|
- [项目代码](https://git.yumc.pw/502647092/MiaoScript)
|
||||||
|
- [项目脑图](http://naotu.baidu.com/file/293b9a0fc7cef23c69de81c55e3617d5?token=1eee8fd759198eb7)
|
||||||
|
|
||||||
|
### 规划
|
||||||
|
|
||||||
|
- 初期只会支持JS类型的插件开发
|
||||||
|
- 二期会出一个建议版本的MS脚本 可以用简单的语法实现简单的功能
|
||||||
|
- 各个层级会有依赖控制 比如 `MS脚本 => JS脚本 => 调用Java原生API`
|
||||||
|
|
||||||
|
## 框架设计
|
||||||
|
|
||||||
|
### MiaoScript TS 实现
|
||||||
|
|
||||||
|
项目具体实现 由 TypeScript 进行编写 然后编译至 `es5` 用于兼容 Java8 的 `Nashorn`
|
||||||
|
|
||||||
|
### Project Structure
|
||||||
|
|
||||||
|
```txt
|
||||||
|
└─packages
|
||||||
|
├─api 全平台兼容的接口
|
||||||
|
├─core 核心代码 用于引导加载
|
||||||
|
├─common 公共类库代码 例如 http reflect 模块
|
||||||
|
├─client NodeJS的Minecraft客户端 用于调试插件
|
||||||
|
├─container IOC容器 用于注入具体实现
|
||||||
|
├─ployfill Nashorn 的一些自定义增强
|
||||||
|
├─nashorn Nashorn 的类型定义
|
||||||
|
├─bungee BungeeCordAPI内部实现
|
||||||
|
├─bukkit BukkitAPI内部实现
|
||||||
|
├─sponge SpongeAPI内部实现
|
||||||
|
├─nukkit NukkitAPI内部实现
|
||||||
|
├─ployfill JS环境的相关环境补全
|
||||||
|
├─plugin 插件管理器
|
||||||
|
├─websocket Netty的WebSocket注入
|
||||||
|
├─type Java的类型定义
|
||||||
|
| ├─bungee BungeeCord类型定义
|
||||||
|
| ├─bukkit Bukkit类型定义
|
||||||
|
| ├─sponge Sponge类型定义
|
||||||
|
| └─nukkit Nukkit类型定义
|
||||||
|
└─plugins 这里当然是插件啦
|
||||||
|
├─bungee 只兼容BungeeCord的插件
|
||||||
|
├─bukkit 只兼容Bukkit的插件
|
||||||
|
├─sponge 只兼容Sponge的插件
|
||||||
|
└─nukkit 只兼容Nukkit的插件
|
||||||
|
```
|
||||||
|
|
||||||
|
详细的内容就不逼逼了 自己看代码吧
|
||||||
|
|
||||||
|
Github: https://github.com/circlecloud/ms
|
||||||
|
YUMC: https://git.yumc.pw/circlecloud/ms
|
||||||
|
|
||||||
|
## 插件开发基础
|
||||||
|
|
||||||
|
### 开发IDE (推荐VSCode或者MiaoScrit在线IDE)
|
||||||
|
|
||||||
|
如果只是简单的开发 你可用记事本 (但是没有任何补全和错误提示)
|
||||||
|
|
||||||
|
### 开发环境准备(针对高级用户)
|
||||||
|
|
||||||
|
- 安装 `NodeJS` 和 `Yarn`
|
||||||
|
- 拉取代码
|
||||||
|
- `git clone https://github.com/circlecloud/ms.git`
|
||||||
|
- 进入目录 `ms`
|
||||||
|
- 安装 npm 包
|
||||||
|
- `yarn`
|
||||||
|
- 建立内部依赖链接
|
||||||
|
- `yarn bs`
|
||||||
|
- 编译一次生成对应的类库
|
||||||
|
- `yarn build`
|
||||||
|
- 编译插件
|
||||||
|
- `yarn build:plugins`
|
||||||
|
|
||||||
|
### 直接在 MiaoScript Online WebIDE 开发
|
||||||
|
|
||||||
|
填坑中...
|
||||||
|
|
||||||
|
## 基本插件框架
|
||||||
|
|
||||||
|
### HelloWorld 示例插件
|
||||||
|
|
||||||
|
先来一个 `HelloWorld.ts` 插件示范!
|
||||||
|
|
||||||
|
```ts
|
||||||
|
/// <reference types="@ms/types" />
|
||||||
|
|
||||||
|
import { server } from '@ms/api';
|
||||||
|
import { inject } from '@ms/container';
|
||||||
|
import { plugin, interfaces, cmd, listener, tab } from '@ms/plugin'
|
||||||
|
|
||||||
|
@plugin({ name: 'HelloWorld', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
|
export class HelloWorld extends interfaces.Plugin {
|
||||||
|
@inject(server.Server)
|
||||||
|
private Server: server.Server
|
||||||
|
@config()
|
||||||
|
private config = {
|
||||||
|
version: 1.0.0
|
||||||
|
}
|
||||||
|
|
||||||
|
load() {
|
||||||
|
this.logger.log('Plugin load from MiaoScript Plugin System...');
|
||||||
|
}
|
||||||
|
enable() {
|
||||||
|
this.logger.log('Plugin enable from MiaoScript Plugin System...');
|
||||||
|
}
|
||||||
|
disable() {
|
||||||
|
this.logger.log('Plugin disable from MiaoScript Plugin System...');
|
||||||
|
}
|
||||||
|
|
||||||
|
bukkitload() {
|
||||||
|
this.logger.log('Load When ServerType is Bukkit!')
|
||||||
|
}
|
||||||
|
bukkitenable() {
|
||||||
|
this.logger.log('Enable When ServerType is Bukkit!')
|
||||||
|
}
|
||||||
|
bukkitdisable() {
|
||||||
|
this.logger.log('Disable When ServerType is Bukkit!')
|
||||||
|
}
|
||||||
|
|
||||||
|
spongeload() {
|
||||||
|
this.logger.log('Load When ServerType is Sponge!')
|
||||||
|
}
|
||||||
|
spongeenable() {
|
||||||
|
this.logger.log('Enable When ServerType is Sponge!')
|
||||||
|
}
|
||||||
|
spongedisable() {
|
||||||
|
this.logger.log('Disable When ServerType is Sponge!')
|
||||||
|
}
|
||||||
|
|
||||||
|
bungeeload() {
|
||||||
|
this.logger.log('Load When ServerType is BungeeCord!')
|
||||||
|
}
|
||||||
|
bungeeenable() {
|
||||||
|
this.logger.log('Enable When ServerType is BungeeCord!')
|
||||||
|
}
|
||||||
|
bungeedisable() {
|
||||||
|
this.logger.log('Disable When ServerType is BungeeCord!')
|
||||||
|
}
|
||||||
|
|
||||||
|
nukkitload() {
|
||||||
|
this.logger.log('Load When ServerType is Nukkit!')
|
||||||
|
}
|
||||||
|
nukkitenable() {
|
||||||
|
this.logger.log('Enable When ServerType is Nukkit!')
|
||||||
|
}
|
||||||
|
nukkitdisable() {
|
||||||
|
this.logger.log('Disable When ServerType is Nukkit!')
|
||||||
|
}
|
||||||
|
|
||||||
|
@cmd()
|
||||||
|
hello(sender: any, command: string, args: string[]) {
|
||||||
|
this.logger.log(sender, command, args);
|
||||||
|
sender.sendMessage(JSON.stringify({ command, ...args }))
|
||||||
|
}
|
||||||
|
|
||||||
|
@tab()
|
||||||
|
tabhello(_sender: any, _command: string, _args: string[]) {
|
||||||
|
return ['world']
|
||||||
|
}
|
||||||
|
|
||||||
|
// bukkit nukkit 大部分API神似 可以直接用
|
||||||
|
@listener({ servers: ['bukkit', 'nukkit'] })
|
||||||
|
PlayerJoin(event: org.bukkit.event.player.PlayerJoinEvent) {
|
||||||
|
let plyaer = event.getPlayer();
|
||||||
|
this.logger.console(`§cBukkit §aPlayerJoinEvent: §b${plyaer.getName()}`)
|
||||||
|
setTimeout(() => this.sendWelcome(plyaer), 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
@listener({ servers: ['sponge'] })
|
||||||
|
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
|
||||||
|
this.logger.console(`§cSponge §aClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
|
||||||
|
setTimeout(() => this.sendWelcome(event.getTargetEntity()), 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendWelcome(player: any) {
|
||||||
|
this.logger.sender(player, `§a欢迎来到 §bMiaoScript §a的世界!`)
|
||||||
|
this.logger.sender(player, `§6当前版本: §c${this.Server.getVersion()}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
@listener({ servers: ['bungee'] })
|
||||||
|
ServerConnected(e: any) {
|
||||||
|
let event = e as net.md_5.bungee.api.event.ServerConnectedEvent
|
||||||
|
this.logger.console(`§cBungeeCord §aServerConnectedEvent: §b${event.getPlayer().getDisplayName()}`)
|
||||||
|
setTimeout(() => this.logger.sender(event.getPlayer(), `§a欢迎来到 §bMiaoScript §a的世界 §6来自 §cBungeeCord §6的问候!`), 10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- 进入 `ms`目录
|
||||||
|
- 执行编译 `yarn build:plugins`
|
||||||
|
- 从 `packages/plugins/dist` 中复制 `HelloWorld.js` 和 `HelloWorld.js.map`(可选 用于显示插件原有行数) 文件 到对应的插件目录
|
||||||
|
- Bungee: plugins/MiaoScript/plugins/
|
||||||
|
- Bukkit: plugins/MiaoScript/plugins/
|
||||||
|
- Sponge: config/miaoscript/plugins/
|
||||||
|
- Nukkit: plugins/MiaoScript/plugins/
|
||||||
|
- 重载 `MiaoScript`
|
||||||
|
- 打开客户端进入游戏 预览一下效果
|
||||||
|
- 从 Spigot 服务端进入
|
||||||
|

|
||||||
|

|
||||||
|
- 从 Sponge 服务端进入
|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
|
## 注册插件
|
||||||
|
|
||||||
|
- 从上面的示例可以看到 一个插件 通过注解 `@plugin` 即可启动
|
||||||
|
- 此注解接受一个 `PluginMetadata` 对象 定义如下
|
||||||
|
```ts
|
||||||
|
export interface PluginMetadata {
|
||||||
|
/**
|
||||||
|
* 插件名称
|
||||||
|
*/
|
||||||
|
name: string;
|
||||||
|
/**
|
||||||
|
* 支持的服务器列表 为空则代表所有
|
||||||
|
*/
|
||||||
|
servers?: string[];
|
||||||
|
/**
|
||||||
|
* 前缀
|
||||||
|
*/
|
||||||
|
prefix?: string;
|
||||||
|
/**
|
||||||
|
* 插件版本
|
||||||
|
*/
|
||||||
|
version: string;
|
||||||
|
/**
|
||||||
|
* 插件版本
|
||||||
|
*/
|
||||||
|
author: string | string[];
|
||||||
|
/**
|
||||||
|
* 插件源文件 必须指定为 __filename
|
||||||
|
*/
|
||||||
|
source: string;
|
||||||
|
/**
|
||||||
|
* 插件本体
|
||||||
|
*/
|
||||||
|
target?: any;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 插件生命周期
|
||||||
|
|
||||||
|
MiaoScript 的生命周期遵循了 Bukkit 的生命周期
|
||||||
|
|
||||||
|
MiaoScript 针对不同的服务端 提供了扩展的周期
|
||||||
|
以服务端类型开头阶段名结束 例如 `bukkitload` `spongeenbale` `bungeedisable`
|
||||||
|
扩展的生命周期只会在特定的服务器执行
|
||||||
|
|
||||||
|
### load 加载阶段
|
||||||
|
|
||||||
|
此阶段通常用于初始化基础配置 数据库链接等
|
||||||
|
某些对外提供功能的插件 需要在此阶段初始化完成
|
||||||
|
|
||||||
|
### enable 启动阶段
|
||||||
|
|
||||||
|
此阶段通常用于注册命令 注册事件等
|
||||||
|
由于命令和事件 MiaoScript 已经托管了 所以开发者可以直接用注解实现
|
||||||
|
|
||||||
|
### disable 关闭阶段
|
||||||
|
|
||||||
|
此阶段通常用于注销命令 注销事件等
|
||||||
|
由于命令和事件 MiaoScript 已经托管了 所以开发者可以直接用注解实现
|
||||||
|
|
||||||
|
## 注册命令/补全
|
||||||
|
|
||||||
|
### cmd 命令
|
||||||
|
|
||||||
|
命令 就是玩家在Minecraft中执行命令 下面是一个示例的命令
|
||||||
|
|
||||||
|
- 命令是一个 `function` 通过 `@cmd` 注解注册
|
||||||
|
- 由于不同的服务端有不同的逻辑 所以支持通过 `servers` 指定注册的类型 加上 `!` 代表不注册 不指定 `servers` 则注册所有的类型
|
||||||
|
- 命令注册时默认使用方法名称为命令名称 当前你可以传入 name 参数指定命令名称 例如 `{name: 'test'}`
|
||||||
|
- 接受三个参数 `sender: any, command: string, args: string[]`
|
||||||
|
- 分别代表 命令发送者 命令名称 命令参数
|
||||||
|
|
||||||
|
```ts
|
||||||
|
@cmd({ servers: ["bukkit", "sponge", "!bungee"] })
|
||||||
|
hello(sender: any, command: string, args: string[]) {
|
||||||
|
this.logger.log(sender, command, args);
|
||||||
|
this.logger.sender(sender, JSON.stringify({ command, args }));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### tab 补全
|
||||||
|
|
||||||
|
补全就是 玩家在Minecraft执行命令时 使用 Tab键 补全
|
||||||
|
|
||||||
|
- 补全是一个 `function` 一般以 `tab` 开头 需要补全的命令结尾 通过 `@tab` 注解注册
|
||||||
|
- 补全注册时默认使用方法名称为补全名称 当前你可以传入 name 参数指定命令名称 例如 `{name: 'test'}`
|
||||||
|
- 接受三个参数 `sender: any, command: string, args: string[]`
|
||||||
|
- 分别代表 命令发送者 命令名称 命令参数
|
||||||
|
|
||||||
|
_注意: 当补全命令未注册时 补全无效! 且补全和命令必须在同一个Class内!_
|
||||||
|
|
||||||
|
```ts
|
||||||
|
@tab()
|
||||||
|
tabhello(_sender: any, _command: string, _args: string[]) {
|
||||||
|
return ['world']
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 监听事件
|
||||||
|
|
||||||
|
事件是指 Minecraft 中发生的各种事情
|
||||||
|
|
||||||
|
- 监听事件是一个 `function` 通过 `@listener` 注册
|
||||||
|
- 由于不同的服务端有不同的逻辑 所以支持通过 `servers` 指定注册的类型 加上 `!` 代表不注册 不指定 `servers` 则注册所有的类型
|
||||||
|
- 事件名称默认为方法名称
|
||||||
|
- 所有类型服务端的事件 MiaoScript 都会进行一次映射 方便使用
|
||||||
|
- 例如 `PlayerJoinEvent` 会映射为 `PlayerJoinEvent, playerjoinevent, playerjoin` 等
|
||||||
|
- 一般规则就是 类名直接小写 如果遇到子类 则保留 `$`
|
||||||
|
- 例如 `ClientConnectionEvent.Join` 会映射为 `clientconnectionevent$join`
|
||||||
|
- 事件的注可以传入 `servertype` 来指定这个事件类型的服务端加载 默认是所有服务端都加载
|
||||||
|
- 事件监听方法的第一个参数就是本次事件的具体内容 (这里就需要自己去查询对应的JavaDoc了)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// bukkit nukkit 大部分API神似 可以直接用
|
||||||
|
@listener({ servers: ['bukkit', 'nukkit'] })
|
||||||
|
PlayerJoin(event: org.bukkit.event.player.PlayerJoinEvent) {
|
||||||
|
let plyaer = event.getPlayer();
|
||||||
|
this.logger.console(`§cBukkit §aPlayerJoinEvent: §b${plyaer.getName()}`)
|
||||||
|
setTimeout(() => this.sendWelcome(plyaer), 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
@listener({ servers: ['sponge'] })
|
||||||
|
ClientConnectionEvent$Join(event: org.spongepowered.api.event.network.ClientConnectionEvent.Join) {
|
||||||
|
this.logger.console(`§cSponge §aClientConnectionEvent.Join: §b${event.getTargetEntity().getName()}`)
|
||||||
|
setTimeout(() => this.sendWelcome(event.getTargetEntity()), 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendWelcome(player: any) {
|
||||||
|
this.logger.sender(player, `§a欢迎来到 §bMiaoScript §a的世界!`)
|
||||||
|
this.logger.sender(player, `§6当前版本: §c${this.Server.getVersion()}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
@listener({ servers: ['bungee'] })
|
||||||
|
ServerConnected(e: any) {
|
||||||
|
let event = e as net.md_5.bungee.api.event.ServerConnectedEvent
|
||||||
|
this.logger.console(`§cBungeeCord §aServerConnectedEvent: §b${event.getPlayer().getDisplayName()}`)
|
||||||
|
setTimeout(() => this.logger.sender(event.getPlayer(), `§a欢迎来到 §bMiaoScript §a的世界 §6来自 §cBungeeCord §6的问候!`), 10);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 配置文件
|
||||||
|
|
||||||
|
配置文件 默认读取的是 `MiaoScript根目录/plugins/插件名称/配置名称.配置格式`
|
||||||
|
|
||||||
|
例如下面文件 默认处理的是 `plugins/MiaoScript/plugins/HelloWorld/config.yml`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
@config()
|
||||||
|
private config = {
|
||||||
|
version: 1.0.0
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 插件列表
|
||||||
|
|
||||||
|
暂无
|
||||||
|
|
||||||
|
> 注意: 一楼的列表是老版本的 新版本无法加载!
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"useWorkspaces": true,
|
"useWorkspaces": true,
|
||||||
"npmClient": "yarn",
|
"npmClient": "yarn",
|
||||||
"packages": [
|
"packages": [
|
||||||
|
|||||||
@@ -11,15 +11,14 @@
|
|||||||
"watch": "lerna run watch --parallel",
|
"watch": "lerna run watch --parallel",
|
||||||
"build": "lerna run build --scope=\"@ccms/!(plugins)\"",
|
"build": "lerna run build --scope=\"@ccms/!(plugins)\"",
|
||||||
"build:plugins": "lerna run build --scope=\"@ccms/plugins\"",
|
"build:plugins": "lerna run build --scope=\"@ccms/plugins\"",
|
||||||
|
"publish": "yarn lerna exec \"npm publish --access=public\" --scope=\"@ccms/!(plugins|client|types)\"",
|
||||||
"ug": "yarn upgrade-interactive --latest",
|
"ug": "yarn upgrade-interactive --latest",
|
||||||
"np": "lerna exec \"npm publish --registry https://registry.npmjs.org\" --scope=\"@ccms/!(client|plugins)\"",
|
|
||||||
"lsp": "npm login --registry=https://registry.npmjs.org --scope=@ccms",
|
|
||||||
"lp": "lerna publish"
|
"lp": "lerna publish"
|
||||||
},
|
},
|
||||||
"workspaces": [
|
"workspaces": [
|
||||||
"packages/*"
|
"packages/*"
|
||||||
],
|
],
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"lerna": "^3.21.0"
|
"lerna": "^3.20.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "@ccms/amqp",
|
|
||||||
"version": "0.7.0",
|
|
||||||
"description": "MiaoScript amqp package",
|
|
||||||
"keywords": [
|
|
||||||
"miaoscript",
|
|
||||||
"minecraft",
|
|
||||||
"bukkit",
|
|
||||||
"sponge"
|
|
||||||
],
|
|
||||||
"author": "MiaoWoo <admin@yumc.pw>",
|
|
||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
|
||||||
"license": "ISC",
|
|
||||||
"main": "dist/index.js",
|
|
||||||
"scripts": {
|
|
||||||
"clean": "rimraf dist",
|
|
||||||
"watch": "tsc --watch",
|
|
||||||
"build": "yarn clean && tsc",
|
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@ccms/api": "^0.7.0",
|
|
||||||
"@ccms/nashorn": "^0.7.0",
|
|
||||||
"@ccms/common": "^0.7.0",
|
|
||||||
"@ccms/container": "^0.7.0"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"reflect-metadata": "^0.1.13",
|
|
||||||
"rimraf": "^3.0.2",
|
|
||||||
"typescript": "^3.9.2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { ConnectionFactoryAdapter } from "./connection"
|
|
||||||
import { RabbitTemplateAdapter } from "./template"
|
|
||||||
|
|
||||||
export const RabbitAdmin = Java.type('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
|
||||||
|
|
||||||
export class RabbitAdminAdapter {
|
|
||||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitAdmin
|
|
||||||
constructor(config: RabbitTemplateAdapter | org.springframework.amqp.rabbit.core.RabbitTemplate | ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory) {
|
|
||||||
this._Handler = new RabbitAdmin((config instanceof RabbitTemplateAdapter || config instanceof ConnectionFactoryAdapter) ? config.getHandler() : config)
|
|
||||||
}
|
|
||||||
getHandler(): org.springframework.amqp.rabbit.core.RabbitAdmin {
|
|
||||||
return this._Handler
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
export const ConfirmCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback')
|
|
||||||
export const ReturnCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback')
|
|
||||||
|
|
||||||
export abstract class ConfirmCallbackAdapter {
|
|
||||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback
|
|
||||||
constructor() {
|
|
||||||
let ConfirmCallbackImpl = Java.extend(ReturnCallback, {
|
|
||||||
confirm: (correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string) => this.confirm(correlationData, ack, cause)
|
|
||||||
})
|
|
||||||
this._Handler = new ConfirmCallbackImpl()
|
|
||||||
}
|
|
||||||
abstract confirm(correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string)
|
|
||||||
getHandler() {
|
|
||||||
return this._Handler
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export abstract class ReturnCallbackAdapter {
|
|
||||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback
|
|
||||||
constructor() {
|
|
||||||
let ReturnCallbackImpl = Java.extend(ReturnCallback, {
|
|
||||||
returnedMessage: (message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string) => this.returnedMessage(message, replyCode, replyText, exchange, routingKey)
|
|
||||||
})
|
|
||||||
this._Handler = new ReturnCallbackImpl()
|
|
||||||
}
|
|
||||||
abstract returnedMessage(message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string)
|
|
||||||
getHandler() {
|
|
||||||
return this._Handler
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import threadPool from '@ccms/common/dist/thread-pool'
|
|
||||||
|
|
||||||
export const ConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.ConnectionFactory')
|
|
||||||
const CachingConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.CachingConnectionFactory')
|
|
||||||
interface ConnectionConfig {
|
|
||||||
url: string,
|
|
||||||
username?: string,
|
|
||||||
password?: string,
|
|
||||||
publisherConfirms?: boolean
|
|
||||||
cacheSize?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ConnectionFactoryAdapter {
|
|
||||||
private _Handler: org.springframework.amqp.rabbit.connection.CachingConnectionFactory
|
|
||||||
|
|
||||||
constructor(config: ConnectionConfig) {
|
|
||||||
if (!config.url) { throw new Error('Connection UrI Can\'t be undefiend!') }
|
|
||||||
config = { publisherConfirms: true, cacheSize: 50, ...config }
|
|
||||||
this._Handler = new CachingConnectionFactory(new java.net.URI(config.url))
|
|
||||||
config.username && this._Handler.setUsername(config.username)
|
|
||||||
config.password && this._Handler.setPassword(config.password)
|
|
||||||
this._Handler.setPublisherConfirms(config.publisherConfirms)
|
|
||||||
this._Handler.setExecutor(threadPool.create({
|
|
||||||
groupName: '@ccms/amqp-rabbit'
|
|
||||||
}))
|
|
||||||
this._Handler.setChannelCacheSize(config.cacheSize)
|
|
||||||
}
|
|
||||||
getHandler() {
|
|
||||||
return this._Handler
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
import { ConnectionFactoryAdapter, ConnectionFactory } from "./connection"
|
|
||||||
import { ChannelAwareMessageListenerAdapter, ChannelAwareMessageListener } from "./listener"
|
|
||||||
|
|
||||||
export const SimpleMessageListenerContainer = org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
|
||||||
export const AcknowledgeMode = org.springframework.amqp.core.AcknowledgeMode
|
|
||||||
interface ContainerConfig {
|
|
||||||
connectionFactory: ConnectionFactoryAdapter | typeof ConnectionFactory
|
|
||||||
queueNames: string[]
|
|
||||||
messageListener: ChannelAwareMessageListenerAdapter | typeof ChannelAwareMessageListener
|
|
||||||
maxConcurrentConsumers?: number
|
|
||||||
concurrentConsumers?: number
|
|
||||||
acknowledgeMode?: org.springframework.amqp.core.AcknowledgeMode
|
|
||||||
}
|
|
||||||
|
|
||||||
export class MessageListenerContainerAdapter {
|
|
||||||
private _Handler: org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
|
||||||
constructor(config: ContainerConfig) {
|
|
||||||
config = { concurrentConsumers: 5, maxConcurrentConsumers: 10, acknowledgeMode: AcknowledgeMode.AUTO, ...config }
|
|
||||||
this._Handler = new SimpleMessageListenerContainer(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
|
|
||||||
//@ts-ignore
|
|
||||||
this._Handler.setQueueNames(config.queueNames)
|
|
||||||
this._Handler.setMaxConcurrentConsumers(config.maxConcurrentConsumers)
|
|
||||||
this._Handler.setConcurrentConsumers(config.concurrentConsumers)
|
|
||||||
this._Handler.setAcknowledgeMode(config.acknowledgeMode)
|
|
||||||
this._Handler.setMessageListener(config.messageListener instanceof ChannelAwareMessageListenerAdapter ? config.messageListener.getHandler() : config.messageListener)
|
|
||||||
}
|
|
||||||
getHandler() {
|
|
||||||
return this._Handler
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
const JavaString = Java.type('java.lang.String')
|
|
||||||
const MessageProperties = org.springframework.amqp.core.MessageProperties
|
|
||||||
const Message = org.springframework.amqp.core.Message
|
|
||||||
|
|
||||||
export const MessageConverter = Java.type('org.springframework.amqp.support.converter.MessageConverter')
|
|
||||||
|
|
||||||
export class MessageConverterAdapter {
|
|
||||||
private _Handler: org.springframework.amqp.support.converter.MessageConverter
|
|
||||||
constructor() {
|
|
||||||
var MessageConverterImpl = Java.extend(MessageConverter, {
|
|
||||||
toMessage: (object: any, messageProperties: org.springframework.amqp.core.MessageProperties) => this.toMessage(object, messageProperties),
|
|
||||||
fromMessage: (message: org.springframework.amqp.core.Message) => this.fromMessage(message)
|
|
||||||
})
|
|
||||||
this._Handler = new MessageConverterImpl()
|
|
||||||
}
|
|
||||||
toMessage(object: any, messageProperties: org.springframework.amqp.core.MessageProperties) {
|
|
||||||
if (typeof object == "string") {
|
|
||||||
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
|
|
||||||
return new Message(new JavaString(object).getBytes(), messageProperties)
|
|
||||||
} else {
|
|
||||||
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
|
||||||
return new Message(new JavaString(JSON.stringify(object)).getBytes(), messageProperties)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fromMessage(message: org.springframework.amqp.core.Message) {
|
|
||||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_TEXT_PLAIN) {
|
|
||||||
return new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding())
|
|
||||||
}
|
|
||||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
|
||||||
return JSON.parse(new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding()))
|
|
||||||
}
|
|
||||||
return message
|
|
||||||
}
|
|
||||||
getHandler() {
|
|
||||||
return this._Handler
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
export * from './admin'
|
|
||||||
export * from './callback'
|
|
||||||
export * from './connection'
|
|
||||||
export * from './container'
|
|
||||||
export * from './converter'
|
|
||||||
export * from './listener'
|
|
||||||
export * from './template'
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
const JavaString = Java.type('java.lang.String')
|
|
||||||
export const MessageProperties = org.springframework.amqp.core.MessageProperties
|
|
||||||
export const ChannelAwareMessageListener = Java.type('org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener')
|
|
||||||
export const AmqpRejectAndDontRequeueException = org.springframework.amqp.AmqpRejectAndDontRequeueException
|
|
||||||
export const Channel: com.rabbitmq.client.Channel = Java.type('com.rabbitmq.client.Channel')
|
|
||||||
export const Message = org.springframework.amqp.core.Message
|
|
||||||
export type MessageHandler<T> = (content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => any
|
|
||||||
export abstract class ChannelAwareMessageListenerAdapter<T = any> {
|
|
||||||
private _Handler: org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener
|
|
||||||
constructor(manual: boolean = false) {
|
|
||||||
let ChannelAwareMessageListenerImpl = Java.extend(ChannelAwareMessageListener, {
|
|
||||||
onMessage: (message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => {
|
|
||||||
let content = new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding() || "UTF-8")
|
|
||||||
try {
|
|
||||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
|
||||||
content = JSON.parse(content)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
if (manual) {
|
|
||||||
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true)
|
|
||||||
} else {
|
|
||||||
throw new AmqpRejectAndDontRequeueException(`${error}`, error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
manual ? this.manualOnMessage(content, message, channel) : this.onMessage(content, message, channel)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
this._Handler = new ChannelAwareMessageListenerImpl()
|
|
||||||
}
|
|
||||||
abstract onMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any
|
|
||||||
onError(error: Error, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any { }
|
|
||||||
getHandler() {
|
|
||||||
return this._Handler
|
|
||||||
}
|
|
||||||
private manualOnMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
|
|
||||||
let deliveryTag = message.getMessageProperties().getDeliveryTag()
|
|
||||||
try {
|
|
||||||
if (this.onMessage(content, message, channel)) {
|
|
||||||
channel.basicAck(deliveryTag, false)
|
|
||||||
} else if (message.getMessageProperties().getRedelivered()) {
|
|
||||||
channel.basicReject(deliveryTag, true)
|
|
||||||
} else {
|
|
||||||
channel.basicNack(deliveryTag, false, true)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
channel.basicReject(deliveryTag, this.onError(error, message, channel))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
import { MessageConverterAdapter } from "./converter"
|
|
||||||
import { ConnectionFactoryAdapter } from "./connection"
|
|
||||||
import { ConfirmCallbackAdapter, ReturnCallbackAdapter } from "./callback"
|
|
||||||
|
|
||||||
export const RabbitTemplate = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate')
|
|
||||||
|
|
||||||
interface TemplateConfig {
|
|
||||||
connectionFactory: ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory
|
|
||||||
confirmCallback?: ConfirmCallbackAdapter
|
|
||||||
returnCallback?: ReturnCallbackAdapter
|
|
||||||
messageConverter?: MessageConverterAdapter
|
|
||||||
}
|
|
||||||
export class RabbitTemplateAdapter {
|
|
||||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate
|
|
||||||
constructor(config: TemplateConfig) {
|
|
||||||
config = { messageConverter: new MessageConverterAdapter(), ...config }
|
|
||||||
console.debug(JSON.stringify(config))
|
|
||||||
this._Handler = new RabbitTemplate(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
|
|
||||||
config.returnCallback && this._Handler.setReturnCallback(config.returnCallback.getHandler())
|
|
||||||
config.confirmCallback && this._Handler.setConfirmCallback(config.confirmCallback.getHandler())
|
|
||||||
config.messageConverter && this._Handler.setMessageConverter(config.messageConverter.getHandler())
|
|
||||||
}
|
|
||||||
|
|
||||||
getHandler() {
|
|
||||||
return this._Handler
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
import { JSClass } from "@ccms/container"
|
|
||||||
import { RabbitAdminAdapter, MessageListenerContainerAdapter, AcknowledgeMode, MessageHandler, ChannelAwareMessageListenerAdapter } from "./adapter"
|
|
||||||
|
|
||||||
const RabbitAdmin = Java.type('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
|
||||||
|
|
||||||
export class AmqpAdmin {
|
|
||||||
@JSClass('org.springframework.amqp.core.TopicExchange')
|
|
||||||
private TopicExchange: typeof org.springframework.amqp.core.TopicExchange
|
|
||||||
@JSClass('org.springframework.amqp.core.Queue')
|
|
||||||
private Queue: typeof org.springframework.amqp.core.Queue
|
|
||||||
@JSClass('org.springframework.amqp.core.Binding')
|
|
||||||
private Binding: typeof org.springframework.amqp.core.Binding
|
|
||||||
|
|
||||||
@JSClass('org.springframework.amqp.core.Binding.DestinationType')
|
|
||||||
private DestinationType: typeof org.springframework.amqp.core.Binding.DestinationType
|
|
||||||
|
|
||||||
private amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
|
|
||||||
|
|
||||||
constructor(amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin | any) {
|
|
||||||
if (amqpAdmin instanceof RabbitAdmin) {
|
|
||||||
this.amqpAdmin = amqpAdmin
|
|
||||||
} else if (amqpAdmin instanceof RabbitAdminAdapter) {
|
|
||||||
this.amqpAdmin = amqpAdmin.getHandler()
|
|
||||||
} else {
|
|
||||||
this.amqpAdmin = new RabbitAdminAdapter(amqpAdmin).getHandler()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
getHandler() {
|
|
||||||
return this.amqpAdmin
|
|
||||||
}
|
|
||||||
|
|
||||||
getQueueProperties(name: string) {
|
|
||||||
return this.amqpAdmin.getQueueProperties(name)
|
|
||||||
}
|
|
||||||
|
|
||||||
declareExchange(name: string) {
|
|
||||||
let exchange = new this.TopicExchange(name, true, false)
|
|
||||||
this.amqpAdmin.declareExchange(exchange)
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
declareQueue(name: string) {
|
|
||||||
let queue = new this.Queue(name, true)
|
|
||||||
this.amqpAdmin.declareQueue(queue)
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
declareBinding(queue: string, exchange: string, routerKey: string, argument: any = null) {
|
|
||||||
let binding = new this.Binding(queue, this.DestinationType.QUEUE, exchange, routerKey, argument)
|
|
||||||
this.amqpAdmin.declareBinding(binding)
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
declareQueueAndBindExchange(queue: string, exchange: string, routerKey: string) {
|
|
||||||
return this.declareQueue(queue).declareExchange(exchange).declareBinding(queue, exchange, routerKey)
|
|
||||||
}
|
|
||||||
|
|
||||||
createContainer<T>(queue: string, listener: MessageHandler<T>, acknowledgeMode = AcknowledgeMode.AUTO) {
|
|
||||||
let connection = this.amqpAdmin.getRabbitTemplate().getConnectionFactory()
|
|
||||||
return new MessageListenerContainerAdapter({
|
|
||||||
connectionFactory: connection,
|
|
||||||
queueNames: [queue],
|
|
||||||
messageListener: new SimpleMessageHandler(listener),
|
|
||||||
acknowledgeMode: acknowledgeMode
|
|
||||||
}).getHandler()
|
|
||||||
}
|
|
||||||
|
|
||||||
send()
|
|
||||||
send() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
getTemplate() {
|
|
||||||
return this.amqpAdmin.getRabbitTemplate()
|
|
||||||
}
|
|
||||||
|
|
||||||
close() {
|
|
||||||
this.getTemplate().stop()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export class SimpleMessageHandler extends ChannelAwareMessageListenerAdapter {
|
|
||||||
constructor(private handler: MessageHandler<any>) {
|
|
||||||
super()
|
|
||||||
}
|
|
||||||
onMessage(content: any, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
|
|
||||||
return this.handler(content, message, channel)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
export const METADATA_KEY = {
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
/// <reference types="@ccms/nashorn" />
|
|
||||||
/// <reference types="@ccms/types/dist/typings/jdk" />
|
|
||||||
/// <reference types="@ccms/types/dist/typings/spring" />
|
|
||||||
/// <reference types="@ccms/types/dist/typings/spring/amqp" />
|
|
||||||
/// <reference types="@ccms/types/dist/typings/rabbitmq" />
|
|
||||||
|
|
||||||
import { amqp } from '@ccms/api'
|
|
||||||
import { getContainer, reduceMetadata } from '@ccms/container'
|
|
||||||
|
|
||||||
function init() {
|
|
||||||
const beanFactory = base.getInstance().getAutowireCapableBeanFactory()
|
|
||||||
getContainer().bind(amqp.rabbit.Template).toDynamicValue((ctx) => {
|
|
||||||
let metadata = reduceMetadata(ctx)
|
|
||||||
if (!metadata.named) {
|
|
||||||
return beanFactory.getBean('rabbitTemplate')
|
|
||||||
} else {
|
|
||||||
return beanFactory.getBean(`${metadata.named}-rabbitTemplate`)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
getContainer().bind(amqp.rabbit.Admin).toDynamicValue((ctx) => {
|
|
||||||
let metadata = reduceMetadata(ctx)
|
|
||||||
if (!metadata.named) {
|
|
||||||
return beanFactory.getBean('rabbitAdmin')
|
|
||||||
} else {
|
|
||||||
return beanFactory.getBean(`${metadata.named}-rabbitAdmin`)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
init()
|
|
||||||
|
|
||||||
export * from './admin'
|
|
||||||
export * from './adapter'
|
|
||||||
export * from './manager'
|
|
||||||
export * from './constants'
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
export class AmqpListener {
|
|
||||||
constructor() {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
import { amqp } from "@ccms/api"
|
|
||||||
import { provideSingleton } from "@ccms/container"
|
|
||||||
|
|
||||||
import { ConnectionFactoryAdapter, RabbitTemplateAdapter, RabbitAdminAdapter } from "./adapter"
|
|
||||||
import { AmqpAdmin } from "./admin"
|
|
||||||
|
|
||||||
@provideSingleton(amqp.Manager)
|
|
||||||
export class AmqpManager {
|
|
||||||
createConnection(url: string, username: string, password: string) {
|
|
||||||
return new ConnectionFactoryAdapter({ url, username, password })
|
|
||||||
}
|
|
||||||
createTemplate(adapter: ConnectionFactoryAdapter) {
|
|
||||||
return new RabbitTemplateAdapter({ connectionFactory: adapter })
|
|
||||||
}
|
|
||||||
createAdmin(adapter: RabbitTemplateAdapter | ConnectionFactoryAdapter) {
|
|
||||||
return new AmqpAdmin(new RabbitAdminAdapter(adapter))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"extends": "../../tsconfig.json",
|
|
||||||
"compilerOptions": {
|
|
||||||
"baseUrl": "src",
|
|
||||||
"outDir": "dist"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/api",
|
"name": "@ccms/api",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -19,9 +19,8 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/container": "^0.7.0",
|
"@ccms/container": "^0.6.0",
|
||||||
"@ccms/ployfill": "^0.7.0",
|
"@ccms/ployfill": "^0.6.0",
|
||||||
"@ccms/common": "^0.7.0",
|
|
||||||
"base64-js": "^1.3.1",
|
"base64-js": "^1.3.1",
|
||||||
"source-map-builder": "^0.0.7"
|
"source-map-builder": "^0.0.7"
|
||||||
},
|
},
|
||||||
@@ -29,6 +28,6 @@
|
|||||||
"@types/base64-js": "^1.2.5",
|
"@types/base64-js": "^1.2.5",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import i18n from '@ccms/i18n'
|
import i18n from '@ccms/i18n'
|
||||||
import { injectable } from "@ccms/container"
|
import { injectable } from "@ccms/container";
|
||||||
import { plugin } from './interfaces'
|
|
||||||
|
|
||||||
export namespace command {
|
export namespace command {
|
||||||
@injectable()
|
@injectable()
|
||||||
@@ -11,17 +10,16 @@ export namespace command {
|
|||||||
* @param name 命令
|
* @param name 命令
|
||||||
* @param exec 执行器
|
* @param exec 执行器
|
||||||
*/
|
*/
|
||||||
on(plugin: plugin.Plugin, name: string, exec: { cmd: Function, tab?: Function }) {
|
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
|
||||||
var cmd = this.create(plugin, name)
|
var cmd = this.create(plugin, name);
|
||||||
if (!cmd) { throw Error("") }
|
|
||||||
console.debug(i18n.translate("ms.api.command.register", { plugin: plugin.description.name, name, cmd }))
|
console.debug(i18n.translate("ms.api.command.register", { plugin: plugin.description.name, name, cmd }))
|
||||||
if (exec.cmd && typeof exec.cmd === "function") {
|
if (exec.cmd && typeof exec.cmd === "function") {
|
||||||
this.onCommand(plugin, cmd, exec.cmd)
|
this.onCommand(plugin, cmd, exec.cmd);
|
||||||
} else {
|
} else {
|
||||||
throw Error(i18n.translate("ms.api.command.register.input.error", { exec: exec.cmd }))
|
throw Error(i18n.translate("ms.api.command.register.input.error", { exec: exec.cmd }))
|
||||||
}
|
}
|
||||||
if (exec.tab && typeof exec.tab === "function") {
|
if (exec.tab && typeof exec.tab === "function") {
|
||||||
this.onTabComplete(plugin, cmd, exec.tab)
|
this.onTabComplete(plugin, cmd, exec.tab);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
@@ -29,40 +27,40 @@ export namespace command {
|
|||||||
* @param plugin 插件
|
* @param plugin 插件
|
||||||
* @param name 命令
|
* @param name 命令
|
||||||
*/
|
*/
|
||||||
off(plugin: plugin.Plugin, name: string) {
|
off(plugin: any, name: string) {
|
||||||
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
|
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
|
||||||
this.remove(plugin, name)
|
this.remove(plugin, name);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected abstract create(plugin: plugin.Plugin, command: string): any
|
protected abstract create(plugin: any, command: string);
|
||||||
protected abstract remove(plugin: plugin.Plugin, command: string): void
|
protected abstract remove(plugin: any, command: string);
|
||||||
protected abstract onCommand(plugin: plugin.Plugin, command: any, executor: Function)
|
protected abstract onCommand(plugin: any, command: any, executor: Function);
|
||||||
protected abstract onTabComplete(plugin: plugin.Plugin, command: any, tabCompleter: Function)
|
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
|
||||||
protected setExecutor(plugin: plugin.Plugin, command: any, executor: Function) {
|
protected setExecutor(plugin: any, command: any, executor: Function) {
|
||||||
return (sender: any, _: any, command: string, args: string[]) => {
|
return (sender: any, _: any, command: string, args: string[]) => {
|
||||||
try {
|
try {
|
||||||
return executor(sender, command, Java.from(args))
|
return executor(sender, command, Java.from(args));
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.i18n("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
console.i18n("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
||||||
console.ex(ex)
|
console.ex(ex);
|
||||||
if (sender.name != 'CONSOLE') {
|
if (sender.name != 'CONSOLE') {
|
||||||
console.sender(sender, [i18n.translate("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
|
console.sender(sender, [i18n.translate("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
|
||||||
}
|
}
|
||||||
return true
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
protected setTabCompleter(plugin: plugin.Plugin, command: any, tabCompleter: Function) {
|
protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
|
||||||
return (sender: any, _: any, command: string, args: string[]) => {
|
return (sender: any, _: any, command: string, args: string[]) => {
|
||||||
try {
|
try {
|
||||||
var token = args[args.length - 1]
|
var token = args[args.length - 1];
|
||||||
var complete = tabCompleter(sender, command, Java.from(args)) || []
|
var complete = tabCompleter(sender, command, Java.from(args)) || [];
|
||||||
return this.copyPartialMatches(complete, token)
|
return this.copyPartialMatches(complete, token);
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.i18n("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
console.i18n("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
||||||
console.ex(ex)
|
console.ex(ex);
|
||||||
console.sender(sender, [i18n.translate("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
|
console.sender(sender, [i18n.translate("ms.api.command.tab.completer.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)]);
|
||||||
return []
|
return [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -72,7 +70,7 @@ export namespace command {
|
|||||||
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
|
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
|
||||||
array.push(e)
|
array.push(e)
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
return array
|
return array
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ import i18m from '@ccms/i18n'
|
|||||||
import { SourceMapBuilder } from 'source-map-builder'
|
import { SourceMapBuilder } from 'source-map-builder'
|
||||||
import * as base64 from 'base64-js'
|
import * as base64 from 'base64-js'
|
||||||
|
|
||||||
const Arrays = Java.type('java.util.Arrays')
|
const Arrays = Java.type('java.util.Arrays');
|
||||||
const Level = Java.type('java.util.logging.Level')
|
const Level = Java.type('java.util.logging.Level');
|
||||||
const Paths = Java.type('java.nio.file.Paths')
|
const Paths = Java.type('java.nio.file.Paths');
|
||||||
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
|
const ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.'];
|
||||||
|
|
||||||
enum LogLevel {
|
enum LogLevel {
|
||||||
ALL,
|
ALL,
|
||||||
@@ -19,19 +19,19 @@ enum LogLevel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class MiaoScriptConsole implements Console {
|
export class MiaoScriptConsole implements Console {
|
||||||
Console: NodeJS.ConsoleConstructor
|
Console: NodeJS.ConsoleConstructor;
|
||||||
|
|
||||||
private static sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
private sourceMaps: { [key: string]: SourceMapBuilder } = {};
|
||||||
private static sourceFileMaps: { [key: string]: string } = {}
|
private sourceFileMaps: { [key: string]: string } = {};
|
||||||
private _name: string = ''
|
private _name: string = '';
|
||||||
private _level: LogLevel = LogLevel.INFO
|
private _level: LogLevel = LogLevel.INFO;
|
||||||
|
|
||||||
protected logger: any
|
protected logger: any;
|
||||||
protected prefix: string = '§6[§bMiaoScript§6]§r '
|
protected prefix: string = '§6[§bMiaoScript§6]§r ';
|
||||||
|
|
||||||
constructor(name?: string) {
|
constructor(name?: string) {
|
||||||
this.name = name
|
this.name = name;
|
||||||
this.logger = global.logger
|
this.logger = global.logger;
|
||||||
if (global.debug) {
|
if (global.debug) {
|
||||||
this._level = LogLevel.DEBUG
|
this._level = LogLevel.DEBUG
|
||||||
}
|
}
|
||||||
@@ -41,36 +41,36 @@ export class MiaoScriptConsole implements Console {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get name() {
|
get name() {
|
||||||
return this._name
|
return this._name;
|
||||||
}
|
}
|
||||||
|
|
||||||
set name(name: string) {
|
set name(name: string) {
|
||||||
if (name) {
|
if (name) {
|
||||||
this._name = `[${name}] `
|
this._name = `[${name}] `;
|
||||||
// noinspection JSUnusedGlobalSymbols
|
// noinspection JSUnusedGlobalSymbols
|
||||||
this.prefix = `§6[§cMS§6][§b${name}§6]§r `
|
this.prefix = `§6[§cMS§6][§b${name}§6]§r `;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log(...args: any[]): void {
|
log(...args: any[]): void {
|
||||||
this.logger.info(this.name + args.join(' '))
|
this.logger.info(this.name + args.join(' '));
|
||||||
}
|
}
|
||||||
info(...args: any[]) {
|
info(...args: any[]) {
|
||||||
this.logger.info(this.name + args.join(' '))
|
this.logger.info(this.name + args.join(' '));
|
||||||
}
|
}
|
||||||
warn(...args: any[]) {
|
warn(...args: any[]) {
|
||||||
this.logger.warning(this.name + args.join(' '))
|
this.logger.warning(this.name + args.join(' '));
|
||||||
}
|
}
|
||||||
error(...args: any[]) {
|
error(...args: any[]) {
|
||||||
this.logger.log(Level.SEVERE, this.name + args.join(' '))
|
this.logger.log(Level.SEVERE, this.name + args.join(' '));
|
||||||
}
|
}
|
||||||
debug(...args: any[]) {
|
debug(...args: any[]) {
|
||||||
if (global.debug) {
|
if (global.debug) {
|
||||||
this.logger.info(this.name + '[DEBUG] ' + args.join(' '))
|
this.logger.info(this.name + '[DEBUG] ' + args.join(' '));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
trace(...args: any[]): void {
|
trace(...args: any[]): void {
|
||||||
if (this._level <= LogLevel.TRACE) {
|
if (this._level <= LogLevel.TRACE) {
|
||||||
this.logger.info(this.name + '[TRACE] ' + args.join(' '))
|
this.logger.info(this.name + '[TRACE] ' + args.join(' '));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
sender(...args) {
|
sender(...args) {
|
||||||
@@ -93,31 +93,31 @@ export class MiaoScriptConsole implements Console {
|
|||||||
readSourceMap(fileName: string, lineNumber: number) {
|
readSourceMap(fileName: string, lineNumber: number) {
|
||||||
try {
|
try {
|
||||||
if (fileName.endsWith('js')) {
|
if (fileName.endsWith('js')) {
|
||||||
if (MiaoScriptConsole.sourceMaps[fileName] === undefined) {
|
if (this.sourceMaps[fileName] === undefined) {
|
||||||
MiaoScriptConsole.sourceMaps[fileName] = null
|
this.sourceMaps[fileName] = null
|
||||||
let sourceLine = base.read(fileName).split('\n')
|
let sourceLine = base.read(fileName).split('\n');
|
||||||
let lastLine = sourceLine[sourceLine.length - 1]
|
let lastLine = sourceLine[sourceLine.length - 1]
|
||||||
if (lastLine.startsWith('//# sourceMappingURL=')) {
|
if (lastLine.startsWith('//# sourceMappingURL=')) {
|
||||||
let sourceContent = null
|
let sourceContent = null;
|
||||||
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
|
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1];
|
||||||
if (sourceMappingURL.startsWith('data:application/jsonbase64,')) {
|
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
||||||
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
||||||
} else if (sourceMappingURL.startsWith('http')) {
|
} else if (sourceMappingURL.startsWith('http')) {
|
||||||
// TODO
|
// TODO
|
||||||
} else {
|
} else {
|
||||||
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
|
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile();
|
||||||
if (file.exists()) { sourceContent = base.read(file) }
|
if (file.exists()) { sourceContent = base.read(file) }
|
||||||
}
|
}
|
||||||
if (sourceContent) {
|
if (sourceContent) {
|
||||||
MiaoScriptConsole.sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
this.sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
||||||
MiaoScriptConsole.sourceFileMaps[fileName] = Paths.get(fileName, '..', MiaoScriptConsole.sourceMaps[fileName].sources[0]).toFile().getCanonicalPath()
|
this.sourceFileMaps[fileName] = Paths.get(fileName, '..', this.sourceMaps[fileName].sources[0]).toFile().getCanonicalPath();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (MiaoScriptConsole.sourceMaps[fileName]) {
|
if (this.sourceMaps[fileName]) {
|
||||||
let sourceMapping = MiaoScriptConsole.sourceMaps[fileName].getSource(lineNumber, 25, true, true)
|
let sourceMapping = this.sourceMaps[fileName].getSource(lineNumber, 25, true, true);
|
||||||
fileName = MiaoScriptConsole.sourceFileMaps[fileName]
|
fileName = this.sourceFileMaps[fileName]
|
||||||
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine }
|
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -128,26 +128,21 @@ export class MiaoScriptConsole implements Console {
|
|||||||
lineNumber
|
lineNumber
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
stack(ex: Error, color: boolean = true): string[] {
|
stack(ex: Error): string[] {
|
||||||
let stack = ex.getStackTrace()
|
let stack = ex.getStackTrace();
|
||||||
let cache = [(color ? '§c' : '') + ex]
|
let cache = ['§c' + ex];
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
if (stack.class) {
|
if (stack.class) {
|
||||||
stack = Arrays.asList(stack)
|
stack = Arrays.asList(stack)
|
||||||
}
|
}
|
||||||
stack.forEach(trace => {
|
stack.forEach(trace => {
|
||||||
if (!trace.fileName || trace.fileName.startsWith('jar:file:') || trace.fileName.startsWith('file:')) { return }
|
|
||||||
if (trace.className.startsWith('<')) {
|
if (trace.className.startsWith('<')) {
|
||||||
let { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
let { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||||
if (color) {
|
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${lineNumber}`)
|
||||||
cache.push(` §e->§c ${fileName}:${lineNumber} => §4${trace.methodName}`)
|
|
||||||
} else {
|
|
||||||
cache.push(` -> ${fileName}:${lineNumber} => ${trace.methodName}`)
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
let className = trace.className
|
let className = trace.className;
|
||||||
var fileName = trace.fileName as string
|
var fileName = trace.fileName as string;
|
||||||
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
||||||
className = className.substr(className.lastIndexOf('$') + 1)
|
className = className.substr(className.lastIndexOf('$') + 1)
|
||||||
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||||
@@ -155,74 +150,70 @@ export class MiaoScriptConsole implements Console {
|
|||||||
} else {
|
} else {
|
||||||
for (let prefix in ignoreLogPrefix) {
|
for (let prefix in ignoreLogPrefix) {
|
||||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (color) {
|
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`);
|
||||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
|
|
||||||
} else {
|
|
||||||
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
return cache
|
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?: NodeJS.InspectOptions): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
dirxml(...data: any[]): void {
|
dirxml(...data: any[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
group(...label: any[]): void {
|
group(...label: any[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
groupCollapsed(...label: any[]): void {
|
groupCollapsed(...label: any[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
groupEnd(): void {
|
groupEnd(): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
table(tabularData: any, properties?: string[]): void {
|
table(tabularData: any, properties?: string[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
time(label?: string): void {
|
time(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
timeEnd(label?: string): void {
|
timeEnd(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
timeLog(label?: string, ...data: any[]): void {
|
timeLog(label?: string, ...data: any[]): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
markTimeline(label?: string): void {
|
markTimeline(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
profile(label?: string): void {
|
profile(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
profileEnd(label?: string): void {
|
profileEnd(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
timeStamp(label?: string): void {
|
timeStamp(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
timeline(label?: string): void {
|
timeline(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
timelineEnd(label?: string): void {
|
timelineEnd(label?: string): void {
|
||||||
throw new Error("Method not implemented.")
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ export namespace constants {
|
|||||||
Bukkit = 'bukkit',
|
Bukkit = 'bukkit',
|
||||||
Sponge = 'sponge',
|
Sponge = 'sponge',
|
||||||
Nukkit = 'nukkit',
|
Nukkit = 'nukkit',
|
||||||
Bungee = 'bungee',
|
Bungee = 'bungee'
|
||||||
Spring = 'spring'
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,9 +21,6 @@ export namespace event {
|
|||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class Event {
|
export abstract class Event {
|
||||||
// export EventPriority to blockly
|
|
||||||
public EventPriority = EventPriority;
|
|
||||||
|
|
||||||
private mapEvent = [];
|
private mapEvent = [];
|
||||||
private listenerMap = [];
|
private listenerMap = [];
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
export namespace amqp {
|
|
||||||
export const Manager = Symbol('AmqpManager')
|
|
||||||
export namespace rabbit {
|
|
||||||
export const Admin = Symbol('RabbitAdmin')
|
|
||||||
export const Template = Symbol('RabbitTemplate')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
export namespace database {
|
|
||||||
export const DataBaseManager = Symbol("DataBaseManager");
|
|
||||||
export const DataSource = Symbol("DataSource");
|
|
||||||
export const DataBase = Symbol("DataBase");
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,2 @@
|
|||||||
export * from './web'
|
|
||||||
export * from './amqp'
|
|
||||||
export * from './plugin'
|
export * from './plugin'
|
||||||
export * from './server'
|
export * from './server'
|
||||||
export * from './database'
|
|
||||||
|
|||||||
@@ -2,147 +2,29 @@ export namespace plugin {
|
|||||||
/**
|
/**
|
||||||
* MiaoScript Plugin
|
* MiaoScript Plugin
|
||||||
*/
|
*/
|
||||||
export const Plugin = Symbol("Plugin")
|
export const Plugin = Symbol("Plugin");
|
||||||
/**
|
/**
|
||||||
* MiaoScript Plugin Folder
|
* MiaoScript Plugin Folder
|
||||||
*/
|
*/
|
||||||
export const PluginFolder = Symbol("PluginFolder")
|
export const PluginFolder = Symbol("PluginFolder");
|
||||||
/**
|
/**
|
||||||
* Runtime Plugin Instance
|
* Runtime Plugin Instance
|
||||||
*/
|
*/
|
||||||
export const PluginInstance = Symbol("PluginInstance")
|
export const PluginInstance = Symbol("PluginInstance");
|
||||||
/**
|
/**
|
||||||
* MiaoScript Plugin Manager Symbol
|
* MiaoScript Plugin Manager Symbol
|
||||||
*/
|
*/
|
||||||
export const PluginManager = Symbol("PluginManager")
|
export const PluginManager = Symbol("PluginManager");
|
||||||
/**
|
/**
|
||||||
* MiaoScript Plugin Manager Interface
|
* MiaoScript Plugin Manager Interface
|
||||||
*/
|
*/
|
||||||
export interface PluginManager {
|
export interface PluginManager {
|
||||||
scan(folder: string): void
|
scan(folder: string): void;
|
||||||
build(): void
|
build(): void;
|
||||||
loadFromFile(file: string, scanner?: plugin.PluginScanner): Plugin
|
load(...args: any[]): void;
|
||||||
load(...args: any[]): void
|
enable(...args: any[]): void;
|
||||||
enable(...args: any[]): void
|
disable(...args: any[]): void;
|
||||||
disable(...args: any[]): void
|
reload(...args: any[]): void;
|
||||||
reload(...args: any[]): void
|
getPlugins(): Map<string, any>;
|
||||||
getPlugin(name: string): plugin.Plugin
|
|
||||||
getPlugins(): Map<string, plugin.Plugin>
|
|
||||||
}
|
|
||||||
export const PluginScanner = Symbol("PluginScanner")
|
|
||||||
/**
|
|
||||||
* 插件扫描器
|
|
||||||
*/
|
|
||||||
export interface PluginScanner {
|
|
||||||
/**
|
|
||||||
* 扫描器类型
|
|
||||||
*/
|
|
||||||
type: string
|
|
||||||
/**
|
|
||||||
* 扫描插件 返回插件加载列表
|
|
||||||
* @param target 扫描目标
|
|
||||||
*/
|
|
||||||
scan(target: any): string[]
|
|
||||||
/**
|
|
||||||
* 加载扫描到的目标
|
|
||||||
* @param target 加载目标
|
|
||||||
*/
|
|
||||||
load(target: any): any
|
|
||||||
}
|
|
||||||
export const PluginLoader = Symbol("PluginLoader")
|
|
||||||
/**
|
|
||||||
* 插件加载器
|
|
||||||
*/
|
|
||||||
export interface PluginLoader {
|
|
||||||
/**
|
|
||||||
* 加载器类型
|
|
||||||
*/
|
|
||||||
type: string
|
|
||||||
/**
|
|
||||||
* 加载插件 获取元数据
|
|
||||||
* @param target 加载目标
|
|
||||||
* @param result 扫描器加载的结果
|
|
||||||
*/
|
|
||||||
require(target: any, result: any): PluginMetadata
|
|
||||||
/**
|
|
||||||
* 构建插件
|
|
||||||
* @param metadata 插件元信息
|
|
||||||
*/
|
|
||||||
build(metadata: any): 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
|
|
||||||
/**
|
|
||||||
* 前缀
|
|
||||||
*/
|
|
||||||
prefix?: string
|
|
||||||
/**
|
|
||||||
* 插件版本
|
|
||||||
*/
|
|
||||||
version: string
|
|
||||||
/**
|
|
||||||
* 插件版本
|
|
||||||
*/
|
|
||||||
author: string | string[]
|
|
||||||
/**
|
|
||||||
* 插件源文件 必须指定为 __filename
|
|
||||||
*/
|
|
||||||
source: string
|
|
||||||
/**
|
|
||||||
* 插件类型 默认为 ioc 执行 MiaoScript 加载逻辑
|
|
||||||
*/
|
|
||||||
type?: string
|
|
||||||
/**
|
|
||||||
* 插件扫描器
|
|
||||||
*/
|
|
||||||
scanner?: PluginScanner
|
|
||||||
/**
|
|
||||||
* 插件加载器
|
|
||||||
*/
|
|
||||||
loader?: PluginLoader
|
|
||||||
/**
|
|
||||||
* 插件本体
|
|
||||||
*/
|
|
||||||
target?: any
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,143 +1,36 @@
|
|||||||
import * as reflect from '@ccms/common/dist/reflect'
|
|
||||||
import { injectable } from '@ccms/container'
|
|
||||||
|
|
||||||
import { NativePluginManager } from './native_plugin'
|
import { NativePluginManager } from './native_plugin'
|
||||||
import { constants } from '../../constants'
|
|
||||||
|
|
||||||
export namespace server {
|
export namespace server {
|
||||||
/**
|
/**
|
||||||
* Runtime ServerType
|
* Runtime ServerType
|
||||||
*/
|
*/
|
||||||
export const ServerType = Symbol("ServerType")
|
export const ServerType = Symbol("ServerType");
|
||||||
/**
|
/**
|
||||||
* Runtime Console
|
* Runtime Console
|
||||||
*/
|
*/
|
||||||
export const Console = Symbol("Console")
|
export const Console = Symbol("Console");
|
||||||
/**
|
/**
|
||||||
* MiaoScript Server
|
* MiaoScript Server
|
||||||
*/
|
*/
|
||||||
export const Server = Symbol("Server")
|
export const Server = Symbol("Server");
|
||||||
/**
|
/**
|
||||||
* Runtime Server Instance
|
* Runtime Server Instance
|
||||||
*/
|
*/
|
||||||
export const ServerInstance = Symbol("ServerInstance")
|
export const ServerInstance = Symbol("ServerInstance");
|
||||||
/**
|
/**
|
||||||
* MiaoScript Server
|
* MiaoScript Server
|
||||||
*/
|
*/
|
||||||
export interface Server {
|
export interface Server {
|
||||||
getVersion(): string
|
getVersion(): string;
|
||||||
getPlayer(name: string): any
|
getPlayer(name: string): any;
|
||||||
getOnlinePlayers(): any[]
|
getOnlinePlayers(): any[];
|
||||||
getConsoleSender(): any
|
getConsoleSender(): any;
|
||||||
getService(service: string): any
|
getService(service: string): any;
|
||||||
dispatchCommand(sender: string | any, command: string): boolean
|
dispatchCommand(sender: string | any, command: string): boolean;
|
||||||
dispatchConsoleCommand(command: string): boolean
|
dispatchConsoleCommand(command: string): boolean;
|
||||||
getPluginsFolder(): string
|
getPluginsFolder(): string;
|
||||||
getNativePluginManager(): NativePluginManager
|
getNativePluginManager(): NativePluginManager;
|
||||||
getDedicatedServer?(): any
|
getNettyPipeline(): any;
|
||||||
getNettyPipeline(): any
|
sendJson(sender: string | any, json: object | string): void;
|
||||||
getRootLogger(): any
|
|
||||||
sendJson(sender: string | any, json: object | string): void
|
|
||||||
tabComplete?(sender: string | any, input: string, index?: number): string[]
|
|
||||||
}
|
|
||||||
@injectable()
|
|
||||||
export abstract class ReflectServer implements server.Server {
|
|
||||||
protected pipeline: any
|
|
||||||
protected rootLogger: any
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
this.reflect()
|
|
||||||
}
|
|
||||||
|
|
||||||
getVersion(): string {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getPlayer(name: string) {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getOnlinePlayers(): any[] {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getConsoleSender() {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getService(service: string) {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
dispatchCommand(sender: 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.")
|
|
||||||
}
|
|
||||||
getNativePluginManager(): NativePluginManager {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getDedicatedServer() {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getNettyPipeline() {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
getRootLogger() {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
sendJson(sender: any, json: string | object): void {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
tabComplete?(sender: any, input: string, index?: number): string[] {
|
|
||||||
throw new Error("Method not implemented.")
|
|
||||||
}
|
|
||||||
protected reflect() {
|
|
||||||
try {
|
|
||||||
let consoleServer = this.getDedicatedServer()
|
|
||||||
this.reflectPipeline(consoleServer)
|
|
||||||
this.reflectRootLogger(consoleServer)
|
|
||||||
} catch (error) {
|
|
||||||
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) { }
|
|
||||||
}
|
|
||||||
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
|
||||||
for (const field of constants.Reflect.Field.listeningChannels) {
|
|
||||||
try {
|
|
||||||
promise = reflect.on(connection).get(field).get().get(0)
|
|
||||||
if (promise.class.name.indexOf('Promise') !== -1) { break }
|
|
||||||
promise = undefined
|
|
||||||
} catch (error) { }
|
|
||||||
}
|
|
||||||
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
|
||||||
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
|
||||||
}
|
|
||||||
protected reflectRootLogger(consoleServer: any) {
|
|
||||||
try {
|
|
||||||
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get().parent
|
|
||||||
} catch (error) {
|
|
||||||
try { this.rootLogger = reflect.on(consoleServer).get(0).get().parent } catch (error) { }
|
|
||||||
}
|
|
||||||
if (this.rootLogger && this.rootLogger.class.name.indexOf('Logger') === -1) {
|
|
||||||
console.error('Error Logger Class: ' + this.rootLogger.class.name)
|
|
||||||
this.rootLogger = undefined
|
|
||||||
}
|
|
||||||
// get root logger
|
|
||||||
for (let index = 0; index < 5 && this.rootLogger.parent; index++) {
|
|
||||||
this.rootLogger = this.rootLogger.parent
|
|
||||||
}
|
|
||||||
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
export namespace web {
|
|
||||||
export const Server = Symbol('Server')
|
|
||||||
}
|
|
||||||
@@ -58,9 +58,9 @@ export namespace task {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected run(...args: any[]): void {
|
protected run(): void {
|
||||||
try {
|
try {
|
||||||
this.func(...args);
|
this.func();
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.console('§4插件执行任务时发生错误', ex)
|
console.console('§4插件执行任务时发生错误', ex)
|
||||||
console.ex(ex);
|
console.ex(ex);
|
||||||
@@ -69,9 +69,8 @@ export namespace task {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 提交任务
|
* 提交任务
|
||||||
* @param args 任务参数
|
|
||||||
*/
|
*/
|
||||||
abstract submit(...args: any[]): Cancelable;
|
abstract submit(): Cancelable;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 返可取消的对象
|
* 返可取消的对象
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/bukkit",
|
"name": "@ccms/bukkit",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript bukkit package",
|
"description": "MiaoScript bukkit package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,11 +21,11 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.7.0",
|
"@ccms/api": "^0.6.0",
|
||||||
"@ccms/common": "^0.7.0",
|
"@ccms/common": "^0.6.0",
|
||||||
"@ccms/container": "^0.7.0"
|
"@ccms/container": "^0.6.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,12 +7,13 @@ import chat from './enhance/chat'
|
|||||||
let Bukkit = org.bukkit.Bukkit;
|
let Bukkit = org.bukkit.Bukkit;
|
||||||
|
|
||||||
@provideSingleton(server.Server)
|
@provideSingleton(server.Server)
|
||||||
export class BukkitServer extends server.ReflectServer {
|
export class BukkitServer implements server.Server {
|
||||||
private pluginsFolder: string;
|
private pluginsFolder: string;
|
||||||
|
private pipeline: any;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
|
||||||
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath();
|
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath();
|
||||||
|
this.reflectPipeline()
|
||||||
}
|
}
|
||||||
|
|
||||||
getPlayer(name: string) {
|
getPlayer(name: string) {
|
||||||
@@ -45,15 +46,9 @@ export class BukkitServer extends server.ReflectServer {
|
|||||||
getNativePluginManager() {
|
getNativePluginManager() {
|
||||||
return Bukkit.getPluginManager() as any;
|
return Bukkit.getPluginManager() as any;
|
||||||
}
|
}
|
||||||
getDedicatedServer() {
|
|
||||||
return reflect.on(Bukkit.getServer()).get('console').get()
|
|
||||||
}
|
|
||||||
getNettyPipeline() {
|
getNettyPipeline() {
|
||||||
return this.pipeline;
|
return this.pipeline;
|
||||||
}
|
}
|
||||||
getRootLogger() {
|
|
||||||
return this.rootLogger;
|
|
||||||
}
|
|
||||||
sendJson(sender: string | any, json: object | string): void {
|
sendJson(sender: string | any, json: object | string): void {
|
||||||
if (typeof sender === "string") {
|
if (typeof sender === "string") {
|
||||||
sender = this.getPlayer(sender)
|
sender = this.getPlayer(sender)
|
||||||
@@ -63,4 +58,27 @@ export class BukkitServer extends server.ReflectServer {
|
|||||||
this.dispatchConsoleCommand(result)
|
this.dispatchConsoleCommand(result)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private reflectPipeline() {
|
||||||
|
let consoleServer = reflect.on(Bukkit.getServer()).get('console').get()
|
||||||
|
let connection: any;
|
||||||
|
let promise: any;
|
||||||
|
for (const method of constants.Reflect.Method.getServerConnection) {
|
||||||
|
try {
|
||||||
|
connection = reflect.on(consoleServer).call(method).get()
|
||||||
|
if (connection.class.name.indexOf('ServerConnection') !== -1) { break; }
|
||||||
|
connection = undefined;
|
||||||
|
} catch (error) { }
|
||||||
|
}
|
||||||
|
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
||||||
|
for (const field of constants.Reflect.Field.listeningChannels) {
|
||||||
|
try {
|
||||||
|
promise = reflect.on(connection).get(field).get().get(0);
|
||||||
|
if (promise.class.name.indexOf('Promise') !== -1) { break; }
|
||||||
|
promise = undefined;
|
||||||
|
} catch (error) { }
|
||||||
|
}
|
||||||
|
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
||||||
|
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,8 +23,10 @@ export class BukkitTaskManager implements task.TaskManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class BukkitTask extends task.Task {
|
export class BukkitTask extends task.Task {
|
||||||
submit(...args: any[]): task.Cancelable {
|
submit(): task.Cancelable {
|
||||||
let run = new BukkitRunnable({ run: () => this.run(...args) })
|
let run = new BukkitRunnable({
|
||||||
|
run: () => this.run()
|
||||||
|
})
|
||||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||||
if (this.interval) {
|
if (this.interval) {
|
||||||
return run[funcName](this.plugin, this.laterTime, this.interval)
|
return run[funcName](this.plugin, this.laterTime, this.interval)
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/bungee",
|
"name": "@ccms/bungee",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript bungee package",
|
"description": "MiaoScript bungee package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,11 +21,11 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.7.0",
|
"@ccms/api": "^0.6.0",
|
||||||
"@ccms/common": "^0.7.0",
|
"@ccms/common": "^0.6.0",
|
||||||
"@ccms/container": "^0.7.0"
|
"@ccms/container": "^0.6.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
|||||||
export class BungeeServer implements server.Server {
|
export class BungeeServer implements server.Server {
|
||||||
private pluginsFolder: string;
|
private pluginsFolder: string;
|
||||||
private pipeline: any;
|
private pipeline: any;
|
||||||
private rootLogger: any;
|
|
||||||
|
|
||||||
@inject(task.TaskManager)
|
@inject(task.TaskManager)
|
||||||
private task: task.TaskManager
|
private task: task.TaskManager
|
||||||
@@ -36,11 +35,6 @@ export class BungeeServer implements server.Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}).later(10).timer(20).submit()
|
}).later(10).timer(20).submit()
|
||||||
try {
|
|
||||||
this.rootLogger = Bungee.getLogger()
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Can't found rootLogger!")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getPlayer(name: string) {
|
getPlayer(name: string) {
|
||||||
@@ -76,9 +70,6 @@ export class BungeeServer implements server.Server {
|
|||||||
getNettyPipeline() {
|
getNettyPipeline() {
|
||||||
return this.pipeline;
|
return this.pipeline;
|
||||||
}
|
}
|
||||||
getRootLogger() {
|
|
||||||
return this.rootLogger;
|
|
||||||
}
|
|
||||||
sendJson(sender: string | any, json: string): void {
|
sendJson(sender: string | any, json: string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,8 +22,8 @@ export class BungeeTaskManager implements task.TaskManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class BungeeTask extends task.Task {
|
export class BungeeTask extends task.Task {
|
||||||
submit(...args: any[]): task.Cancelable {
|
submit(): task.Cancelable {
|
||||||
let run = new Runnable({ run: () => this.run(...args) })
|
let run = new Runnable({ run: () => this.run() })
|
||||||
if (this.isAsync) {
|
if (this.isAsync) {
|
||||||
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
"private": true,
|
||||||
"name": "@ccms/client",
|
"name": "@ccms/client",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript client package",
|
"description": "MiaoScript client package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -26,6 +26,6 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,9 +6,7 @@ import { attachEvents } from './event'
|
|||||||
|
|
||||||
let username = process.argv[2] || 'Mr_jtb'
|
let username = process.argv[2] || 'Mr_jtb'
|
||||||
let version = process.argv[3] || '1.12.2'
|
let version = process.argv[3] || '1.12.2'
|
||||||
let address = process.argv[4] || '192.168.2.5:25577'
|
let client = createConnection('192.168.2.5', 25577, username)
|
||||||
let realAddress = address.split(":");
|
|
||||||
let client = createConnection(realAddress[0], parseInt(realAddress[1] || "25565"), username)
|
|
||||||
|
|
||||||
function createConnection(host: string, port: number, username: string) {
|
function createConnection(host: string, port: number, username: string) {
|
||||||
let client = createClient({
|
let client = createClient({
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/common",
|
"name": "@ccms/common",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,10 +21,10 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/nashorn": "^0.7.0"
|
"@ccms/nashorn": "^0.6.0"
|
||||||
},
|
},
|
||||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,9 @@ export function concat(...args: string[]) {
|
|||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
export function file(...opts: any[]): any {
|
export function file(...opts: any[]): any {
|
||||||
if (!opts[0]) { throw new Error("文件名称不得为 undefined 或者 null !") }
|
if (!opts[0]) {
|
||||||
|
console.warn("文件名称不得为 undefined 或者 null !");
|
||||||
|
}
|
||||||
switch (opts.length) {
|
switch (opts.length) {
|
||||||
case 1:
|
case 1:
|
||||||
var f = opts[0];
|
var f = opts[0];
|
||||||
@@ -141,7 +143,7 @@ export function del(file) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (file.isDirectory()) {
|
if (file.isDirectory()) {
|
||||||
Files.list(file.toPath()).collect(Collector.toList()).forEach(function (f) {
|
Files.list(file.toPath()).collect(Collector.toList()).forEach(function(f) {
|
||||||
del(f);
|
del(f);
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ function request(config: RequestConfig) {
|
|||||||
for (const header in config.headers) {
|
for (const header in config.headers) {
|
||||||
xhr.setRequestHeader(header, config.headers[header]);
|
xhr.setRequestHeader(header, config.headers[header]);
|
||||||
}
|
}
|
||||||
xhr.send(typeof config.data === "string" ? config.data : JSON.stringify(config.data));
|
xhr.send(config.data);
|
||||||
if ((xhr.getResponseHeader("Content-Type") + '').indexOf('application/json') != -1) {
|
if ((xhr.getResponseHeader("Content-Type") + '').indexOf('application/json') != -1) {
|
||||||
xhr.responseType = "json"
|
xhr.responseType = "json"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,204 +1,196 @@
|
|||||||
/// <reference types="@ccms/types/dist/typings/jdk" />
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 反射工具类
|
* 反射工具类
|
||||||
* Created by MiaoWoo on 2017/2/9 0009.
|
* Created by MiaoWoo on 2017/2/9 0009.
|
||||||
*/
|
*/
|
||||||
const JavaClass = Java.type('java.lang.Class')
|
const JavaClass = Java.type('java.lang.Class');
|
||||||
const JavaObject = Java.type('java.lang.Object')
|
const JavaObject = Java.type('java.lang.Object')
|
||||||
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException')
|
const NoSuchFieldException = Java.type('java.lang.NoSuchFieldException');
|
||||||
const methodCache = []
|
const methodCache = [];
|
||||||
|
|
||||||
class Reflect {
|
class Reflect {
|
||||||
private obj: java.lang.Object
|
private obj: any;
|
||||||
private class: java.lang.Class
|
private class: any
|
||||||
|
|
||||||
constructor(obj: any) {
|
constructor(obj: any) {
|
||||||
// if (obj === undefined || obj === null) { throw Error(`reflect object can't be ${obj}!`) }
|
// if (obj === undefined || obj === null) { throw Error(`reflect object can't be ${obj}!`) }
|
||||||
if (obj instanceof JavaClass) {
|
if (obj instanceof JavaClass) {
|
||||||
this.obj = null
|
this.obj = null;
|
||||||
this.class = obj
|
this.class = obj;
|
||||||
} else {
|
} else {
|
||||||
this.obj = obj
|
this.obj = obj;
|
||||||
if (obj !== null && obj !== undefined && obj.class) {
|
if (obj !== null && obj !== undefined && obj.class) {
|
||||||
this.class = obj.class
|
this.class = obj.class;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
method(name: string, ...args: any[]) {
|
method(...args: any[]) {
|
||||||
return declaredMethod(this.class, name, args)
|
return declaredMethod(this.class, args[0], types(args.slice(1)));
|
||||||
}
|
}
|
||||||
|
|
||||||
methods() {
|
methods() {
|
||||||
return Java.from(declaredMethods(this.class))
|
return Java.from(declaredMethods(this.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
field(name: string | java.lang.String): Reflect {
|
field(name): Reflect {
|
||||||
try {
|
try {
|
||||||
// Try getting a public field
|
// Try getting a public field
|
||||||
let field = this.class.getField(name)
|
let field = this.class.field(name);
|
||||||
return on(field.get(this.obj))
|
return on(field.get(this.obj));
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
// Try again, getting a non-public field
|
// Try again, getting a non-public field
|
||||||
return on(accessible(declaredField(this.class, name)).get(this.obj))
|
return on(accessible(declaredField(this.class, name)).get(this.obj));
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
fields(declared = false): java.lang.reflect.Field[] {
|
fields(declared = false) {
|
||||||
return Java.from(declared ? this.class.getDeclaredFields() : this.class.getFields())
|
return Java.from(declared ? this.class.declaredFields : this.class.fields);
|
||||||
}
|
}
|
||||||
|
|
||||||
values(declared = false) {
|
values(declared = false) {
|
||||||
return this.fields(declared).reduce((cache, field) => { return cache[field.getName()] = this.field(field.getName()).get() }, {}) as any
|
let cache = {};
|
||||||
|
this.fields(declared).forEach(fed => cache[fed.name] = this.field(fed.name).get())
|
||||||
|
return cache;
|
||||||
}
|
}
|
||||||
|
|
||||||
call(...args: any[]): Reflect {
|
call(...args): Reflect {
|
||||||
let params = args.slice(1)
|
let params = args.slice(1);
|
||||||
let method = accessible(declaredMethod(this.class, args[0], ...types(params)))
|
let method = accessible(declaredMethod(this.class, args[0], types(params)));
|
||||||
let result = method.invoke(this.get(), params)
|
let result = method.invoke(this.get(), params);
|
||||||
return result && on(result)
|
return result && on(result);
|
||||||
}
|
};
|
||||||
|
|
||||||
get(): any
|
get(...args): Reflect | any {
|
||||||
get(index: number, declared?: boolean): Reflect
|
return args.length === 1 ? this.field(args[0]) : this.obj;
|
||||||
get(prop: string): Reflect
|
};
|
||||||
get(param?: string | number, declared: boolean = true): Reflect | any {
|
|
||||||
if (param == undefined || param == null) return this.obj
|
|
||||||
if (typeof param == "number") {
|
|
||||||
return on(accessible(this.fields(declared)[param]).get(this.obj))
|
|
||||||
}
|
|
||||||
if (typeof param == "string") {
|
|
||||||
return this.field(param)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
set(name: any, value: any): Reflect {
|
// noinspection JSUnusedGlobalSymbols
|
||||||
accessible(declaredField(this.class, name)).set(this.obj, value)
|
set(name, value): Reflect {
|
||||||
return this
|
accessible(declaredField(this.class, name)).set(this.obj, value);
|
||||||
}
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
create(...args): Reflect {
|
create(...args): Reflect {
|
||||||
return on(declaredConstructor(this.class, args).newInstance(args))
|
return on(declaredConstructor(this.class, args).newInstance(args));
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get an array of types for an array of objects
|
* Get an array of types for an array of objects
|
||||||
*/
|
*/
|
||||||
function types(values: any[], def?: any) {
|
function types(values, def?) {
|
||||||
if (values === null) {
|
if (values === null) {
|
||||||
return []
|
return [];
|
||||||
}
|
}
|
||||||
let result: java.lang.Class[] = []
|
let result: any[] = [];
|
||||||
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class))
|
values.forEach(t => result.push((t || def) ? JavaObject.class : t instanceof JavaClass ? t : t.class));
|
||||||
return result
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
function accessible<T extends java.lang.reflect.AccessibleObject>(accessible: T): T {
|
function accessible(accessible) {
|
||||||
if (accessible === null) {
|
if (accessible === null) {
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
if (!accessible.isAccessible()) {
|
if (!accessible.isAccessible()) {
|
||||||
accessible.setAccessible(true)
|
accessible.setAccessible(true);
|
||||||
}
|
}
|
||||||
return accessible
|
return accessible;
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredConstructor(clazz, param) {
|
function declaredConstructor(clazz, param) {
|
||||||
let constructor
|
let constructor;
|
||||||
try {
|
try {
|
||||||
constructor = clazz.getDeclaredConstructor(types(param))
|
constructor = clazz.getDeclaredConstructor(types(param));
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
try {
|
try {
|
||||||
constructor = clazz.getDeclaredConstructor(types(param, true))
|
constructor = clazz.getDeclaredConstructor(types(param, true));
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
constructor = clazz.getDeclaredConstructors()[0]
|
constructor = clazz.getDeclaredConstructors()[0];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return accessible(constructor)
|
return accessible(constructor);
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredField(clazz: java.lang.Class, name: string | java.lang.String) {
|
function declaredField(clazz, name) {
|
||||||
if (!clazz) { throw Error(`target class can't be ${clazz}!`) }
|
if (!clazz) { throw Error(`target class can't be ${clazz}!`) }
|
||||||
let target = clazz
|
let target = clazz;
|
||||||
let field = null
|
let field = null;
|
||||||
// noinspection JSUnresolvedVariable
|
// noinspection JSUnresolvedVariable
|
||||||
while (target !== JavaObject.class) {
|
while (target !== JavaObject.class) {
|
||||||
try {
|
try {
|
||||||
field = target.getDeclaredField(name)
|
field = target.getDeclaredField(name);
|
||||||
if (field !== null) { break }
|
if (field !== null) { break; }
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (target === undefined) { break }
|
if (target === undefined) { break; }
|
||||||
target = target.getSuperclass()
|
target = target.getSuperclass();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (field === null) {
|
if (field === null) {
|
||||||
throw new NoSuchFieldException(name + " is not found in " + clazz.getName())
|
throw new NoSuchFieldException(name + " is not found in " + clazz.name);
|
||||||
}
|
}
|
||||||
return field
|
return field;
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredMethod(clazz: java.lang.Class, name: string, ...clazzs: any[]): java.lang.reflect.Method {
|
function declaredMethod(clazz, name, clazzs) {
|
||||||
let key = clazz.getName() + '.' + name + ':' + (clazzs || []).join(':')
|
let key = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
|
||||||
if (!methodCache[key]) {
|
if (!methodCache[key]) {
|
||||||
try {
|
try {
|
||||||
methodCache[key] = clazz.getMethod(name, clazzs as any)
|
methodCache[key] = clazz.getMethod(name, clazzs);
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
try {
|
try {
|
||||||
methodCache[key] = clazz.getDeclaredMethod(name, clazzs as any)
|
methodCache[key] = clazz.getDeclaredMethod(name, clazzs);
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
for (const m of Java.from(declaredMethods(clazz))) {
|
for (const m of Java.from(declaredMethods(clazz))) {
|
||||||
if (m.name == name) {
|
if (m.name == name) {
|
||||||
methodCache[key] = m
|
methodCache[key] = m;
|
||||||
break
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return methodCache[key]
|
return methodCache[key];
|
||||||
}
|
}
|
||||||
|
|
||||||
function declaredMethods(clazz) {
|
function declaredMethods(clazz) {
|
||||||
return clazz.declaredMethods
|
return clazz.declaredMethods;
|
||||||
}
|
}
|
||||||
|
|
||||||
let classMethodsCache: any[] = []
|
let classMethodsCache: any[] = [];
|
||||||
|
|
||||||
function mapToObject(javaObj) {
|
function mapToObject(javaObj) {
|
||||||
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
if (!javaObj || !javaObj.class) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
||||||
let target = {}
|
let target = {};
|
||||||
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t))
|
getJavaObjectMethods(javaObj).forEach(t => mapMethod(target, javaObj, t));
|
||||||
return target
|
return target;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getJavaObjectMethods(javaObj) {
|
function getJavaObjectMethods(javaObj) {
|
||||||
let className = javaObj.class.name
|
let className = javaObj.class.name;
|
||||||
if (!classMethodsCache[className]) {
|
if (!classMethodsCache[className]) {
|
||||||
let names: any[] = []
|
let names: any[] = [];
|
||||||
let methods = javaObj.class.methods
|
let methods = javaObj.class.methods;
|
||||||
for (let i in methods) {
|
for (let i in methods) {
|
||||||
names.push(methods[i].name)
|
names.push(methods[i].name);
|
||||||
}
|
}
|
||||||
classMethodsCache[className] = names
|
classMethodsCache[className] = names;
|
||||||
}
|
}
|
||||||
return classMethodsCache[className]
|
return classMethodsCache[className];
|
||||||
}
|
}
|
||||||
|
|
||||||
function mapMethod(target, source, name) {
|
function mapMethod(target, source, name) {
|
||||||
target[name] = function __SimpleDynamicMethod__(...args) {
|
target[name] = function __SimpleDynamicMethod__(...args) {
|
||||||
if (args.length > 0) {
|
if (args.length > 0) {
|
||||||
return source[name](args)
|
return source[name](args);
|
||||||
} else {
|
} else {
|
||||||
return source[name]()
|
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 = {
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
const Thread = Java.type('java.lang.Thread')
|
|
||||||
const ThreadGroup = Java.type("java.lang.ThreadGroup")
|
|
||||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
|
||||||
const ThreadPoolExecutor = Java.type('java.util.concurrent.ThreadPoolExecutor')
|
|
||||||
const LinkedBlockingQueue = Java.type("java.util.concurrent.LinkedBlockingQueue")
|
|
||||||
|
|
||||||
interface ThreadPoolConfig {
|
|
||||||
corePoolSize?: number
|
|
||||||
maximumPoolSize?: number
|
|
||||||
keepAliveTime?: number
|
|
||||||
workQueueSize?: number
|
|
||||||
groupName: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export default {
|
|
||||||
create(config: ThreadPoolConfig): java.util.concurrent.ThreadPoolExecutor {
|
|
||||||
let threadCount = new AtomicInteger(0)
|
|
||||||
config = {
|
|
||||||
corePoolSize: 10,
|
|
||||||
maximumPoolSize: 100,
|
|
||||||
keepAliveTime: 60,
|
|
||||||
workQueueSize: 500,
|
|
||||||
...config
|
|
||||||
}
|
|
||||||
return new ThreadPoolExecutor(
|
|
||||||
config.corePoolSize, config.maximumPoolSize, config.keepAliveTime, Packages.java.util.concurrent.TimeUnit.SECONDS,
|
|
||||||
new LinkedBlockingQueue(config.workQueueSize),
|
|
||||||
(run: any) => new Thread(new ThreadGroup(config.groupName), run, config.groupName + "-" + threadCount.incrementAndGet()),
|
|
||||||
new ThreadPoolExecutor.CallerRunsPolicy()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/compile",
|
"name": "@ccms/compile",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript compile package",
|
"description": "MiaoScript compile package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,6 +21,6 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/container",
|
"name": "@ccms/container",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript container package",
|
"description": "MiaoScript container package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,11 +21,10 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"inversify": "^5.0.1",
|
"inversify": "^5.0.1",
|
||||||
"inversify-binding-decorators": "^4.0.0",
|
"inversify-binding-decorators": "^4.0.0"
|
||||||
"@ccms/nashorn": "^0.7.0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
export namespace ioc {
|
|
||||||
export const Autowired = Symbol('Autowired')
|
|
||||||
export const Resource = Symbol('Resource')
|
|
||||||
export const JavaClass = Symbol('JavaClass')
|
|
||||||
export const JavaInstance = Symbol('JavaInstance')
|
|
||||||
export const JavaStaticClass = Symbol('JavaStaticClass')
|
|
||||||
}
|
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import { interfaces, Container } from "inversify"
|
import { interfaces, Container } from "inversify";
|
||||||
|
|
||||||
let _container: Container
|
let _container: Container;
|
||||||
|
|
||||||
const ContainerInstance = Symbol.for("@ccms/ioc:Container")
|
const ContainerInstance = Symbol.for("@ccms/ioc:Container");
|
||||||
const INJECTION = Symbol.for("INJECTION")
|
const INJECTION = Symbol.for("INJECTION");
|
||||||
|
|
||||||
function _proxyGetter(
|
function _proxyGetter(
|
||||||
proto: any,
|
proto: any,
|
||||||
@@ -13,17 +13,17 @@ function _proxyGetter(
|
|||||||
) {
|
) {
|
||||||
function getter(this: object) {
|
function getter(this: object) {
|
||||||
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
|
if (doCache && !Reflect.hasMetadata(INJECTION, this, key)) {
|
||||||
Reflect.defineMetadata(INJECTION, resolve(), this, key)
|
Reflect.defineMetadata(INJECTION, resolve(), this, key);
|
||||||
}
|
}
|
||||||
if (Reflect.hasMetadata(INJECTION, this, key)) {
|
if (Reflect.hasMetadata(INJECTION, this, key)) {
|
||||||
return Reflect.getMetadata(INJECTION, this, key)
|
return Reflect.getMetadata(INJECTION, this, key);
|
||||||
} else {
|
} else {
|
||||||
return resolve()
|
return resolve();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function setter(this: object, newVal: any) {
|
function setter(this: object, newVal: any) {
|
||||||
Reflect.defineMetadata(INJECTION, newVal, this, key)
|
Reflect.defineMetadata(INJECTION, newVal, this, key);
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.defineProperty(proto, key, {
|
Object.defineProperty(proto, key, {
|
||||||
@@ -31,63 +31,63 @@ function _proxyGetter(
|
|||||||
enumerable: true,
|
enumerable: true,
|
||||||
get: getter,
|
get: getter,
|
||||||
set: setter
|
set: setter
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function initContainer(container: Container) {
|
function initContainer(container: Container) {
|
||||||
Reflect.defineMetadata(ContainerInstance, container, Reflect)
|
Reflect.defineMetadata(ContainerInstance, container, Reflect);
|
||||||
return _container = container
|
_container = container;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getContainer(): Container {
|
function getContainer(): Container {
|
||||||
return _container || initContainer(new Container())
|
return _container || Reflect.getMetadata(ContainerInstance, Reflect)
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePropertyInjectDecorator(doCache: boolean) {
|
function makePropertyInjectDecorator(doCache: boolean) {
|
||||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||||
return function (proto: any, key: string): void {
|
return function(proto: any, key: string): void {
|
||||||
let resolve = () => {
|
let resolve = () => {
|
||||||
return getContainer().get(serviceIdentifier)
|
return getContainer().get(serviceIdentifier);
|
||||||
}
|
};
|
||||||
_proxyGetter(proto, key, resolve, doCache)
|
_proxyGetter(proto, key, resolve, doCache);
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePropertyInjectNamedDecorator(doCache: boolean) {
|
function makePropertyInjectNamedDecorator(doCache: boolean) {
|
||||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>, named: string) {
|
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>, named: string) {
|
||||||
return function (proto: any, key: string): void {
|
return function(proto: any, key: string): void {
|
||||||
let resolve = () => {
|
let resolve = () => {
|
||||||
return getContainer().getNamed(serviceIdentifier, named)
|
return getContainer().getNamed(serviceIdentifier, named);
|
||||||
}
|
};
|
||||||
_proxyGetter(proto, key, resolve, doCache)
|
_proxyGetter(proto, key, resolve, doCache);
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePropertyInjectTaggedDecorator(doCache: boolean) {
|
function makePropertyInjectTaggedDecorator(doCache: boolean) {
|
||||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>, key: string, value: any) {
|
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>, key: string, value: any) {
|
||||||
return function (proto: any, propertyName: string): void {
|
return function(proto: any, propertyName: string): void {
|
||||||
let resolve = () => {
|
let resolve = () => {
|
||||||
return getContainer().getTagged(serviceIdentifier, key, value)
|
return getContainer().getTagged(serviceIdentifier, key, value);
|
||||||
}
|
};
|
||||||
_proxyGetter(proto, propertyName, resolve, doCache)
|
_proxyGetter(proto, propertyName, resolve, doCache);
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePropertyMultiInjectDecorator(doCache: boolean) {
|
function makePropertyMultiInjectDecorator(doCache: boolean) {
|
||||||
return function (serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
return function(serviceIdentifier: interfaces.ServiceIdentifier<any>) {
|
||||||
return function (proto: any, key: string): void {
|
return function(proto: any, key: string): void {
|
||||||
let resolve = () => {
|
let resolve = () => {
|
||||||
return getContainer().getAll(serviceIdentifier)
|
return getContainer().getAll(serviceIdentifier);
|
||||||
}
|
};
|
||||||
_proxyGetter(proto, key, resolve, doCache)
|
_proxyGetter(proto, key, resolve, doCache);
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
let doCache = true
|
let doCache = true;
|
||||||
|
|
||||||
let lazyInject = makePropertyInjectDecorator(doCache)
|
let lazyInject = makePropertyInjectDecorator(doCache)
|
||||||
let lazyInjectNamed = makePropertyInjectNamedDecorator(doCache)
|
let lazyInjectNamed = makePropertyInjectNamedDecorator(doCache)
|
||||||
@@ -102,4 +102,4 @@ export {
|
|||||||
lazyInjectNamed,
|
lazyInjectNamed,
|
||||||
lazyInjectTagged,
|
lazyInjectTagged,
|
||||||
lazyMultiInject
|
lazyMultiInject
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -1,91 +1,25 @@
|
|||||||
/// <reference types="@ccms/nashorn" />
|
import "reflect-metadata";
|
||||||
|
import { initContainer } from './decorators'
|
||||||
|
import { interfaces, Container } from 'inversify';
|
||||||
|
import { fluentProvide } from 'inversify-binding-decorators';
|
||||||
|
|
||||||
import "reflect-metadata"
|
const provideNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
|
||||||
import { initContainer, getContainer } from './decorators'
|
return fluentProvide(identifier).whenTargetNamed(name).done();
|
||||||
import { interfaces, Container } from 'inversify'
|
};
|
||||||
import { fluentProvide } from 'inversify-binding-decorators'
|
|
||||||
import { ioc } from "./constants"
|
|
||||||
|
|
||||||
/**
|
const provideSingleton = (identifier: interfaces.ServiceIdentifier<any>) => {
|
||||||
* 注册一个命名对象
|
return fluentProvide(identifier).inSingletonScope().done();
|
||||||
* @param identifier 标识符
|
};
|
||||||
* @param name 名称
|
|
||||||
*/
|
|
||||||
export const provideNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
|
|
||||||
return fluentProvide(identifier).whenTargetNamed(name).done()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
const DefaultContainer = new Container();
|
||||||
* 注册一个单例对象
|
initContainer(DefaultContainer);
|
||||||
* @param identifier 标识符
|
|
||||||
*/
|
|
||||||
export const provideSingleton = (identifier: interfaces.ServiceIdentifier<any>) => {
|
|
||||||
return fluentProvide(identifier).inSingletonScope().done()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 注册一个单例对象
|
|
||||||
* @param identifier 标识符
|
|
||||||
*/
|
|
||||||
export const provideSingletonNamed = (identifier: interfaces.ServiceIdentifier<any>, name: string) => {
|
|
||||||
return fluentProvide(identifier).inSingletonScope().whenTargetNamed(name).done()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获得一个 java.lang.Class
|
|
||||||
* @param className Java全类名
|
|
||||||
*/
|
|
||||||
export const JavaClass = (className: string) => {
|
|
||||||
return function (target: any, propertyKey: string, index?: number) {
|
|
||||||
try { target[propertyKey] = Java.type(className).class; return } catch (error) { }
|
|
||||||
try { target[propertyKey] = base.getClass(className); return } catch (error) { }
|
|
||||||
console.warn('JavaClass Inject target', target, 'propertyKey', propertyKey, 'failed!')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获得一个JS的Java类
|
|
||||||
* @param className Java 全类名
|
|
||||||
*/
|
|
||||||
export const JSClass = (className: string) => {
|
|
||||||
return function (target: any, propertyKey: string, index?: number) {
|
|
||||||
try { target[propertyKey] = Java.type(className); return } catch (error) { }
|
|
||||||
try { target[propertyKey] = base.getClass(className).static; return } catch (error) { }
|
|
||||||
console.warn('JSClass Inject target', target, 'propertyKey', propertyKey, 'failed!')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 自动注入实例由平台实现
|
|
||||||
* @param className 类名
|
|
||||||
*/
|
|
||||||
export const Autowired = (className?: string | any) => {
|
|
||||||
return function (target: any, propertyKey: string) {
|
|
||||||
target[propertyKey] = getContainer().getNamed(ioc.Autowired, className || propertyKey)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 自动注入资源由平台实现
|
|
||||||
* @param className 类名
|
|
||||||
*/
|
|
||||||
export const Resource = (resourceName?: string | any) => {
|
|
||||||
return function (target: any, propertyKey: string) {
|
|
||||||
target[propertyKey] = getContainer().getNamed(ioc.Resource, resourceName || propertyKey)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const reduceMetadata = (ctx: interfaces.Context): any => {
|
|
||||||
return ctx.currentRequest.target.metadata.reduce((result, entry, index) => {
|
|
||||||
result[entry.key] = entry.value
|
|
||||||
return result
|
|
||||||
}, {})
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DefaultContainer = new Container()
|
|
||||||
initContainer(DefaultContainer)
|
|
||||||
|
|
||||||
export * from 'inversify'
|
export * from 'inversify'
|
||||||
export * from './constants'
|
|
||||||
export * from './decorators'
|
export * from './decorators'
|
||||||
export * from 'inversify-binding-decorators'
|
export * from 'inversify-binding-decorators'
|
||||||
|
export {
|
||||||
|
fluentProvide,
|
||||||
|
provideNamed,
|
||||||
|
provideSingleton,
|
||||||
|
DefaultContainer
|
||||||
|
};
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/core",
|
"name": "@ccms/core",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,11 +21,11 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.7.0",
|
"@ccms/api": "^0.6.0",
|
||||||
"@ccms/container": "^0.7.0"
|
"@ccms/container": "^0.6.0"
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,116 +1,103 @@
|
|||||||
let containerStartTime = Date.now()
|
let containerStartTime = Date.now();
|
||||||
console.i18n("ms.core.ioc.initialize", { scope: global.scope })
|
console.i18n("ms.core.ioc.initialize", { scope: global.scope });
|
||||||
import { plugin, server, task, constants } from '@ccms/api'
|
import { plugin, server, task, constants } from '@ccms/api'
|
||||||
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule } from '@ccms/container'
|
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule } from '@ccms/container'
|
||||||
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
|
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
|
||||||
import http from '@ccms/common/dist/http'
|
|
||||||
import { EventEmitter } from 'events'
|
|
||||||
|
|
||||||
@provideSingleton(MiaoScriptCore)
|
@provideSingleton(MiaoScriptCore)
|
||||||
class MiaoScriptCore {
|
class MiaoScriptCore {
|
||||||
@inject(server.Console)
|
@inject(server.Console)
|
||||||
private Console: Console
|
private Console: Console;
|
||||||
@inject(task.TaskManager)
|
@inject(task.TaskManager)
|
||||||
private taskManager: task.TaskManager
|
private taskManager: task.TaskManager;
|
||||||
@inject(plugin.PluginFolder)
|
@inject(plugin.PluginFolder)
|
||||||
private pluginFolder: string
|
private pluginFolder: string;
|
||||||
@inject(plugin.PluginManager)
|
@inject(plugin.PluginManager)
|
||||||
private pluginManager: plugin.PluginManager
|
private pluginManager: plugin.PluginManager;
|
||||||
|
|
||||||
enable() {
|
enable() {
|
||||||
this.loadServerConsole()
|
this.loadServerConsole();
|
||||||
this.loadTaskFunction()
|
this.loadTaskFunction();
|
||||||
global.level = "TRACE"
|
global.level = "TRACE"
|
||||||
this.loadPlugins()
|
this.loadPlugins();
|
||||||
return () => this.disable()
|
return () => this.disable();
|
||||||
}
|
}
|
||||||
|
|
||||||
loadServerConsole() {
|
loadServerConsole() {
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
global.setGlobal('console', new this.Console(), { writable: false, configurable: false })
|
global.setGlobal('console', new this.Console())
|
||||||
}
|
}
|
||||||
|
|
||||||
loadTaskFunction() {
|
loadTaskFunction() {
|
||||||
global.setGlobal('setTimeout', (func: Function, tick: number, ...args: any[]) => {
|
global.setGlobal('setTimeout', (func: Function, tick: number, async: boolean = false) => this.taskManager.create(func).later(tick).async(async).submit())
|
||||||
return this.taskManager.create(func).later(tick).submit(...args)
|
global.setGlobal('setInterval', (func: Function, tick: number, async: boolean = false) => this.taskManager.create(func).timer(tick).async(async).submit())
|
||||||
}, { writable: false, configurable: false })
|
|
||||||
global.setGlobal('setInterval', (func: Function, tick: number, ...args: any[]) => {
|
|
||||||
return this.taskManager.create(func).timer(tick).submit(...args)
|
|
||||||
}, { writable: false, configurable: false })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
loadPlugins() {
|
loadPlugins() {
|
||||||
let loadPluginStartTime = new Date().getTime()
|
let loadPluginStartTime = new Date().getTime()
|
||||||
console.i18n("ms.core.plugin.initialize")
|
console.i18n("ms.core.plugin.initialize")
|
||||||
this.pluginManager.scan(this.pluginFolder)
|
this.pluginManager.scan(this.pluginFolder);
|
||||||
this.pluginManager.build()
|
this.pluginManager.build();
|
||||||
this.pluginManager.load(this.pluginManager.getPlugins())
|
this.pluginManager.load();
|
||||||
this.pluginManager.enable(this.pluginManager.getPlugins())
|
this.pluginManager.enable();
|
||||||
console.i18n("ms.core.plugin.completed", { time: (new Date().getTime() - loadPluginStartTime) / 1000 })
|
console.i18n("ms.core.plugin.completed", { time: (new Date().getTime() - loadPluginStartTime) / 1000 })
|
||||||
}
|
}
|
||||||
|
|
||||||
disable() {
|
disable() {
|
||||||
console.i18n("ms.core.engine.disable")
|
console.i18n("ms.core.engine.disable")
|
||||||
this.pluginManager.disable(this.pluginManager.getPlugins())
|
this.pluginManager.disable();
|
||||||
this.taskManager.disable()
|
this.taskManager.disable();
|
||||||
process.emit('exit', 0)
|
//@ts-ignore
|
||||||
process.exit(0)
|
require.disable()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function detectServer(): constants.ServerType {
|
function detectServer(): constants.ServerType {
|
||||||
try {
|
try {
|
||||||
Java.type("org.bukkit.Bukkit")
|
Java.type("org.bukkit.Bukkit");
|
||||||
return constants.ServerType.Bukkit
|
return constants.ServerType.Bukkit
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Java.type("org.spongepowered.api.Sponge")
|
Java.type("org.spongepowered.api.Sponge");
|
||||||
return constants.ServerType.Sponge
|
return constants.ServerType.Sponge
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Java.type("cn.nukkit.Nukkit")
|
Java.type("cn.nukkit.Nukkit");
|
||||||
return constants.ServerType.Nukkit
|
return constants.ServerType.Nukkit
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Java.type("net.md_5.bungee.api.ProxyServer")
|
Java.type("net.md_5.bungee.api.ProxyServer");
|
||||||
return constants.ServerType.Bungee
|
return constants.ServerType.Bungee
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
}
|
}
|
||||||
try {
|
|
||||||
Java.type("org.springframework.boot.SpringApplication")
|
|
||||||
return constants.ServerType.Spring
|
|
||||||
} catch (ex) {
|
|
||||||
}
|
|
||||||
throw Error('Unknow Server Type...')
|
throw Error('Unknow Server Type...')
|
||||||
}
|
}
|
||||||
|
|
||||||
function initialize() {
|
function initialize() {
|
||||||
// @ts-ignore
|
|
||||||
try { engineLoad({ script: http.get("http://ms.yumc.pw/api/plugin/download/name/initialize"), name: 'core/initialize.js' }) } catch (error) { console.debug(error) }
|
|
||||||
try {
|
try {
|
||||||
let corePackageStartTime = new Date().getTime()
|
let corePackageStartTime = new Date().getTime()
|
||||||
container.bind(ContainerInstance).toConstantValue(container)
|
container.bind(ContainerInstance).toConstantValue(container);
|
||||||
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance())
|
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance());
|
||||||
container.bind(plugin.PluginFolder).toConstantValue('plugins')
|
container.bind(plugin.PluginFolder).toConstantValue('plugins');
|
||||||
let type = detectServer()
|
let type = detectServer();
|
||||||
console.i18n("ms.core.initialize.detect", { scope: global.scope, type })
|
console.i18n("ms.core.initialize.detect", { scope: global.scope, type });
|
||||||
container.bind(server.ServerType).toConstantValue(type)
|
container.bind(server.ServerType).toConstantValue(type);
|
||||||
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
|
console.i18n("ms.core.package.initialize", { scope: global.scope, type });
|
||||||
require(`${global.scope}/${type}`).default(container)
|
require(`${global.scope}/${type}`).default(container);
|
||||||
require(`${global.scope}/plugin`)
|
require(`${global.scope}/plugin`)
|
||||||
container.load(buildProviderModule())
|
container.load(buildProviderModule());
|
||||||
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 })
|
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 });
|
||||||
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
||||||
console.i18n("ms.core.engine.completed", { time: (Date.now() - global.NashornEngineStartTime) / 1000 })
|
console.i18n("ms.core.engine.completed", { time: (Date.now() - global.NashornEngineStartTime) / 1000 });
|
||||||
return disable
|
return disable;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.i18n("ms.core.initialize.error", { error })
|
console.i18n("ms.core.initialize.error", { error });
|
||||||
console.ex(error)
|
console.ex(error)
|
||||||
return () => console.i18n('ms.core.engine.disable.abnormal')
|
return () => console.i18n('ms.core.engine.disable.abnormal')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default initialize()
|
export default initialize();
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "@ccms/database",
|
|
||||||
"version": "0.7.0",
|
|
||||||
"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",
|
|
||||||
"scripts": {
|
|
||||||
"clean": "rimraf dist",
|
|
||||||
"watch": "tsc --watch",
|
|
||||||
"build": "yarn clean && tsc",
|
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"reflect-metadata": "^0.1.13",
|
|
||||||
"rimraf": "^3.0.2",
|
|
||||||
"typescript": "^3.9.2"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@ccms/api": "^0.7.0",
|
|
||||||
"@ccms/container": "^0.7.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
export const METADATA_KEY = {
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
/// <reference types="@ccms/types/dist/typings/spring" />
|
|
||||||
|
|
||||||
import { Model } from './model'
|
|
||||||
|
|
||||||
const HikariDataSource = Java.type('com.zaxxer.hikari.HikariDataSource')
|
|
||||||
const HikariConfig = Java.type('com.zaxxer.hikari.HikariConfig')
|
|
||||||
const JdbcTemplate = Java.type('org.springframework.jdbc.core.JdbcTemplate')
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 数据库配置
|
|
||||||
*/
|
|
||||||
export interface DataBaseConfig {
|
|
||||||
/**
|
|
||||||
* 数据库连接串
|
|
||||||
*/
|
|
||||||
url: string | javax.sql.DataSource
|
|
||||||
/**
|
|
||||||
* 数据库驱动
|
|
||||||
*/
|
|
||||||
driverClassName?: string
|
|
||||||
/**
|
|
||||||
* 用户名
|
|
||||||
*/
|
|
||||||
username?: string
|
|
||||||
/**
|
|
||||||
* 密码
|
|
||||||
*/
|
|
||||||
password?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 数据库封装类
|
|
||||||
*/
|
|
||||||
export class DataBase {
|
|
||||||
private dataSource: javax.sql.DataSource
|
|
||||||
private jdbcTemplate: org.springframework.jdbc.core.JdbcTemplate
|
|
||||||
|
|
||||||
constructor(dbConfig: DataBaseConfig) {
|
|
||||||
if (!dbConfig.url) { throw new Error('DataBase url can\'t be null!') }
|
|
||||||
this.createDataSource(dbConfig)
|
|
||||||
this.initialize()
|
|
||||||
}
|
|
||||||
|
|
||||||
private createDataSource(dbConfig: DataBaseConfig) {
|
|
||||||
if (typeof dbConfig.url === "string") {
|
|
||||||
if (!dbConfig.username || !dbConfig.password) {
|
|
||||||
throw new Error('DataBase username or password can\'t be null!')
|
|
||||||
}
|
|
||||||
let config = new HikariConfig()
|
|
||||||
if (dbConfig.driverClassName) {
|
|
||||||
config.setDriverClassName(dbConfig.driverClassName)
|
|
||||||
}
|
|
||||||
config.setUsername(dbConfig.username)
|
|
||||||
config.setPassword(dbConfig.password)
|
|
||||||
config.setJdbcUrl(dbConfig.url)
|
|
||||||
this.dataSource = new HikariDataSource(config)
|
|
||||||
} else {
|
|
||||||
this.dataSource = dbConfig.url
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private initialize() {
|
|
||||||
this.jdbcTemplate = new JdbcTemplate(this.dataSource)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 执行SQL查询
|
|
||||||
* @param sql SQL语句
|
|
||||||
*/
|
|
||||||
query<T>(sql: string, ...args: any[]): Array<T> {
|
|
||||||
let startTime = Date.now()
|
|
||||||
let result = Java.from(this.jdbcTemplate.queryForList(sql, args))
|
|
||||||
console.debug(java.lang.String.format(`\n[DB] query \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 执行SQL更新
|
|
||||||
* @param sql SQL语句
|
|
||||||
*/
|
|
||||||
update(sql: string, ...args: any[]): number {
|
|
||||||
let startTime = Date.now()
|
|
||||||
let result = this.jdbcTemplate.update(sql, args)
|
|
||||||
console.debug(java.lang.String.format(`\n[DB] update \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
close() {
|
|
||||||
//@ts-ignore
|
|
||||||
this.dataSource.close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import 'reflect-metadata'
|
|
||||||
|
|
||||||
export function id() {
|
|
||||||
return (target: Object, propertyKey: string | symbol) => void {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
/// <reference types="@ccms/nashorn" />
|
|
||||||
/// <reference types="@ccms/types/dist/typings/jdk/index" />
|
|
||||||
|
|
||||||
export * from './database'
|
|
||||||
export * from './manager'
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
import { plugin, database } from '@ccms/api'
|
|
||||||
import { provideSingleton, inject, postConstruct } from '@ccms/container'
|
|
||||||
import { DataBase, DataBaseConfig } from './database'
|
|
||||||
|
|
||||||
@provideSingleton(database.DataBaseManager)
|
|
||||||
export class DataBaseManager {
|
|
||||||
@inject(plugin.PluginInstance)
|
|
||||||
private instance: any
|
|
||||||
|
|
||||||
private beanFactory: any
|
|
||||||
private mainDatabase: DataBase
|
|
||||||
private databases: { [key: string]: DataBase } = {}
|
|
||||||
|
|
||||||
@postConstruct()
|
|
||||||
initialize() {
|
|
||||||
try {
|
|
||||||
this.beanFactory = this.instance.getAutowireCapableBeanFactory()
|
|
||||||
let mainDatasource = this.beanFactory.getBean(Packages.javax.sql.DataSource.class)
|
|
||||||
this.mainDatabase = new DataBase({ url: mainDatasource })
|
|
||||||
} catch (error) {
|
|
||||||
console.ex(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获得主数据库
|
|
||||||
* Get MainDatabase
|
|
||||||
*/
|
|
||||||
getMainDatabase() {
|
|
||||||
return this.mainDatabase
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 创建数据库
|
|
||||||
* Create A Database Instance
|
|
||||||
* @param name 数据库名称 用于代码 database Name use at code
|
|
||||||
* @param config 数据库配置
|
|
||||||
*/
|
|
||||||
createDatabase(name: string, config: DataBaseConfig) {
|
|
||||||
Java.synchronized(() => {
|
|
||||||
if (this.databases[name]) return this.databases[name]
|
|
||||||
return this.databases[name] = new DataBase(config)
|
|
||||||
}, this.databases)()
|
|
||||||
}
|
|
||||||
|
|
||||||
getDatabase(name: string) {
|
|
||||||
return this.databases[name]
|
|
||||||
}
|
|
||||||
|
|
||||||
disable() {
|
|
||||||
Object.values(this.databases).forEach((ds) => ds?.close())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { DataBase } from "./database"
|
|
||||||
|
|
||||||
export class Model<T> {
|
|
||||||
constructor(private database: DataBase) {
|
|
||||||
|
|
||||||
}
|
|
||||||
queryForList(): Array<T> {
|
|
||||||
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"extends": "../../tsconfig.json",
|
|
||||||
"compilerOptions": {
|
|
||||||
"baseUrl": "src",
|
|
||||||
"outDir": "dist"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
ms.i18n.completed: "Internationalization component initialization completed. Current Language: English"
|
|
||||||
ms.ployfill.initialize: "Initialization Java Nashorn ployfill. Please wait..."
|
ms.ployfill.initialize: "Initialization Java Nashorn ployfill. Please wait..."
|
||||||
ms.ployfill.completed: "Java Nashorn ployfill loading completed... Cost ({time}s)!"
|
ms.ployfill.completed: "Java Nashorn ployfill loading completed... Cost ({time}s)!"
|
||||||
|
|
||||||
@@ -39,10 +38,7 @@ ms.plugin.manager.stage.exec.error: "§6Plugin §b{plugin} §6exec §d{executor}
|
|||||||
ms.plugin.manager.stage.load: "Loading"
|
ms.plugin.manager.stage.load: "Loading"
|
||||||
ms.plugin.manager.stage.enable: "Enabling"
|
ms.plugin.manager.stage.enable: "Enabling"
|
||||||
ms.plugin.manager.stage.disable: "Disabling"
|
ms.plugin.manager.stage.disable: "Disabling"
|
||||||
ms.plugin.manager.build.error: "§6Load Plugin From §b{file} §6failed. §4Error: §c{error}"
|
|
||||||
ms.plugin.manager.build.update: "Auto Update Plugin {name} ..."
|
ms.plugin.manager.build.update: "Auto Update Plugin {name} ..."
|
||||||
ms.plugin.manager.build.not.extends: "§4Found error plugin §b{source} §4it's not extends interfaces.Plugin, the plugin will be ignore!"
|
ms.plugin.manager.build.not.extends: "§4Found error plugin §b{source} §4it's not extends interfaces.Plugin, the plugin will be ignore!"
|
||||||
ms.plugin.manager.build.exists: "§4Found duplicate plugin §b{exists} §4and §b{source}§4. the first plugin will be ignore!"
|
ms.plugin.manager.build.exists: "§4Found duplicate plugin §b{exists} §4and §b{source}§4. the first plugin will be ignore!"
|
||||||
ms.plugin.manager.config.load.error: "[{plugin}] config {name}.{format} load failed. Error: {error}"
|
|
||||||
ms.plugin.manager.config.save.error: "[{plugin}] config {name}.{format} save failed. Error: {error}"
|
|
||||||
ms.plugin.manager.config.save.default: "[{plugin}] config {name}.{format} not exists. auto create from default variable..."
|
ms.plugin.manager.config.save.default: "[{plugin}] config {name}.{format} not exists. auto create from default variable..."
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
ms.i18n.completed: "国际化组件 初始化完成 当前语言: 简体中文"
|
|
||||||
ms.ployfill.initialize: "加载 Java Nashorn 补丁. 请稍候..."
|
ms.ployfill.initialize: "加载 Java Nashorn 补丁. 请稍候..."
|
||||||
ms.ployfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
|
ms.ployfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
|
||||||
|
|
||||||
@@ -39,10 +38,7 @@ ms.plugin.manager.stage.exec.error: "§6插件 §b{plugin} §6执行 §d{executo
|
|||||||
ms.plugin.manager.stage.load: "加载"
|
ms.plugin.manager.stage.load: "加载"
|
||||||
ms.plugin.manager.stage.enable: "启用"
|
ms.plugin.manager.stage.enable: "启用"
|
||||||
ms.plugin.manager.stage.disable: "关闭"
|
ms.plugin.manager.stage.disable: "关闭"
|
||||||
ms.plugin.manager.build.error: "§6从文件 §b{file} §6加载插件失败 §4错误: §c{error}"
|
|
||||||
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
|
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
|
||||||
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
|
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
|
||||||
ms.plugin.manager.build.duplicate: "§4发现已存在插件 §b{exists} §4和 §b{source}§4 存在冲突. 已存在插件将会被替换!"
|
ms.plugin.manager.build.duplicate: "§4发现已存在插件 §b{exists} §4和 §b{source}§4 存在冲突. 已存在插件将会被替换!"
|
||||||
ms.plugin.manager.config.load.error: "[{plugin}] 配置 {name}.{format} 加载失败. 错误: {error}"
|
|
||||||
ms.plugin.manager.config.save.error: "[{plugin}] 配置 {name}.{format} 保存失败. 错误: {error}"
|
|
||||||
ms.plugin.manager.config.save.default: "[{plugin}] 配置 {name}.{format} 不存在. 从默认值自动创建保存..."
|
ms.plugin.manager.config.save.default: "[{plugin}] 配置 {name}.{format} 不存在. 从默认值自动创建保存..."
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/i18n",
|
"name": "@ccms/i18n",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript i18n package",
|
"description": "MiaoScript i18n package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,10 +22,10 @@
|
|||||||
"@types/js-yaml": "^3.12.3",
|
"@types/js-yaml": "^3.12.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/nashorn": "^0.7.0",
|
"@ccms/nashorn": "^0.6.0",
|
||||||
"js-yaml": "^3.13.1"
|
"js-yaml": "^3.13.1"
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
|
|||||||
@@ -45,7 +45,6 @@ export class Translate {
|
|||||||
console.i18n = (name: string, param?: TranslateParam) => {
|
console.i18n = (name: string, param?: TranslateParam) => {
|
||||||
console.log(this.translate(name, param))
|
console.log(this.translate(name, param))
|
||||||
}
|
}
|
||||||
console.i18n('ms.i18n.completed')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
readYamlFile(dir: string, name: string) {
|
readYamlFile(dir: string, name: string) {
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
12
packages/nashorn/build.sh
Executable file
12
packages/nashorn/build.sh
Executable file
@@ -0,0 +1,12 @@
|
|||||||
|
# sponge bukkit jdk bungee nukkit
|
||||||
|
TYPE=nukkit
|
||||||
|
TARGET=../types/dist/typings
|
||||||
|
npx tsc src/build.ts --outDir dist
|
||||||
|
cd dist
|
||||||
|
rm -rf temp
|
||||||
|
mkdir -p temp
|
||||||
|
node build.js ${TYPE}
|
||||||
|
cd ../
|
||||||
|
rm -rf ${TARGET}/${TYPE}
|
||||||
|
mkdir -p ${TARGET}/${TYPE}
|
||||||
|
cp dist/temp/* ${TARGET}/${TYPE}/ -R
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/nashorn",
|
"name": "@ccms/nashorn",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,6 +22,6 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
200
packages/nashorn/src/build.ts
Normal file
200
packages/nashorn/src/build.ts
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
import * as fs from "fs";
|
||||||
|
|
||||||
|
function convertJson2TypeDefiend(infile: string, outDir: string) {
|
||||||
|
const file = infile.split(".json")[0];
|
||||||
|
const json = fs.readFileSync(`${inDir}/${file}.json`).toString();
|
||||||
|
const obj = JSON.parse(json);
|
||||||
|
const qnas: string[] = obj.qualifiedName.split(".");
|
||||||
|
let closeBuk = 0;
|
||||||
|
let temp = `declare namespace ${qnas[0]} {\n`;
|
||||||
|
closeBuk++;
|
||||||
|
const nms = qnas.slice(1, qnas.length - 1);
|
||||||
|
for (const nm of nms) {
|
||||||
|
temp += `${' '.repeat(closeBuk)}namespace ${nm.replace('function', 'function$')} {\n`;
|
||||||
|
closeBuk++;
|
||||||
|
}
|
||||||
|
let classModifier = formatClassModifier(obj.modifiers)
|
||||||
|
temp += `${' '.repeat(closeBuk)}// @ts-ignore\n`
|
||||||
|
temp += `${' '.repeat(closeBuk)}${classModifier}${qnas[qnas.length - 1]}`
|
||||||
|
let isInterface = classModifier.includes('interface')
|
||||||
|
let safeInterface = [];
|
||||||
|
for (const ifs of obj.interfaces) {
|
||||||
|
if (!ifs.qualifiedName.startsWith('java')) {
|
||||||
|
safeInterface.push(ifs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (isInterface) {
|
||||||
|
if (safeInterface.length > 0) {
|
||||||
|
temp += ' extends '
|
||||||
|
for (const ifs of safeInterface) {
|
||||||
|
temp += ifs.qualifiedName;
|
||||||
|
temp += ', '
|
||||||
|
}
|
||||||
|
temp = temp.substr(0, temp.length - 2);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
temp += `${(obj.superclass) ? (' extends ' + (obj.superclass.qualifiedName == "<any>" ? "object" : obj.superclass.qualifiedName)) : ''}`;
|
||||||
|
if (safeInterface.length > 0) {
|
||||||
|
temp += ' implements '
|
||||||
|
for (const ifs of safeInterface) {
|
||||||
|
temp += ifs.qualifiedName;
|
||||||
|
temp += ', '
|
||||||
|
}
|
||||||
|
temp = temp.substr(0, temp.length - 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
temp += ' {\n'
|
||||||
|
closeBuk++;
|
||||||
|
for (const constructor of obj.constructors) {
|
||||||
|
temp += `${formatDoc(constructor.docString, closeBuk)}${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}constructor(${formatParameters(constructor.parameters)})\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
let members = [];
|
||||||
|
|
||||||
|
let methods = '';
|
||||||
|
for (const method of obj.methods) {
|
||||||
|
let methodModifier = isInterface ? '' : replaceModifiers(method.modifiers, classModifier.includes('abstract'))
|
||||||
|
if (!whiteKey.includes(method.name)) {
|
||||||
|
if (members[method.name] && methodModifier.includes('abstract')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
members[method.name] = methodModifier;
|
||||||
|
}
|
||||||
|
methods += `${formatDoc(method.docString, closeBuk)}${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}${methodModifier} ${method.name}(${formatParameters(method.parameters)}): ${mappingType(method.returnType.type)};\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
let fields = '';
|
||||||
|
for (const field of obj.fields) {
|
||||||
|
if (members[field.name]) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
fields += `${' '.repeat(closeBuk)}// @ts-ignore\n${' '.repeat(closeBuk)}${isInterface ? '' : replaceModifiers(field.modifiers)} ${field.name}: ${mappingType(field.type ? field.type.type : "any")};\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
temp += fields + methods;
|
||||||
|
|
||||||
|
for (let index = 0; index < closeBuk; index++) {
|
||||||
|
temp += `${' '.repeat(closeBuk - index - 1)}}\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(`${outDir}/${file}.${suffix}`, temp);
|
||||||
|
return `${file}.${suffix}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatClassModifier(modifiers: string) {
|
||||||
|
let tempm = modifiers.replace('public', '').replace('static', '').replace('final', '').trim();
|
||||||
|
if (!modifiers.includes('interface')) { tempm += ' class' }
|
||||||
|
return tempm.length > 0 ? (tempm + ' ') : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDoc(doc: string, closeBuk: number) {
|
||||||
|
let middleDoc = '';
|
||||||
|
for (const line of doc.split('\n')) {
|
||||||
|
if (line.trim().length != 0) {
|
||||||
|
middleDoc += `${' '.repeat(closeBuk)} * ${line.trim()}\n`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return middleDoc.length > 0 ? `${' '.repeat(closeBuk)}/**\n${middleDoc}${' '.repeat(closeBuk)} */\n` : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function replaceModifiers(modifiers: string, absClass = false): string {
|
||||||
|
// modifiers = modifiers.replace(' final', ' readonly');
|
||||||
|
modifiers = modifiers.split(" final")[0];
|
||||||
|
modifiers = modifiers.split(" native")[0];
|
||||||
|
modifiers = modifiers.split(" volatile")[0];
|
||||||
|
modifiers = modifiers.split(" transient")[0];
|
||||||
|
modifiers = modifiers.split(" synchronized")[0];
|
||||||
|
if (!absClass) {
|
||||||
|
modifiers = modifiers.split(" abstract")[0];
|
||||||
|
}
|
||||||
|
return modifiers;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatParameters(params: any[]) {
|
||||||
|
let tempParam = '';
|
||||||
|
for (const p of params) {
|
||||||
|
tempParam += `${mappingName(p.name)}: ${mappingType(p.type ? p.type.qualifiedName : 'any')}, `
|
||||||
|
}
|
||||||
|
return tempParam.substr(0, tempParam.length - 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
const nameMap = [];
|
||||||
|
nameMap['function'] = 'func'
|
||||||
|
nameMap['in'] = 'input'
|
||||||
|
nameMap['var'] = 'variable'
|
||||||
|
|
||||||
|
function mappingName(name: string) {
|
||||||
|
if (whiteKey.includes(name)) { return name }
|
||||||
|
let outName = nameMap[name] || name || '';
|
||||||
|
return outName;
|
||||||
|
}
|
||||||
|
|
||||||
|
let whiteKey = ['shift', "map", 'filter', 'values', 'valueOf', 'toString', 'length', 'includes', 'entries', 'keys', 'join', 'fill']
|
||||||
|
|
||||||
|
const typeMap = [];
|
||||||
|
typeMap['int'] = 'number';
|
||||||
|
typeMap['int[]'] = 'number[]';
|
||||||
|
typeMap['int[][]'] = 'number[][]';
|
||||||
|
typeMap['byte'] = 'number';
|
||||||
|
typeMap['byte[]'] = 'number[]';
|
||||||
|
typeMap['double'] = 'number';
|
||||||
|
typeMap['double[]'] = 'number[]';
|
||||||
|
typeMap['short'] = 'number';
|
||||||
|
typeMap['short[]'] = 'number[]';
|
||||||
|
typeMap['float'] = 'number';
|
||||||
|
typeMap['float[]'] = 'number[]';
|
||||||
|
typeMap['long'] = 'number';
|
||||||
|
typeMap['long[]'] = 'number[]';
|
||||||
|
typeMap['<any>'] = 'any';
|
||||||
|
typeMap['char'] = 'string';
|
||||||
|
typeMap['char[]'] = 'string[]';
|
||||||
|
typeMap['java.lang.String'] = "string";
|
||||||
|
// typeMap['java.util.Date'] = 'any /*java.util.Date*/'
|
||||||
|
// typeMap['java.util.List'] = 'any[] /*java.util.List*/'
|
||||||
|
// typeMap['java.util.Set'] = 'any[] /*java.util.Set*/'
|
||||||
|
// typeMap['java.util.Collection'] = 'any[] /*java.util.Collection*/'
|
||||||
|
// typeMap['java.util.Map'] = 'Map<any, any> /*java.util.Map*/'
|
||||||
|
// Sponge
|
||||||
|
typeMap['Vectori'] = 'any /*Vector3i*/'
|
||||||
|
typeMap['Vectord'] = 'any /*Vector3d*/'
|
||||||
|
typeMap['Vectorf'] = 'any /*Vector3f*/'
|
||||||
|
typeMap['Vector2i'] = 'any /*Vector2i*/'
|
||||||
|
typeMap['Vector2d'] = 'any /*Vector2d*/'
|
||||||
|
typeMap['Vector2f'] = 'any /*Vector2f*/'
|
||||||
|
typeMap['Vector3i'] = 'any /*Vector3i*/'
|
||||||
|
typeMap['Vector3d'] = 'any /*Vector3d*/'
|
||||||
|
typeMap['Vector3f'] = 'any /*Vector3f*/'
|
||||||
|
typeMap['Type'] = 'any /*Type*/'
|
||||||
|
typeMap['Gson'] = 'any /*Gson*/'
|
||||||
|
typeMap['Logger'] = 'any /*Logger*/'
|
||||||
|
typeMap['MethodVisitor'] = 'any /*MethodVisitor*/'
|
||||||
|
typeMap['ConfigurationNode'] = 'any /*ConfigurationNode*/'
|
||||||
|
typeMap['TypeSerializerCollection'] = 'any /*TypeSerializerCollection*/'
|
||||||
|
typeMap['Quaterniond'] = 'any /*Quaterniond*/'
|
||||||
|
typeMap['Matrix2d'] = 'any /*Matrix2d*/'
|
||||||
|
typeMap['Matrix3d'] = 'any /*Matrix3d*/'
|
||||||
|
typeMap['Matrix4d'] = 'any /*Matrix4d*/'
|
||||||
|
|
||||||
|
function mappingType(type: string): string {
|
||||||
|
let outType = typeMap[type] || type || 'any';
|
||||||
|
if (outType.indexOf('.') != -1) {
|
||||||
|
if (outType.startsWith('java.') || outType.startsWith('org.') || outType.startsWith('net.') || outType.startsWith('cn.')) {
|
||||||
|
|
||||||
|
} else {
|
||||||
|
outType = `any /*${outType}*/`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return outType.replace('function', 'function$');
|
||||||
|
}
|
||||||
|
|
||||||
|
var args = process.argv.splice(2)
|
||||||
|
|
||||||
|
const suffix = 'd.ts'
|
||||||
|
const inDir = `../docs/${args[0]}`
|
||||||
|
const outDir = "./temp";
|
||||||
|
const files = fs.readdirSync(inDir);
|
||||||
|
let index = '';
|
||||||
|
for (const file of files) {
|
||||||
|
index += `/// <reference path="./${convertJson2TypeDefiend(file, outDir)}" />\n`;
|
||||||
|
}
|
||||||
|
fs.writeFileSync(`${outDir}/index.${suffix}`, index);
|
||||||
@@ -1,85 +1,75 @@
|
|||||||
declare global {
|
declare global {
|
||||||
const __FILE__: string
|
const __FILE__: string;
|
||||||
const __LINE__: number
|
const __LINE__: number;
|
||||||
const __DIR__: string
|
const __DIR__: string;
|
||||||
const Packages: any
|
let Packages: any;
|
||||||
|
|
||||||
function print(...message: any[]): void
|
function print(...message: any[]): void;
|
||||||
function load(script: string | object)
|
function load(script: string | object);
|
||||||
function loadWithNewGlobal(script: string | object)
|
function loadWithNewGlobal(script: string | object);
|
||||||
function exit(code?: number)
|
function exit(code?: number);
|
||||||
function quit(code?: number)
|
function quit(code?: number);
|
||||||
function JavaImporter(...className: string[])
|
function JavaImporter(...className: string[]);
|
||||||
|
|
||||||
namespace Java {
|
namespace Java {
|
||||||
function type<T = any>(clazz: string): T
|
function type(clazz: string): any;
|
||||||
function from<T>(javaObj: T[]): T[]
|
function from(javaObj: any): any[];
|
||||||
function to<T>(array: T[], type?: T): T[]
|
function to(array: any[]): any;
|
||||||
function extend(...parentTypes: any[]): any
|
function extend(...parentTypes: any[]);
|
||||||
function synchronized(func: () => void, lock: any): Function
|
|
||||||
function asJSONCompatible<T = any>(obj: T): T
|
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
// function super(type: any);
|
// function super(type: any);
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Error {
|
interface Error {
|
||||||
readonly class?: any
|
readonly lineNumber?: number;
|
||||||
readonly lineNumber?: number
|
readonly columnNumber?: number;
|
||||||
readonly columnNumber?: number
|
readonly fileName?: string;
|
||||||
readonly fileName?: string
|
dumpStack?: Function;
|
||||||
dumpStack?: Function
|
printStackTrace?: Function;
|
||||||
printStackTrace?: Function
|
getStackTrace?: () => any[];
|
||||||
getStackTrace?: () => any[]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface String {
|
interface String {
|
||||||
trimLeft(): string
|
trimLeft();
|
||||||
trimRight(): string
|
trimRight();
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Object {
|
interface Object {
|
||||||
setPrototypeOf(obj: object, prototype: object): void
|
setPrototypeOf(obj: object, prototype: object);
|
||||||
bindProperties(to: object, from: object): void
|
bindProperties(to: object, from: object);
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace NodeJS {
|
namespace NodeJS {
|
||||||
interface Global {
|
interface Global {
|
||||||
scope: string
|
scope: string;
|
||||||
logger: any
|
logger: any;
|
||||||
debug: boolean
|
debug: boolean;
|
||||||
level: string
|
level: string;
|
||||||
NashornEngineStartTime: number
|
NashornEngineStartTime: number;
|
||||||
setGlobal: (key: string, value: any, config?: PropertyDescriptor & ThisType<any>) => void
|
setGlobal: (key: string, value: any) => void;
|
||||||
noop: () => void
|
noop: () => void;
|
||||||
console: Console
|
console: Console;
|
||||||
}
|
|
||||||
interface Process {
|
|
||||||
on(event: string, listener: any): this
|
|
||||||
emit(event: string, ...message: any): this
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const root: string
|
var root: string;
|
||||||
const base: Core
|
var base: Core;
|
||||||
const ScriptEngineContextHolder: any
|
var ScriptEngineContextHolder: any;
|
||||||
function engineLoad(str: string | { script: string, name: string }): any
|
function engineLoad(str: string): any;
|
||||||
interface Core {
|
interface Core {
|
||||||
getClass(name: String): any
|
getClass(name: String): any;
|
||||||
getProxyClass(): any
|
getProxyClass(): any;
|
||||||
getInstance(): any
|
getInstance(): any;
|
||||||
read(path: string): string
|
read(path: string): string;
|
||||||
save(path: string, content: string): void
|
save(path: string, content: string): void;
|
||||||
delete(path: string): void
|
delete(path: string): void;
|
||||||
}
|
}
|
||||||
interface Console {
|
interface Console {
|
||||||
ex(err: Error): void
|
ex(err: Error): void;
|
||||||
stack(err: Error, color?: boolean): string[]
|
stack(err: Error): string[];
|
||||||
sender(...args: any): void
|
sender(...args: any): void;
|
||||||
console(...args: any): void
|
console(...args: any): void;
|
||||||
i18n(name: string, ...params: any[]): void
|
i18n(name: string, ...params: any[]);
|
||||||
}
|
|
||||||
interface ProxyConstructor {
|
|
||||||
newProxy<T extends object>(target: T, handler: ProxyHandler<T>): T
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export { }
|
export { };
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/nodejs",
|
"name": "@ccms/nodejs",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript nodejs package",
|
"description": "MiaoScript nodejs package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,10 +21,10 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/nashorn": "^0.7.0"
|
"@ccms/nashorn": "^0.6.0"
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/nukkit",
|
"name": "@ccms/nukkit",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript nukkit package",
|
"description": "MiaoScript nukkit package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -21,11 +21,11 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.7.0",
|
"@ccms/api": "^0.6.0",
|
||||||
"@ccms/common": "^0.7.0",
|
"@ccms/common": "^0.6.0",
|
||||||
"@ccms/container": "^0.7.0"
|
"@ccms/container": "^0.6.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,9 +45,6 @@ export class NukkitServer implements server.Server {
|
|||||||
getNettyPipeline() {
|
getNettyPipeline() {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
getRootLogger() {
|
|
||||||
return Packages.org.apache.logging.log4j.LogManager.getRootLogger()
|
|
||||||
}
|
|
||||||
sendJson(sender: string | any, json: object | string): void {
|
sendJson(sender: string | any, json: object | string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,8 +21,10 @@ export class NukkitTaskManager implements task.TaskManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class NukkitTask extends task.Task {
|
export class NukkitTask extends task.Task {
|
||||||
submit(...args: any[]): task.Cancelable {
|
submit(): task.Cancelable {
|
||||||
let run = new NukkitRunnable({ run: () => this.run(...args) })
|
let run = new NukkitRunnable({
|
||||||
|
run: () => this.run()
|
||||||
|
})
|
||||||
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
let funcName = `runTask${this.interval ? 'Timer' : 'Later'}${this.isAsync ? 'Asynchronously' : ''}`
|
||||||
if (this.interval) {
|
if (this.interval) {
|
||||||
run[funcName](this.plugin, this.laterTime, this.interval);
|
run[funcName](this.plugin, this.laterTime, this.interval);
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/ployfill",
|
"name": "@ccms/ployfill",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript ployfill package",
|
"description": "MiaoScript ployfill package",
|
||||||
"author": "MiaoWoo <admin@yumc.pw>",
|
"author": "MiaoWoo <admin@yumc.pw>",
|
||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
@@ -14,13 +14,13 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/i18n": "^0.7.0",
|
"@ccms/i18n": "^0.6.0",
|
||||||
"@ccms/nashorn": "^0.7.0",
|
"@ccms/nashorn": "^0.6.0",
|
||||||
"core-js": "^3.6.5"
|
"core-js": "^3.6.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,12 @@
|
|||||||
/// <reference types="@ccms/nashorn" />
|
/// <reference types="@ccms/nashorn" />
|
||||||
|
|
||||||
import i18n from '@ccms/i18n'
|
import i18n from '@ccms/i18n'
|
||||||
let ployfillStartTime = new Date().getTime()
|
let ployfillStartTime = new Date().getTime();
|
||||||
i18n.initialize()
|
i18n.initialize();
|
||||||
console.i18n("ms.ployfill.initialize")
|
console.i18n("ms.ployfill.initialize");
|
||||||
require('./es5-ext')
|
require('./es5-ext');
|
||||||
require('./node-shim')
|
require('core-js');
|
||||||
require('core-js')
|
|
||||||
//@ts-ignore
|
|
||||||
process.on('exit', () => require.disable())
|
|
||||||
global.setGlobal('Proxy', require('./proxy').Proxy)
|
global.setGlobal('Proxy', require('./proxy').Proxy)
|
||||||
global.setGlobal('XMLHttpRequest', require('./xml-http-request').XMLHttpRequest)
|
global.setGlobal('XMLHttpRequest', require('./xml-http-request').XMLHttpRequest)
|
||||||
global.setGlobal('Blob', require('blob-polyfill').Blob)
|
global.setGlobal('Blob', require('blob-polyfill').Blob)
|
||||||
console.i18n("ms.ployfill.completed", { time: (new Date().getTime() - ployfillStartTime) / 1000 })
|
console.i18n("ms.ployfill.completed", { time: (new Date().getTime() - ployfillStartTime) / 1000 });
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
import { EventEmitter } from 'events'
|
|
||||||
|
|
||||||
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")
|
|
||||||
|
|
||||||
const threadCount = new AtomicInteger(0)
|
|
||||||
const threadGroup = new ThreadGroup("@ccms/ployfill-micro-task")
|
|
||||||
const microTaskPool = new ThreadPoolExecutor(
|
|
||||||
10, 100, 60, Packages.java.util.concurrent.TimeUnit.SECONDS,
|
|
||||||
new LinkedBlockingQueue(500),
|
|
||||||
(run: any) => new Thread(threadGroup, run, "@ccms/micro-task-" + threadCount.incrementAndGet()),
|
|
||||||
new ThreadPoolExecutor.CallerRunsPolicy()
|
|
||||||
)
|
|
||||||
|
|
||||||
class Process extends EventEmitter {
|
|
||||||
env = {
|
|
||||||
__noSuchProperty__: (prop) => {
|
|
||||||
return Packages.java.lang.System.getenv(prop)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
platform = Packages.java.lang.System.getProperty("os.name")
|
|
||||||
nextTick(func: Function) {
|
|
||||||
microTaskPool.execute(func)
|
|
||||||
}
|
|
||||||
queueMicrotask(func: Function) {
|
|
||||||
microTaskPool.execute(func)
|
|
||||||
}
|
|
||||||
exit() {
|
|
||||||
microTaskPool.shutdown();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
global.setGlobal('process', new Process(), {})
|
|
||||||
global.setGlobal('queueMicrotask', (func: any) => microTaskPool.execute(func), {})
|
|
||||||
@@ -82,14 +82,12 @@ export class XMLHttpRequest {
|
|||||||
private _url: string;
|
private _url: string;
|
||||||
private _async: boolean;
|
private _async: boolean;
|
||||||
private _mimeType: string;
|
private _mimeType: string;
|
||||||
private _requestHeaders: HttpHeader = {};
|
|
||||||
|
|
||||||
private _status: number = 0;
|
private _status: number = 0;
|
||||||
private _statusText: string = null;
|
private _statusText: string = null;
|
||||||
private _response: any;
|
private _response: any;
|
||||||
private _responseText: any;
|
|
||||||
private _responseURL: string;
|
private _responseURL: string;
|
||||||
private _responseHeaders: HttpHeader = {};
|
private _responseHeaders: HttpHeader;
|
||||||
|
|
||||||
private _connection = null;
|
private _connection = null;
|
||||||
|
|
||||||
@@ -116,10 +114,10 @@ export class XMLHttpRequest {
|
|||||||
return this._statusText;
|
return this._statusText;
|
||||||
}
|
}
|
||||||
get response() {
|
get response() {
|
||||||
return this._response || this.get();
|
return this._response ? JSON.parse(this._response) : this._response;
|
||||||
}
|
}
|
||||||
get responseText() {
|
get responseText() {
|
||||||
return this._responseText;
|
return this._response;
|
||||||
}
|
}
|
||||||
get responseXML() {
|
get responseXML() {
|
||||||
return this._response;
|
return this._response;
|
||||||
@@ -128,17 +126,17 @@ export class XMLHttpRequest {
|
|||||||
return this._responseURL;
|
return this._responseURL;
|
||||||
}
|
}
|
||||||
|
|
||||||
public onload: () => void;
|
onload() { }
|
||||||
public onerror: (ex: Error) => void;
|
onerror(ex: Error) { }
|
||||||
public onabort: () => void;
|
onabort() { }
|
||||||
public onprogress: () => void;
|
onprogress() { }
|
||||||
public ontimeout: (ex: Error) => void;
|
ontimeout(ex: Error) { }
|
||||||
public onloadend: () => void;
|
onloadend() { }
|
||||||
public onloadstart: () => void;
|
onloadstart() { }
|
||||||
public onreadystatechange: () => void;
|
onreadystatechange() { }
|
||||||
|
|
||||||
setRequestHeader(key: string, val: string) {
|
setRequestHeader(key: string, val: string) {
|
||||||
this._requestHeaders[key] = val;
|
this._connection.setRequestProperty(key, val);
|
||||||
}
|
}
|
||||||
getResponseHeader(key: string): string {
|
getResponseHeader(key: string): string {
|
||||||
return this._responseHeaders[key];
|
return this._responseHeaders[key];
|
||||||
@@ -153,8 +151,6 @@ export class XMLHttpRequest {
|
|||||||
this._mimeType = mimeType;
|
this._mimeType = mimeType;
|
||||||
}
|
}
|
||||||
open(method: RequestMethod, url: string, async: boolean = true, user?: string, password?: string) {
|
open(method: RequestMethod, url: string, async: boolean = true, user?: string, password?: string) {
|
||||||
if (this._readyState !== ReadyState.UNSENT) { throw new Error(`Error Status ${this._readyState}!`) }
|
|
||||||
|
|
||||||
this._method = method;
|
this._method = method;
|
||||||
this._url = url;
|
this._url = url;
|
||||||
this._async = async;
|
this._async = async;
|
||||||
@@ -173,39 +169,33 @@ export class XMLHttpRequest {
|
|||||||
this.setReadyState(ReadyState.OPENED);
|
this.setReadyState(ReadyState.OPENED);
|
||||||
}
|
}
|
||||||
send(body?: string | object): Future<string> {
|
send(body?: string | object): Future<string> {
|
||||||
for (const header in this._requestHeaders) {
|
|
||||||
this._connection.setRequestProperty(header, this._requestHeaders[header]);
|
|
||||||
}
|
|
||||||
if (this._readyState !== ReadyState.OPENED) { throw new Error(`Error Status ${this._readyState}!`) }
|
if (this._readyState !== ReadyState.OPENED) { throw new Error(`Error Status ${this._readyState}!`) }
|
||||||
let future = executor.submit(new Callable({ call: () => this._send(body) }));
|
let future = executor.submit(new Callable({ call: () => this._send(body) }));
|
||||||
if (!this._async) { future.get() }
|
if (!this._async) { future.get() }
|
||||||
return future;
|
return future;
|
||||||
}
|
}
|
||||||
get() {
|
get() {
|
||||||
if (this._response === undefined) {
|
switch (this._responseType) {
|
||||||
switch (this._responseType) {
|
case "json":
|
||||||
case "json":
|
return this.response;
|
||||||
return this._response = JSON.parse(this._responseText);
|
case "text":
|
||||||
case "text":
|
return this.responseText;
|
||||||
return this._response = this._responseText;
|
default:
|
||||||
default:
|
throw Error(`Unsupport ResponseType: ${this._responseType} !`)
|
||||||
throw Error(`Unsupport ResponseType: ${this._responseType} !`)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return this._response;
|
|
||||||
}
|
}
|
||||||
abort() {
|
abort() {
|
||||||
this._connection.disconnect();
|
this._connection.disconnect();
|
||||||
this.onabort && this.onabort();
|
this.onabort();
|
||||||
}
|
}
|
||||||
|
|
||||||
private _send(body?: string | object) {
|
private _send(body?: string | object) {
|
||||||
try {
|
try {
|
||||||
this._connection.connect();
|
this._connection.connect();
|
||||||
this.onloadstart && this.onloadstart();
|
this.onloadstart();
|
||||||
if (body) {
|
if (body) {
|
||||||
let bodyType = Object.prototype.toString.call(body);
|
let bodyType = Object.prototype.toString.call(body);
|
||||||
if (typeof body !== "string") { throw new Error(`body(${bodyType}) must be string!`) }
|
if (bodyType !== '[object String]') { throw new Error(`body(${bodyType}) must be string!`) }
|
||||||
var out = this._connection.getOutputStream();
|
var out = this._connection.getOutputStream();
|
||||||
out.write(new JavaString(body).getBytes(UTF_8));
|
out.write(new JavaString(body).getBytes(UTF_8));
|
||||||
out.flush();
|
out.flush();
|
||||||
@@ -214,15 +204,15 @@ export class XMLHttpRequest {
|
|||||||
this.setReadyState(ReadyState.LOADING);
|
this.setReadyState(ReadyState.LOADING);
|
||||||
this._status = this._connection.getResponseCode();
|
this._status = this._connection.getResponseCode();
|
||||||
this._statusText = this._connection.getResponseMessage();
|
this._statusText = this._connection.getResponseMessage();
|
||||||
|
this.setResponseHeaders(this._connection.getHeaderFields());
|
||||||
if (this._status >= 0 && this._status < 300) {
|
if (this._status >= 0 && this._status < 300) {
|
||||||
this._responseText = this.readOutput(this._connection.getInputStream());
|
this._response = this.readOutput(this._connection.getInputStream());
|
||||||
} else if (this._status >= 300 && this._status < 400) {
|
} else if (this._status >= 300 && this._status < 400) {
|
||||||
this._responseURL = this.getResponseHeader('Location');
|
this._responseURL = this.getResponseHeader('Location');
|
||||||
} else {
|
} else {
|
||||||
this._responseText = this.readOutput(this._connection.getErrorStream());
|
this._response = this.readOutput(this._connection.getErrorStream());
|
||||||
}
|
}
|
||||||
this.setResponseHeaders(this._connection.getHeaderFields());
|
this.onloadend();
|
||||||
this.onloadend && this.onloadend();
|
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
if (ex instanceof SocketTimeoutException && this.ontimeout) {
|
if (ex instanceof SocketTimeoutException && this.ontimeout) {
|
||||||
return this.ontimeout(ex)
|
return this.ontimeout(ex)
|
||||||
@@ -237,14 +227,15 @@ export class XMLHttpRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private setResponseHeaders(header: any) {
|
private setResponseHeaders(header: any) {
|
||||||
header.forEach((key: string | number, value: string | any[]) => {
|
this._responseHeaders = {};
|
||||||
|
header.forEach((key, value) => {
|
||||||
this._responseHeaders[key] = value[value.length - 1]
|
this._responseHeaders[key] = value[value.length - 1]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private setReadyState(state: ReadyState) {
|
private setReadyState(state: ReadyState) {
|
||||||
this._readyState = state;
|
this._readyState = state;
|
||||||
this.onreadystatechange && this.onreadystatechange();
|
this.onreadystatechange();
|
||||||
}
|
}
|
||||||
|
|
||||||
private readOutput(input: any) {
|
private readOutput(input: any) {
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
../../.npmignore
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ccms/plugin",
|
"name": "@ccms/plugin",
|
||||||
"version": "0.7.0",
|
"version": "0.6.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,13 +22,13 @@
|
|||||||
"@types/js-yaml": "^3.12.3",
|
"@types/js-yaml": "^3.12.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.9.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ccms/api": "^0.7.0",
|
"@ccms/api": "^0.6.0",
|
||||||
"@ccms/common": "^0.7.0",
|
"@ccms/common": "^0.6.0",
|
||||||
"@ccms/container": "^0.7.0",
|
"@ccms/container": "^0.6.0",
|
||||||
"@ccms/i18n": "^0.7.0",
|
"@ccms/i18n": "^0.6.0",
|
||||||
"js-yaml": "^3.13.1"
|
"js-yaml": "^3.13.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ export class YamlPluginConfig implements PluginConfigLoader {
|
|||||||
return yaml.safeLoad(content);
|
return yaml.safeLoad(content);
|
||||||
}
|
}
|
||||||
dump(variable: any): string {
|
dump(variable: any): string {
|
||||||
return yaml.safeDump(variable, { skipInvalid: true });
|
return yaml.safeDump(variable);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
export const METADATA_KEY = {
|
export const METADATA_KEY = {
|
||||||
plugin: Symbol.for("@ccms/plugin:plugin"),
|
plugin: "@ccms/plugin:plugin",
|
||||||
souece: Symbol.for("@ccms/plugin:souece"),
|
cmd: "@ccms/plugin:cmd",
|
||||||
cmd: Symbol.for("@ccms/plugin:cmd"),
|
tab: "@ccms/plugin:tab",
|
||||||
tab: Symbol.for("@ccms/plugin:tab"),
|
listener: "@ccms/plugin:listener",
|
||||||
listener: Symbol.for("@ccms/plugin:listener"),
|
config: "@ccms/plugin:config",
|
||||||
config: Symbol.for("@ccms/plugin:config"),
|
|
||||||
stage: {
|
stage: {
|
||||||
load: Symbol.for("@ccms/plugin:stage:load"),
|
load: "@ccms/plugin:stage:load",
|
||||||
enable: Symbol.for("@ccms/plugin:stage:enable"),
|
enable: "@ccms/plugin:stage:enable",
|
||||||
disable: Symbol.for("@ccms/plugin:stage:disable")
|
disable: "@ccms/plugin:stage:disable"
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,26 +1,21 @@
|
|||||||
import { plugin as pluginApi } from "@ccms/api"
|
import { injectable, decorate } from "@ccms/container";
|
||||||
import { injectable, decorate } from "@ccms/container"
|
|
||||||
import { interfaces } from './interfaces'
|
import { interfaces } from './interfaces'
|
||||||
import { METADATA_KEY } from './constants'
|
import { METADATA_KEY } from './constants'
|
||||||
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata, getPluginConfigMetadata, getPluginStageMetadata, getPluginSources } from './utils'
|
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata, getPluginConfigMetadata, getPluginStageMetadata } from './utils'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* MiaoScript plugin
|
* MiaoScript plugin
|
||||||
* @param metadata PluginMetadata
|
* @param metadata PluginMetadata
|
||||||
*/
|
*/
|
||||||
export function plugin(metadata: pluginApi.PluginMetadata) {
|
export function plugin(metadata: interfaces.PluginMetadata) {
|
||||||
return function (target: any) {
|
return function (target: any) {
|
||||||
metadata.target = target
|
metadata.target = target;
|
||||||
metadata.type = "ioc"
|
decorate(injectable(), target);
|
||||||
decorate(injectable(), target)
|
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target);
|
||||||
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target)
|
const previousMetadata: Map<string, interfaces.PluginMetadata> = getPluginMetadatas();
|
||||||
const previousMetadata: Map<string, pluginApi.PluginMetadata> = getPluginMetadatas()
|
previousMetadata.set(metadata.name, metadata);
|
||||||
previousMetadata.set(metadata.name, metadata)
|
Reflect.defineMetadata(METADATA_KEY.plugin, previousMetadata, Reflect);
|
||||||
Reflect.defineMetadata(METADATA_KEY.plugin, previousMetadata, Reflect)
|
};
|
||||||
const previousSources: Map<string, pluginApi.PluginMetadata> = getPluginSources()
|
|
||||||
previousSources.set(metadata.source.toString(), metadata)
|
|
||||||
Reflect.defineMetadata(METADATA_KEY.souece, previousSources, Reflect)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,13 +24,13 @@ export function plugin(metadata: pluginApi.PluginMetadata) {
|
|||||||
*/
|
*/
|
||||||
export function cmd(metadata: interfaces.CommandMetadata = {}) {
|
export function cmd(metadata: interfaces.CommandMetadata = {}) {
|
||||||
return function (target: any, key: string, value: any) {
|
return function (target: any, key: string, value: any) {
|
||||||
metadata.name = metadata.name || key
|
metadata.name = metadata.name || key;
|
||||||
metadata.executor = key
|
metadata.executor = key;
|
||||||
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
||||||
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginCommandMetadata(target)
|
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginCommandMetadata(target)
|
||||||
previousMetadata.set(metadata.name, metadata)
|
previousMetadata.set(metadata.name, metadata);
|
||||||
Reflect.defineMetadata(METADATA_KEY.cmd, previousMetadata, target.constructor)
|
Reflect.defineMetadata(METADATA_KEY.cmd, previousMetadata, target.constructor);
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -44,14 +39,14 @@ export function cmd(metadata: interfaces.CommandMetadata = {}) {
|
|||||||
*/
|
*/
|
||||||
export function tab(metadata: interfaces.CommandMetadata = {}) {
|
export function tab(metadata: interfaces.CommandMetadata = {}) {
|
||||||
return function (target: any, key: string, value: any) {
|
return function (target: any, key: string, value: any) {
|
||||||
metadata.name = metadata.name || (key.startsWith('tab') ? key.split('tab', 2)[1] : key)
|
metadata.name = metadata.name || (key.startsWith('tab') ? key.split('tab', 2)[1] : key);
|
||||||
if (!metadata.name) { return }
|
if (!metadata.name) { return; }
|
||||||
metadata.executor = key
|
metadata.executor = key;
|
||||||
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
||||||
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginTabCompleterMetadata(target)
|
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginTabCompleterMetadata(target)
|
||||||
previousMetadata.set(metadata.name, metadata)
|
previousMetadata.set(metadata.name, metadata)
|
||||||
Reflect.defineMetadata(METADATA_KEY.tab, previousMetadata, target.constructor)
|
Reflect.defineMetadata(METADATA_KEY.tab, previousMetadata, target.constructor);
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -60,32 +55,30 @@ export function tab(metadata: interfaces.CommandMetadata = {}) {
|
|||||||
*/
|
*/
|
||||||
export function listener(metadata: interfaces.ListenerMetadata = {}) {
|
export function listener(metadata: interfaces.ListenerMetadata = {}) {
|
||||||
return function (target: any, key: string, value: any) {
|
return function (target: any, key: string, value: any) {
|
||||||
metadata.name = metadata.name || key
|
metadata.name = metadata.name || key;
|
||||||
metadata.executor = key
|
metadata.executor = key;
|
||||||
const previousMetadata: interfaces.ListenerMetadata[] = getPluginListenerMetadata(target)
|
const previousMetadata: interfaces.ListenerMetadata[] = getPluginListenerMetadata(target)
|
||||||
Reflect.defineMetadata(METADATA_KEY.listener, [metadata, ...previousMetadata], target.constructor)
|
Reflect.defineMetadata(METADATA_KEY.listener, [metadata, ...previousMetadata], target.constructor);
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function config(metadata: interfaces.ConfigMetadata = {}) {
|
export function config(metadata: interfaces.ConfigMetadata = { version: 1, format: 'yml' }) {
|
||||||
return function (target: any, key: string) {
|
return function (target: any, key: string) {
|
||||||
metadata.name = metadata.name || key
|
metadata.name = metadata.name || key;
|
||||||
metadata.variable = key
|
metadata.variable = key;
|
||||||
metadata.version = metadata.version ?? 1
|
|
||||||
metadata.format = metadata.format ?? 'yml'
|
|
||||||
const previousMetadata: Map<string, interfaces.ConfigMetadata> = getPluginConfigMetadata(target)
|
const previousMetadata: Map<string, interfaces.ConfigMetadata> = getPluginConfigMetadata(target)
|
||||||
previousMetadata.set(metadata.name, metadata)
|
previousMetadata.set(metadata.name, metadata);
|
||||||
Reflect.defineMetadata(METADATA_KEY.config, previousMetadata, target.constructor)
|
Reflect.defineMetadata(METADATA_KEY.config, previousMetadata, target.constructor);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function stage(metadata: interfaces.ExecMetadata = {}, stage: string) {
|
function stage(metadata: interfaces.ExecMetadata = {}, stage: string) {
|
||||||
return function (target: any, key: string, value: any) {
|
return function (target: any, key: string, value: any) {
|
||||||
metadata.name = metadata.name || key
|
metadata.name = metadata.name || key;
|
||||||
metadata.executor = key
|
metadata.executor = key;
|
||||||
const previousMetadata: interfaces.ExecMetadata[] = getPluginStageMetadata(target, stage)
|
const previousMetadata: interfaces.ExecMetadata[] = getPluginStageMetadata(target, stage)
|
||||||
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...previousMetadata], target.constructor)
|
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...previousMetadata], target.constructor);
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function load(metadata: interfaces.ExecMetadata = {}) {
|
export function load(metadata: interfaces.ExecMetadata = {}) {
|
||||||
|
|||||||
@@ -1,15 +1,3 @@
|
|||||||
import './scanner/file-scanner'
|
|
||||||
import './loader/ioc-loader'
|
|
||||||
import './loader/basic-loader'
|
|
||||||
|
|
||||||
export * from './manager'
|
export * from './manager'
|
||||||
export * from './decorators'
|
export * from './decorators'
|
||||||
export * from './interfaces'
|
export * from './interfaces'
|
||||||
|
|
||||||
export {
|
|
||||||
plugin as JSPlugin,
|
|
||||||
cmd as Cmd,
|
|
||||||
tab as Tab,
|
|
||||||
listener as Listener,
|
|
||||||
config as Config
|
|
||||||
} from './decorators'
|
|
||||||
|
|||||||
@@ -1,72 +1,96 @@
|
|||||||
import { server, MiaoScriptConsole, event, plugin } from "@ccms/api"
|
import { server, MiaoScriptConsole, event } from "@ccms/api";
|
||||||
import { injectable, inject, postConstruct } from "@ccms/container"
|
import { METADATA_KEY } from './constants'
|
||||||
import { getPluginMetadata } from "./utils"
|
import { injectable, inject, postConstruct } from "@ccms/container";
|
||||||
|
import { getPluginMetadata } from "./utils";
|
||||||
|
|
||||||
export namespace interfaces {
|
export namespace interfaces {
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class Plugin implements plugin.Plugin {
|
export abstract class Plugin {
|
||||||
public description: plugin.PluginMetadata
|
public description: PluginMetadata;
|
||||||
public logger: Console
|
public logger: Console;
|
||||||
@inject(server.Console)
|
|
||||||
private Console: MiaoScriptConsole
|
|
||||||
|
|
||||||
constructor() {
|
constructor(@inject(server.Console) Console: MiaoScriptConsole) {
|
||||||
this.description = getPluginMetadata(this)
|
this.description = getPluginMetadata(this)
|
||||||
}
|
|
||||||
|
|
||||||
@postConstruct()
|
|
||||||
private initialize() {
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
this.logger = new this.Console(this.description.prefix || this.description.name)
|
this.logger = new Console(this.description.prefix || this.description.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
public load() { }
|
public load() { }
|
||||||
public enable() { }
|
public enable() { }
|
||||||
public disable() { }
|
public disable() { }
|
||||||
}
|
}
|
||||||
export interface ExecMetadata extends plugin.BaseMetadata {
|
interface BaseMetadata {
|
||||||
|
/**
|
||||||
|
* 名称 为空则为对象名称
|
||||||
|
*/
|
||||||
|
name?: string;
|
||||||
|
/**
|
||||||
|
* 支持的服务器列表 为空则代表所有
|
||||||
|
*/
|
||||||
|
servers?: string[];
|
||||||
|
}
|
||||||
|
export interface PluginMetadata extends BaseMetadata {
|
||||||
|
/**
|
||||||
|
* 插件名称
|
||||||
|
*/
|
||||||
|
name: string;
|
||||||
|
/**
|
||||||
|
* 前缀
|
||||||
|
*/
|
||||||
|
prefix?: string;
|
||||||
|
/**
|
||||||
|
* 插件版本
|
||||||
|
*/
|
||||||
|
version: string;
|
||||||
|
/**
|
||||||
|
* 插件版本
|
||||||
|
*/
|
||||||
|
author: string | string[];
|
||||||
|
/**
|
||||||
|
* 插件源文件 必须指定为 __filename
|
||||||
|
*/
|
||||||
|
source: string;
|
||||||
|
/**
|
||||||
|
* 插件本体
|
||||||
|
*/
|
||||||
|
target?: any;
|
||||||
|
}
|
||||||
|
export interface ExecMetadata extends BaseMetadata {
|
||||||
/**
|
/**
|
||||||
* 执行器
|
* 执行器
|
||||||
*/
|
*/
|
||||||
executor?: string
|
executor?: string;
|
||||||
}
|
}
|
||||||
export interface CommandMetadata extends ExecMetadata {
|
export interface CommandMetadata extends ExecMetadata {
|
||||||
/**
|
|
||||||
* 命令描述
|
|
||||||
*/
|
|
||||||
description?: string
|
|
||||||
/**
|
/**
|
||||||
* 参数列表
|
* 参数列表
|
||||||
*/
|
*/
|
||||||
paramtypes?: string[]
|
paramtypes?: string[];
|
||||||
}
|
}
|
||||||
export interface ListenerMetadata extends ExecMetadata {
|
export interface ListenerMetadata extends ExecMetadata {
|
||||||
/**
|
/**
|
||||||
* 监听优先级
|
* 监听优先级
|
||||||
*/
|
*/
|
||||||
priority?: event.EventPriority
|
priority?: event.EventPriority;
|
||||||
/**
|
/**
|
||||||
* 是否忽略已取消的事件
|
* 是否忽略已取消的事件
|
||||||
*/
|
*/
|
||||||
ignoreCancel?: boolean
|
ignoreCancel?: boolean;
|
||||||
|
|
||||||
}
|
}
|
||||||
export interface ConfigMetadata extends plugin.BaseMetadata {
|
export interface ConfigMetadata extends BaseMetadata {
|
||||||
/**
|
/**
|
||||||
* 配置文件版本号
|
* 配置文件版本号
|
||||||
*/
|
*/
|
||||||
version?: number
|
version?: number;
|
||||||
/**
|
/**
|
||||||
* 实体变量名称
|
* 实体变量名称
|
||||||
*/
|
*/
|
||||||
variable?: string
|
variable?: string;
|
||||||
/**
|
/**
|
||||||
* 配置文件格式 默认 yml
|
* 配置文件格式 默认 yml
|
||||||
*/
|
*/
|
||||||
format?: string
|
format?: string;
|
||||||
/**
|
|
||||||
* 是否为只读(关闭时将不会自动保存)
|
|
||||||
*/
|
|
||||||
readonly?: boolean
|
|
||||||
}
|
}
|
||||||
export type PluginLike = Plugin | string
|
export type PluginLike = Plugin | string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
import { plugin } from "@ccms/api"
|
|
||||||
import { provideSingleton } from "@ccms/container"
|
|
||||||
|
|
||||||
@provideSingleton(plugin.PluginLoader)
|
|
||||||
export class BasicLoader implements plugin.PluginLoader {
|
|
||||||
type: string = 'basic'
|
|
||||||
|
|
||||||
private pluginRequireMap: Map<string, any>
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
this.pluginRequireMap = new Map()
|
|
||||||
}
|
|
||||||
require(target: any, result: any) {
|
|
||||||
this.pluginRequireMap.set(target.toString(), result)
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
build(metadata: plugin.PluginMetadata) {
|
|
||||||
return this.pluginRequireMap.get(metadata.source.toString())
|
|
||||||
}
|
|
||||||
load(plugin: plugin.Plugin): void { }
|
|
||||||
enable(plugin: plugin.Plugin): void { }
|
|
||||||
disable(plugin: plugin.Plugin): void { }
|
|
||||||
reload(plugin: plugin.Plugin): void { }
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user