Compare commits

...

54 Commits

Author SHA1 Message Date
d9a2ea9c78 v0.4.0 2020-03-25 13:54:45 +08:00
c505cda10b feat: export error handle & merge config
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 18:30:50 +08:00
100ccbcde3 feat: add api doc
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 17:59:18 +08:00
c6575ed481 fix: sourceMap sometime error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 15:02:20 +08:00
83359d8cb9 fix: ack callback call twice
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 14:52:50 +08:00
cca4979f16 feat: optimize framework add error catch(only log)
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 13:27:11 +08:00
251c9366f5 style: change error color
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-24 13:26:15 +08:00
8f01dcc8e8 feat: complate sockt.io server
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-23 18:33:12 +08:00
c25a616dba feat: add adapter and socket
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-23 00:58:53 +08:00
aa9169b043 feat: tracatch plugin build
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-21 15:48:45 +08:00
d87e152f3b feat: add nodejs package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-21 15:47:59 +08:00
2fcadeda4e feat: complate socket.io base framework
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-21 15:47:42 +08:00
b7927830ae v0.3.2 2020-03-18 11:19:08 +08:00
2dbd2182c2 fix: source map print error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-18 11:15:49 +08:00
01df79eaf1 refactor: move docs to MiaoDocs
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-10 13:19:48 +08:00
16fe9ba9bd update: README
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-04 02:23:37 +08:00
950ce69b83 feat: modify stage order
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-04 02:11:55 +08:00
fa8e44d838 feat: update readme and fix container package error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-04 02:04:35 +08:00
b7af785273 feat: add docs package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-04 02:04:02 +08:00
6c9f7bbcf6 v0.3.1 2020-03-03 01:14:22 +08:00
c4c4c7f301 feat: public types package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-03 01:11:49 +08:00
6538c4b7bb feat: complate spiget and forgesvc api
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 22:40:18 +08:00
a4e6d1660d feat: update readme
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 22:38:34 +08:00
511b042eba feat: update MCBBS.MD
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 22:37:08 +08:00
6f0b5a5572 feat: add error handle
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 22:28:27 +08:00
e9ac46487c feat: merge type defiend
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 22:29:29 +08:00
9371823d30 remove: manager package
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 21:00:54 +08:00
c86f0d9ec1 feat: add complate function
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-02 00:32:07 +08:00
c2d94ef104 feat: optimize types ref
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-01 20:28:16 +08:00
6ada3e41d0 fix: Dependency cycles
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-01 19:37:34 +08:00
8c12319dc9 feat: add i18n to ployfill
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-01 17:01:27 +08:00
395d2d8816 feat: add NativePluginManager
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-03-01 15:19:43 +08:00
6f628a3d7e feat: add download and getPluginsFolder
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-29 22:28:43 +08:00
2232e82c36 feat: upgrade typescript
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-29 18:21:02 +08:00
291b5010e7 feat: add command error i18n
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-29 00:44:11 +08:00
3595294444 feat: add normal env task
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 18:20:45 +08:00
e38358ef98 feat: MiaoConsole exclude nukkit
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 18:15:33 +08:00
4c418c33c0 feat: channel add ext data
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 18:14:17 +08:00
65d112be09 feat: add nukkit example
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 17:59:06 +08:00
15a75dffe2 fix: servers check error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 17:57:29 +08:00
7b8e693a03 v0.3.0 2020-02-27 12:27:19 +08:00
5426023adb feat: optimize code
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 12:26:04 +08:00
73b91c417e feat: improve i18n scope
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 12:11:18 +08:00
2693a22bf0 feat: support i18n translate
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 01:58:23 +08:00
2322de1e40 feat: add package i18n
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-27 01:57:44 +08:00
2320736a92 feat: remove async check
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-26 10:43:47 +08:00
e8d5d10d44 feat: unmanaged baseEventDir
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-26 10:36:30 +08:00
a9996ba297 feat: use inversify autoProvide inject
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-26 10:15:33 +08:00
68380ddbba feat: exclude async event monitor
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-25 23:32:12 +08:00
0baf8f3cab fix: event execute class type error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-25 23:15:39 +08:00
a2bce715f3 fix: nukkit unregister event error
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-25 18:25:16 +08:00
3c55df03d8 feat: use new channel service
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 18:36:32 +08:00
f6526e79fc feat: add channel support for bungee bukkit sponge
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 18:36:08 +08:00
f4c2294c06 feat: update ignore file
Signed-off-by: MiaoWoo <admin@yumc.pw>
2020-02-24 16:35:19 +08:00
101 changed files with 3998 additions and 734 deletions

2
.gitignore vendored
View File

@@ -1,3 +1,5 @@
.vscode
.theia
node_modules
dist
package-lock.json

View File

@@ -11,19 +11,24 @@
├─api 全平台兼容的接口
├─core 核心代码 用于引导加载
├─common 公共类库代码 例如 http reflect 模块
├─compile 实时编译模块 自动编译TS文件为js
├─client NodeJS的Minecraft客户端 用于调试插件
├─container IOC容器 用于注入具体实现
├─ployfill Nashorn 的一些自定义增强
├─nashorn Nashorn 的类型定义
├─ployfill Java Nashorn的补丁
├─bungee BungeeCordAPI内部实现
├─bukkit BukkitAPI内部实现
├─sponge SpongeAPI内部实现
├─nukkit NukkitAPI内部实现
├─plugin 插件管理器
├─manager 插件管理中心后端服务
├─types Java在TypeScript的类型定义文件
├─websocket Netty的WebSocket的MiaoScript实现(兼容socket.io)
├─websocket Netty的WebSocket注入
├─type Java的类型定义
| ├─bungee BungeeCord类型定义
| ├─bukkit Bukkit类型定义
| ├─sponge Sponge类型定义
| └─nukkit Nukkit类型定义
└─plugins 这里当然是插件啦
├─bungee 只兼容BungeeCord的插件
├─bukkit 只兼容Bukkit的插件
─sponge 只兼容Sponge的插件
─sponge 只兼容Sponge的插件
└─nukkit 只兼容Nukkit的插件
```

62
cli.sh
View File

@@ -1,62 +0,0 @@
#!/bin/bash
SHELL_PREFIX="[FAAS-CLI]"
# Shell Base Script
set -e
c_red="\033[38;5;1m"
c_blue="\033[38;5;4m"
c_green="\033[38;5;2m"
c_reset="\033[0m"
c_yellow="\033[38;5;3m"
c_prefix="${c_blue}${SHELL_PREFIX}>>${c_reset}"
dateStr() {
echo -e "[$(date '+%H:%M:%S')]"
}
info() {
echo -e "${c_prefix}$(dateStr) ${*}"
}
warn() {
echo -e "${c_prefix}$(dateStr) ${c_yellow}${*}${c_reset}"
}
error() {
echo -e "${c_prefix}$(dateStr) ${c_red}${*}${c_reset}"
}
#====================
cd $(dirname $0)
# User Input Variable
action=
while [[ $# -gt 0 ]]; do
case "$1" in
-a)
action="$2"
shift
;;
-*)
echo "Illegal option $1"
;;
esac
shift $(( $# > 0 ? 1 : 0 ))
done
case "${action}" in
undo)
hash=$(git log -n 1 --format=format:%H)
tag=$(git tag -l --contains=${hash})
if [[ -z "${tag}" ]]; then
error "last commit not have tag exit..."
exit 0
fi
git reset HEAD^
git tag -d ${tag}
git push origin master -f
git push origin :${tag}
;;
esac

View File

@@ -5,16 +5,61 @@
### 更新日志
- 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
- 完善 `Sponge` 类型自动补全
- 新增 `@ms/type` 的 `sponge` 类型自动补全
- 2019-09-24
- 完善 `Bukkit` 类型自动补全
- 新增 `@ms/type` 的 `bukkit` 类型自动补全
## 插件简介
- 此插件可以实现跨端使用 `TypeScript` 开发 脚本插件
- 目前已经兼容 `Spigot` `Sponge`
- 后续计划兼容 `BungeeCord` `Nukkit`
- 目前已经兼容 `Spigot` `Sponge` `Paper` `CatServer` `BungeeCord` `Nukkit`
- 后续计划兼容 暂无
## 起源 (可以略过)
@@ -65,6 +110,8 @@
- 完整的服务端Java类自动补全
- 全新的 IOC容器 注入功能
- 注解式 注册命令 注册事件
- 2020年3月2日 发布0.3.0版本
- 支持 Bukkit Nukkit BungeeCord Sponge
### 进展
@@ -98,22 +145,26 @@
├─bungee BungeeCordAPI内部实现
├─bukkit BukkitAPI内部实现
├─sponge SpongeAPI内部实现
├─nukkit NukkitAPI内部实现
├─ployfill JS环境的相关环境补全
├─plugin 插件管理器
├─websocket Netty的WebSocket注入
├─type Java的类型定义
| ├─bungee BungeeCord类型定义
| ├─bukkit Bukkit类型定义
| ─sponge Sponge类型定义
├─websocket Netty的WebSocket注入
| ─sponge Sponge类型定义
| └─nukkit Nukkit类型定义
└─plugins 这里当然是插件啦
├─bungee 只兼容BungeeCord的插件
├─bukkit 只兼容Bukkit的插件
─sponge 只兼容Sponge的插件
─sponge 只兼容Sponge的插件
└─nukkit 只兼容Nukkit的插件
```
详细的内容就不逼逼了 自己看代码吧
Github: https://github.com/circlecloud/ms
YUMC: https://git.yumc.pw/circlecloud/ms
## 插件开发基础
@@ -129,8 +180,12 @@ Github: https://github.com/circlecloud/ms
- 进入目录 `ms`
- 安装 npm 包
- `yarn`
- 建立内部依赖链接
- `yarn bs`
- 编译一次生成对应的类库
- `yarn build`
- 编译插件
- `yarn build:plugins`
### 直接在 MiaoScript Online WebIDE 开发
@@ -143,9 +198,7 @@ Github: https://github.com/circlecloud/ms
先来一个 `HelloWorld.ts` 插件示范!
```ts
/// <reference types="@ms/types/dist/typings/bukkit" />
/// <reference types="@ms/types/dist/typings/sponge" />
/// <reference types="@ms/types/dist/typings/bungee" />
/// <reference types="@ms/types" />
import { server } from '@ms/api';
import { inject } from '@ms/container';
@@ -155,6 +208,10 @@ import { plugin, interfaces, cmd, listener, tab } from '@ms/plugin'
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...');
@@ -196,6 +253,16 @@ export class HelloWorld extends interfaces.Plugin {
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);
@@ -207,7 +274,8 @@ export class HelloWorld extends interfaces.Plugin {
return ['world']
}
@listener({ servers: ['bukkit'] })
// 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()}`)
@@ -236,10 +304,11 @@ export class HelloWorld extends interfaces.Plugin {
- 进入 `ms`目录
- 执行编译 `yarn build:plugins`
- 从 `packages/plugins/dist` 中复制 `HelloWorld.js` 文件 到对应的插件目录
- 从 `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 服务端进入
@@ -259,6 +328,10 @@ export interface PluginMetadata {
* 插件名称
*/
name: string;
/**
* 支持的服务器列表 为空则代表所有
*/
servers?: string[];
/**
* 前缀
*/
@@ -284,10 +357,10 @@ export interface PluginMetadata {
### 插件生命周期
MiaoScript的生命周期遵循了 Bukkit 的生命周期
MiaoScript 的生命周期遵循了 Bukkit 的生命周期
MiaoScript针对不同的服务端 提供了扩展的周期
以服务端类型开头阶段名结束 例如 `bukkitload` `spongeenbale`
MiaoScript 针对不同的服务端 提供了扩展的周期
以服务端类型开头阶段名结束 例如 `bukkitload` `spongeenbale` `bungeedisable`
扩展的生命周期只会在特定的服务器执行
### load 加载阶段
@@ -358,7 +431,8 @@ tabhello(_sender: any, _command: string, _args: string[]) {
- 事件监听方法的第一个参数就是本次事件的具体内容 (这里就需要自己去查询对应的JavaDoc了)
```ts
@listener({ servers: ['bukkit'] })
// 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()}`)
@@ -384,6 +458,19 @@ ServerConnected(e: any) {
}
```
## 配置文件
配置文件 默认读取的是 `MiaoScript根目录/plugins/插件名称/配置名称.配置格式`
例如下面文件 默认处理的是 `plugins/MiaoScript/plugins/HelloWorld/config.yml`
```ts
@config()
private config = {
version: 1.0.0
}
```
## 插件列表
暂无

View File

@@ -1,5 +1,5 @@
{
"version": "0.2.1",
"version": "0.4.0",
"useWorkspaces": true,
"npmClient": "yarn",
"packages": [

View File

@@ -8,8 +8,8 @@
"scripts": {
"bs": "lerna bootstrap",
"clean": "lerna run clean",
"watch": "lerna run watch --parallel --scope=\"@ms/!(manager)\"",
"build": "lerna run build --scope=\"@ms/!(plugins|manager)\"",
"watch": "lerna run watch --parallel",
"build": "lerna run build --scope=\"@ms/!(plugins)\"",
"build:plugins": "lerna run build --scope=\"@ms/plugins\"",
"ug": "yarn upgrade-interactive --latest",
"lp": "lerna publish"

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/api",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -22,13 +22,13 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ms/container": "^0.2.1",
"@ms/ployfill": "^0.2.1",
"@ms/container": "^0.4.0",
"@ms/ployfill": "^0.4.0",
"source-map-builder": "^0.0.7"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
}
}

View File

@@ -0,0 +1,66 @@
import { injectable } from "@ms/container";
export namespace channel {
/**
* handle plugin message
* @param data byte[]
*/
export type ChannelListener = (data: any, exts?: any) => void
@injectable()
export abstract class Channel {
private listenerMap = [];
/**
* 注册通道
* @param plugin 插件
* @param channel 通道
* @param exec 执行器
*/
listen(plugin: any, channel: string, exec: ChannelListener) {
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!');
let name = plugin.description.name;
let listener = this.register(channel, exec)
if (!this.listenerMap[name]) this.listenerMap[name] = [];
let offExec = () => {
this.unregister(channel, listener);
console.debug(`[${name}] unregister channel ${channel}`);
};
var off = {
channel,
listener,
off: offExec
};
this.listenerMap[name].push(off);
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`);
return off;
}
/**
* 关闭插件注册的通道
* @param plugin 插件
*/
disable(plugin: any) {
var channelCache = this.listenerMap[plugin.description.name];
if (channelCache) {
channelCache.forEach(t => t.off());
delete this.listenerMap[plugin.description.name];
}
}
/**
* Send Channel Message
* @param player recover target
* @param channel ChannelName
* @param data byte[]
*/
abstract send(player: any, channel: string, data: any)
/**
* register channel
* @param channel ChannelName
*/
abstract register(channel: string, listener: ChannelListener): any
/**
* unregister channel
* @param channel ChannelName
*/
abstract unregister(channel: string, listener?: any): void
}
}

View File

@@ -1,45 +1,53 @@
import i18n from '@ms/i18n'
import { injectable } from "@ms/container";
export namespace command {
@injectable()
export abstract class Command {
/**
* 注册插件命令
* @param plugin 插件
* @param name 命令
* @param exec 执行器
*/
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
var cmd = this.create(plugin, name);
console.debug(`[${plugin.description.name}] register command ${name}(${cmd})...`)
console.debug(i18n.translate("ms.api.command.register", { plugin: plugin.description.name, name, cmd }))
if (exec.cmd && typeof exec.cmd === "function") {
this.onCommand(plugin, cmd, exec.cmd);
} else {
throw Error("CommandExec Must be a function... Input: " + exec.cmd)
throw Error(i18n.translate("ms.api.command.register.input.error", { exec: exec.cmd }))
}
if (exec.tab && typeof exec.tab === "function") {
this.onTabComplete(plugin, cmd, exec.tab);
}
}
/**
* 取消命令注册
* @param plugin 插件
* @param name 命令
*/
off(plugin: any, name: string) {
console.debug(`[${plugin.description.name}] unregister command ${name}...`)
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
this.remove(plugin, name);
}
/**
* Create Server Command Object
*/
protected abstract create(plugin: any, command: string);
protected abstract remove(plugin: any, command: string);
protected abstract onCommand(plugin: any, command: any, executor: Function);
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
protected setExecutor(plugin: any, command: any, executor: Function) {
return (sender: any, _: any, command: string, args: string[]) => {
try {
return executor(sender, command, Java.from(args));
} catch (ex) {
console.console(`§6玩家 §a${sender.name} §6执行 §b${plugin.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6命令时发生异常 §4${ex}`);
console.i18n("ms.api.command.execute.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
console.ex(ex);
console.sender(sender, [`§6执行 §b${plugin.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6命令时发生异常`, ...console.stack(ex)])
console.sender(sender, [i18n.translate("ms.api.command.execute.error", { sender: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
return true;
}
}
}
protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
return (sender: any, _: any, command: string, args: string[]) => {
try {
@@ -47,17 +55,16 @@ export namespace command {
var complete = tabCompleter(sender, command, Java.from(args)) || [];
return this.copyPartialMatches(complete, token);
} catch (ex) {
console.console(`§6玩家 §a${sender.name} §6执行 §b${plugin.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6补全时发生异常 §4${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.sender(sender, [`§6执行 §b${plugin.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6补全时发生异常 §4${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 [];
}
}
}
protected copyPartialMatches(complete: string[], token: string, array: string[] = []): string[] {
if (!token) { return complete }
complete.forEach(function(e) {
complete.forEach(function (e) {
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
array.push(e)
}

View File

@@ -1,3 +1,4 @@
import i18m from '@ms/i18n'
import { SourceMapBuilder } from 'source-map-builder'
const Arrays = Java.type('java.util.Arrays');
@@ -78,6 +79,9 @@ export class MiaoScriptConsole implements Console {
console(...args) {
this.info(args)
}
i18n(name: string, param?: { [key: string]: any }) {
this.console(i18m.translate(name, param))
}
object(obj) {
for (var i in obj) {
this.info(i, '=>', obj[i])
@@ -90,17 +94,21 @@ export class MiaoScriptConsole implements Console {
try {
if (fileName.endsWith('js')) {
var file = Paths.get(fileName + '.map');
if (!this.sourceMaps[fileName]) {
if (this.sourceMaps[fileName] === undefined) {
if (file.toFile().exists()) {
var sourceMapObj = JSON.parse(new JavaString(Files.readAllBytes(file), "UTF-8"))
this.sourceMaps[fileName] = new SourceMapBuilder(sourceMapObj)
} else {
this.sourceMaps[fileName] = null;
}
}
if (this.sourceMaps[fileName]) {
var sourceMapping = this.sourceMaps[fileName].getSource(lineNumber, lineNumber);
var sourceMapping = this.sourceMaps[fileName].getSource(lineNumber, 25, true);
if (sourceMapping) {
fileName = fileName.replace(".js", ".ts");
lineNumber = sourceMapping.mapping.sourceLine;
if (lineNumber != sourceMapping.mapping.sourceLine) {
fileName = fileName.replace(".js", ".ts");
lineNumber = sourceMapping.mapping.sourceLine;
}
}
}
}
@@ -114,7 +122,7 @@ export class MiaoScriptConsole implements Console {
}
stack(ex: Error): string[] {
var stack = ex.getStackTrace();
var cache = [4' + ex];
var cache = [c' + ex];
//@ts-ignore
if (stack.class) {
stack = Arrays.asList(stack)
@@ -138,7 +146,7 @@ export class MiaoScriptConsole implements Console {
}
}
}
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${trace.lineNumber}§c)`);
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`);
}
});
return cache;

View File

@@ -1,14 +1,15 @@
'use strict';
/**
* MiaoScript Event处理类
*/
import '@ms/core'
import '@ms/nashorn'
import { injectable } from '@ms/container'
import i18n from '@ms/i18n'
import { injectable, unmanaged } from '@ms/container'
const Thread = Java.type('java.lang.Thread');
export namespace event {
/**
* 事件监听优先级
*/
export enum EventPriority {
LOWEST = "LOWEST",
LOW = "LOW",
@@ -25,7 +26,7 @@ export namespace event {
protected baseEventDir = '';
constructor(baseEventDir: string) {
constructor(@unmanaged() baseEventDir: string) {
this.baseEventDir = baseEventDir;
}
@@ -35,9 +36,7 @@ export namespace event {
* org.spongepowered.api.event.game.GameRegistryEvent.Register => gameregistryevent$register
*/
mapEventName() {
if (this.baseEventDir === "") {
throw new Error("base event dir is empty, can't map event name !");
}
if (this.baseEventDir === "") { throw new Error(i18n.translate('ms.api.event.empty.event.dir')); }
let count = 0;
let jar = this.getJarFile(this.baseEventDir);
let entries = jar.entries();
@@ -51,7 +50,7 @@ export namespace event {
let clazz = base.getClass(qualifiedName.substring(0, qualifiedName.length - 6));
if (this.isValidEvent(clazz)) {
let simpleName = this.class2Name(clazz).toLowerCase();
console.trace(`Mapping Event [${clazz.canonicalName}] => ${simpleName}`);
console.trace(i18n.translate("ms.api.event.mapping", { canonicalName: clazz.canonicalName, simpleName }));
this.mapEvent[simpleName] = clazz;
count++;
}
@@ -69,7 +68,7 @@ export namespace event {
let url = dirs.nextElement();
if (url.protocol === "jar") { return url.openConnection().jarFile; }
}
throw new Error(`Can't Mapping Event Because not found Resources ${resource}!`)
throw new Error(i18n.translate("ms.api.event.resource.not.found", { resource }))
}
class2Name(clazz: any) {
@@ -77,14 +76,13 @@ export namespace event {
}
name2Class(name: any, event: string) {
var eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
let eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
if (!eventCls) {
try {
eventCls = base.getClass(eventCls);
this.mapEvent[event] = eventCls;
} catch (ex) {
console.console(`§6插件 §b${name} §6注册事件 §c${event} §6失败 §4事件未找到!`);
console.ex(new Error(`Plugin ${name} register event error ${event} not found!`));
console.i18n("ms.api.event.not.found", { name, event })
return;
}
}
@@ -94,14 +92,17 @@ export namespace event {
execute(name, exec, eventCls) {
return (...args: any[]) => {
try {
var time = new Date().getTime()
exec(args[args.length - 1]);
var cost = new Date().getTime() - time;
if (cost > 20) {
console.console(`§c注意! §6插件 §b${name} §6处理 §d${this.class2Name(eventCls)} §6事件 §c耗时 §4${cost}ms !`)
let event = args[args.length - 1];
if (eventCls.isAssignableFrom(event.getClass())) {
let time = Date.now()
exec(event);
let cost = Date.now() - time;
if (cost > 20) {
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
}
}
} catch (ex) {
console.console(`§6插件 §b${name} §6处理 §d${this.class2Name(eventCls)} §6事件时发生异常 §4${ex}`);
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
console.ex(ex);
}
}
@@ -115,8 +116,8 @@ export namespace event {
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
* @param ignoreCancel
*/
listen(plugin: any, event: string, exec: () => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('插件名称为空 请检查传入参数!');
listen(plugin: any, event: string, exec: (event: any) => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"));
var name = plugin.description.name;
var eventCls = this.name2Class(name, event);
if (!eventCls) { return; }
@@ -133,7 +134,7 @@ export namespace event {
if (!listenerMap[name]) listenerMap[name] = [];
var offExec = () => {
this.unregister(eventCls, listener);
console.debug(`[${name}] unregister event ${this.class2Name(eventCls)}`);
console.debug(i18n.translate("ms.api.event.unregister", { name, event: this.class2Name(eventCls) }));
};
var off = {
event: eventCls,
@@ -142,10 +143,14 @@ export namespace event {
};
listenerMap[name].push(off);
// noinspection JSUnresolvedVariable
console.debug(`[${name}] register event ${this.class2Name(eventCls)} => ${exec.name || '[anonymous]'}`);
console.debug(i18n.translate("ms.api.event.register", { name, event: this.class2Name(eventCls) }));
return off;
}
/**
* 关闭插件监听任务
* @param plugin 插件
*/
disable(plugin: any) {
var eventCache = this.listenerMap[plugin.description.name];
if (eventCache) {
@@ -154,8 +159,24 @@ export namespace event {
}
}
/**
* 判断
* @param clazz 事件类
*/
abstract isValidEvent(clazz: any): boolean;
/**
* 注册事件
* @param eventCls 事件类
* @param exec 执行器
* @param priority 优先级
* @param ignoreCancel 是否忽略已取消的事件
*/
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any;
/**
* 取消监听事件
* @param event 事件
* @param listener 监听器
*/
abstract unregister(event: any, listener: any): void;
}
}

View File

@@ -1,6 +1,7 @@
/// <reference types='@ms/ployfill' />
import "@ms/nashorn"
export * from './task'
export * from './event'
export * from './console'
export * from './channel'
export * from './command'
export * from './interfaces'

View File

@@ -4,7 +4,7 @@ export namespace plugin {
*/
export const Plugin = Symbol("Plugin");
/**
* MiaoScript Plugin
* MiaoScript Plugin Folder
*/
export const PluginFolder = Symbol("PluginFolder");
/**

View File

@@ -1,3 +1,5 @@
import { NativePluginManager } from './native_plugin'
export namespace server {
/**
* Runtime ServerType
@@ -26,6 +28,8 @@ export namespace server {
getService(service: string): any;
dispatchCommand(sender: string | any, command: string): boolean;
dispatchConsoleCommand(command: string): boolean;
getPluginsFolder(): string;
getNativePluginManager(): NativePluginManager;
sendJson(sender: string | any, json: object | string): void;
}
}

View File

@@ -0,0 +1,6 @@
export interface NativePluginManager {
load(name: string): boolean;
unload(name: string): boolean;
reload(name: string): boolean;
delete(name: string): boolean;
}

View File

@@ -1,9 +1,15 @@
import { injectable, DefaultContainer as container } from "@ms/container";
export namespace task {
export const TaskManager = Symbol('TaskManager')
export interface TaskManager {
/**
* 创建任务
* @param func 任务内容
*/
create(func: Function): task.Task;
/**
* 在主线程执行代码
* @param func 执行内容
*/
callSyncMethod(func: Function): any;
}
/**
@@ -21,16 +27,28 @@ export namespace task {
this.func = func;
}
/**
* 设置任务异步执行
* @param isAsync 是否异步
*/
async(isAsync: boolean = true): task.Task {
this.isAsync = isAsync;
return this;
}
/**
* 设置任务延时执行
* @param tick 延时 Tick
*/
later(tick: number): task.Task {
this.laterTime = tick;
return this;
}
/**
* 设置任务循环执行
* @param tick 循环时间 Tick
*/
timer(tick: number): task.Task {
this.interval = tick;
return this;
@@ -45,6 +63,9 @@ export namespace task {
}
}
/**
* 提交任务
*/
abstract submit(): Cancelable;
}
/**

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/bukkit",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript bukkit package",
"keywords": [
"miaoscript",
@@ -24,12 +24,11 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/api": "^0.2.1",
"@ms/common": "^0.2.1",
"@ms/container": "^0.2.1",
"@ms/types": "^0.2.1"
"@ms/api": "^0.4.0",
"@ms/common": "^0.4.0",
"@ms/container": "^0.4.0"
}
}

View File

@@ -0,0 +1,28 @@
import { channel, plugin } from '@ms/api'
import { inject, provideSingleton } from '@ms/container'
const Bukkit = org.bukkit.Bukkit
const PluginMessageListener = Java.type("org.bukkit.plugin.messaging.PluginMessageListener")
const Messenger = Bukkit.getMessenger()
@provideSingleton(channel.Channel)
export class BukkitChannel extends channel.Channel {
@inject(plugin.PluginInstance)
private pluginInstance: any;
send(player: any, channel: string, data: any) {
player.sendPluginMessage(this.pluginInstance, channel, data);
}
register(channel: string, listener: channel.ChannelListener) {
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, new PluginMessageListener({
onPluginMessageReceived: (/**String */ channel, /**Player */ player, /**byte[] */data) => {
listener(data, { channel, player, data })
}
}));
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel);
}
unregister(channel: string, listener: any) {
Messenger.unregisterIncomingPluginChannel(this.pluginInstance, channel)
Messenger.unregisterOutgoingPluginChannel(this.pluginInstance, channel)
}
}

View File

@@ -2,14 +2,14 @@ import '@ms/nashorn'
import { command, plugin } from '@ms/api'
import * as reflect from '@ms/common/dist/reflect'
import { injectable, postConstruct, inject } from '@ms/container'
import { provideSingleton, postConstruct, inject } from '@ms/container'
let Bukkit = org.bukkit.Bukkit;
let TabCompleter = Java.type('org.bukkit.command.TabCompleter');
let PluginCommand = Java.type('org.bukkit.command.PluginCommand');
let CommandExecutor = Java.type('org.bukkit.command.CommandExecutor');
@injectable()
@provideSingleton(command.Command)
export class BukkitCommand extends command.Command {
@inject(plugin.PluginInstance)
private pluginInstance: any

View File

@@ -1,5 +1,5 @@
import { event, server, plugin } from '@ms/api'
import { injectable, inject } from '@ms/container';
import { event, plugin } from '@ms/api'
import { inject, provideSingleton } from '@ms/container';
import * as reflect from '@ms/common/dist/reflect'
const Bukkit = Java.type("org.bukkit.Bukkit");
@@ -9,7 +9,7 @@ const Listener = Java.type("org.bukkit.event.Listener");
const EventPriority = Java.type("org.bukkit.event.EventPriority");
const EventExecutor = Java.type("org.bukkit.plugin.EventExecutor");
@injectable()
@provideSingleton(event.Event)
export class BukkitEvent extends event.Event {
@inject(plugin.PluginInstance)
private pluginInstance: any

View File

@@ -1,18 +1,15 @@
/// <reference types="@ms/types/dist/typings/bukkit" />
import { server, command, event, task } from '@ms/api'
import { server } from '@ms/api'
import { Container } from '@ms/container'
import { BukkitConsole } from './console';
import { BukkitEvent } from './event';
import { BukkitServer } from './server';
import { BukkitCommand } from './command';
import { BukkitTaskManager } from './task';
import './event';
import './server';
import './command';
import './channel';
import './task';
export default function BukkitImpl(container: Container) {
container.bind(server.Console).toConstantValue(BukkitConsole);
container.bind(event.Event).to(BukkitEvent).inSingletonScope();
container.bind(server.Server).to(BukkitServer).inSingletonScope();
container.bind(command.Command).to(BukkitCommand).inSingletonScope();
container.bind(task.TaskManager).to(BukkitTaskManager).inSingletonScope();
}

View File

@@ -1,12 +1,18 @@
import { server } from '@ms/api'
import { injectable } from '@ms/container';
import { provideSingleton } from '@ms/container';
import chat from './enhance/chat'
let Bukkit = org.bukkit.Bukkit;
@injectable()
@provideSingleton(server.Server)
export class BukkitServer implements server.Server {
private pluginsFolder: string;
constructor() {
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath();
}
getPlayer(name: string) {
return Bukkit.getPlayer(name)
}
@@ -31,6 +37,12 @@ export class BukkitServer implements server.Server {
dispatchConsoleCommand(command: string): boolean {
return Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)
}
getPluginsFolder(): string {
return this.pluginsFolder;
}
getNativePluginManager() {
return Bukkit.getPluginManager() as any;
}
sendJson(sender: string | any, json: object | string): void {
if (typeof sender === "string") {
sender = this.getPlayer(sender)

View File

@@ -1,11 +1,11 @@
import { task, plugin } from '@ms/api'
import { injectable, inject } from '@ms/container';
import { inject, provideSingleton } from '@ms/container';
const Bukkit = Java.type('org.bukkit.Bukkit');
const BukkitRunnable = Java.type('org.bukkit.scheduler.BukkitRunnable');
const Callable = Java.type('java.util.concurrent.Callable')
@injectable()
@provideSingleton(task.TaskManager)
export class BukkitTaskManager implements task.TaskManager {
@inject(plugin.PluginInstance)
private pluginInstance: any;

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/bungee",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript bungee package",
"keywords": [
"miaoscript",
@@ -24,12 +24,11 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/api": "^0.2.1",
"@ms/common": "^0.2.1",
"@ms/container": "^0.2.1",
"@ms/types": "^0.2.1"
"@ms/api": "^0.4.0",
"@ms/common": "^0.4.0",
"@ms/container": "^0.4.0"
}
}

View File

@@ -0,0 +1,25 @@
import { channel, event } from '@ms/api'
import { provideSingleton, inject } from '@ms/container'
const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
@provideSingleton(channel.Channel)
export class BungeeChannel extends channel.Channel {
@inject(event.Event)
private eventManager: event.Event;
send(player: any, channel: string, data: any) {
throw new Error("Method not implemented.");
}
register(channel: string, listener: channel.ChannelListener) {
Bungee.registerChannel(channel);
// console.console('§6[§eWARN§6] §eMiaoScript channel in BungeeCord only register. you need self hanler PluginMessageEvent!')
return this.eventManager.listen({ description: { name: channel } }, "PluginMessageEvent", (event: net.md_5.bungee.api.event.PluginMessageEvent) => {
listener(event.getData(), event)
})
}
unregister(channel: string, listener: any) {
Bungee.unregisterChannel(channel);
listener.off();
}
}

View File

@@ -1,6 +1,5 @@
import { command, plugin } from "@ms/api";
import { inject, injectable } from "@ms/container";
import * as ref from '@ms/common/dist/reflect'
import { inject, provideSingleton } from "@ms/container";
const Arrays = Java.type('java.util.Arrays')
const Command = Java.extend(Java.type('net.md_5.bungee.api.plugin.Command'), Java.type('net.md_5.bungee.api.plugin.TabExecutor'));
@@ -13,26 +12,7 @@ const createCommand = eval(`
}
`)
class SimpleCommand {
public callable: any;
private name: string;
private executor: Function;
private tabComplete: Function = () => [];
constructor(command: string) {
this.name = command;
this.callable = createCommand(Command, command,
(sender, args) => this.executor(sender, '', command, args),
(sender, args) => Arrays.asList(this.tabComplete(sender, '', command, args))
);
}
setExecutor = (executor: Function) => this.executor = executor;
setTabComplete = (tabComplete: Function) => this.tabComplete = tabComplete;
toString = () => `Bungee SimpleCommand(${this.name})`
}
@injectable()
@provideSingleton(command.Command)
export class BungeeCommand extends command.Command {
@inject(plugin.PluginInstance)
private pluginInstance: any;
@@ -64,3 +44,22 @@ export class BungeeCommand extends command.Command {
return plugin.description.name.toLowerCase() + ":" + command;
}
}
class SimpleCommand {
public callable: any;
private name: string;
private executor: Function;
private tabComplete: Function = () => [];
constructor(command: string) {
this.name = command;
this.callable = createCommand(Command, command,
(sender, args) => this.executor(sender, '', command, args),
(sender, args) => Arrays.asList(this.tabComplete(sender, '', command, args))
);
}
setExecutor = (executor: Function) => this.executor = executor;
setTabComplete = (tabComplete: Function) => this.tabComplete = tabComplete;
toString = () => `Bungee SimpleCommand(${this.name})`
}

View File

@@ -1,5 +1,5 @@
import { event, plugin } from '@ms/api'
import { injectable, inject, postConstruct } from '@ms/container'
import { event } from '@ms/api'
import { provideSingleton, postConstruct } from '@ms/container'
import * as reflect from '@ms/common/dist/reflect'
const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
@@ -21,10 +21,8 @@ EventPriority[event.EventPriority.HIGHEST] = Byte.valueOf(64);
/**
* Bungee Event Impl
*/
@injectable()
@provideSingleton(event.Event)
export class BungeeEvent extends event.Event {
@inject(plugin.PluginInstance)
private pluginInstance: any;
private pluginManager = Bungee.getPluginManager()
// EventBus

View File

@@ -1,18 +1,15 @@
/// <reference types="@ms/types/dist/typings/bungee" />
import { server, command, event, task } from '@ms/api'
import { server } from '@ms/api'
import { Container } from '@ms/container'
import { BungeeConsole } from './console';
import { BungeeEvent } from './event';
import { BungeeServer } from './server';
import { BungeeCommand } from './command';
import { BungeeTaskManager } from './task';
import './event';
import './server';
import './command';
import './channel';
import './task';
export default function BungeeImpl(container: Container) {
container.bind(server.Console).toConstantValue(BungeeConsole);
container.bind(event.Event).to(BungeeEvent).inSingletonScope();
container.bind(server.Server).to(BungeeServer).inSingletonScope();
container.bind(command.Command).to(BungeeCommand).inSingletonScope();
container.bind(task.TaskManager).to(BungeeTaskManager).inSingletonScope();
}

View File

@@ -1,10 +1,16 @@
import { server } from '@ms/api'
import { injectable } from '@ms/container';
import { provideSingleton } from '@ms/container';
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
@injectable()
@provideSingleton(server.Server)
export class BungeeServer implements server.Server {
private pluginsFolder: string;
constructor() {
this.pluginsFolder = Bungee.getPluginsFolder().getCanonicalPath();
}
getPlayer(name: string) {
return Bungee.getPlayer(name);
}
@@ -29,6 +35,12 @@ export class BungeeServer implements server.Server {
dispatchConsoleCommand(command: string): boolean {
return Bungee.getPluginManager().dispatchCommand(Bungee.getConsole(), command)
}
getPluginsFolder(): string {
return this.pluginsFolder;
}
getNativePluginManager() {
return Bungee.getPluginManager() as any
}
sendJson(sender: string | any, json: string): void {
throw new Error("Method not implemented.");
}

View File

@@ -1,10 +1,10 @@
import { task, plugin } from '@ms/api'
import { injectable, inject } from '@ms/container';
import { inject, provideSingleton } from '@ms/container';
var Runnable = Java.type('java.lang.Runnable')
let TimeUnit = Java.type('java.util.concurrent.TimeUnit')
@injectable()
@provideSingleton(task.TaskManager)
export class BungeeTaskManager implements task.TaskManager {
@inject(plugin.PluginInstance)
private pluginInstance: any;

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@ms/client",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript client package",
"keywords": [
"miaoscript",
@@ -30,6 +30,6 @@
"devDependencies": {
"@nestjs/cli": "^6.14.2",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
}
}

View File

@@ -21,6 +21,10 @@ function createConnection(host: string, port: number, username: string) {
return client;
}
client.on('error', (error) => {
console.log("Client Error", error)
})
client.on('end', (resone) => {
console.log("Client End Resone:", resone)
client = createConnection('192.168.2.5', 25577, username)
@@ -29,19 +33,31 @@ client.on('end', (resone) => {
const rl = createInterface({
input: process.stdin,
output: process.stdout,
completer: (line, func) => {
let args = line.split(' ')
let comp = args[args.length - 1]
client.once('tab_complete', (msg) => {
let mcts = msg.matches.filter(s => s)
func(null, [mcts, comp])
})
client.write('tab_complete', {
text: line
})
},
terminal: true,
prompt: ''
})
rl.on('line', function(line) {
rl.on('line', function (line) {
switch (line) {
case "":
break;
case "eval":
break;
case "write":
break;
case "/respawn":
client.write('client_command', { payload: 0 })
// client.write("respawn", {
// })
break;
case "//reco":
client.end("")

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/common",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -24,11 +24,10 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/nashorn": "^0.2.1",
"@ms/ployfill": "^0.2.1"
"@ms/nashorn": "^0.4.0"
},
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
}

View File

@@ -1,4 +1,7 @@
import '@ms/api'
const URL = Java.type('java.net.URL')
const Paths = Java.type('java.nio.file.Paths');
const Files = Java.type('java.nio.file.Files');
const StandardCopyOption = Java.type('java.nio.file.StandardCopyOption');
export type Method =
| 'get' | 'GET'
@@ -31,8 +34,14 @@ function request(config: RequestConfig) {
return xhr.get();
}
function download(url: string, target: string) {
console.debug(`Start Download file ${target} from ${url}....`)
Files.copy(new URL(url).openStream(), Paths.get(target), StandardCopyOption.REPLACE_EXISTING);
console.debug(`File ${target} Download Complate...`)
}
function _proxy(method: Method) {
return function(url: string, data?: any, config?: RequestConfig) {
return function (url: string, data?: any, config?: RequestConfig) {
return request({ url, method, data, ...config });
}
}
@@ -40,5 +49,6 @@ function _proxy(method: Method) {
export default {
get: _proxy('GET'),
post: _proxy('POST'),
request
request,
download
}

View File

@@ -1,4 +1,3 @@
import '@ms/core'
/**
* 反射工具类
* Created by MiaoWoo on 2017/2/9 0009.

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/compile",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript compile package",
"keywords": [
"miaoscript",
@@ -24,6 +24,6 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/container",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript container package",
"keywords": [
"miaoscript",
@@ -24,9 +24,10 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
},
"dependencies": {
"inversify": "^5.0.1",
"inversify-binding-decorators": "^4.0.0"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/core",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -24,15 +24,11 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/api": "^0.2.1",
"@ms/bukkit": "^0.2.1",
"@ms/common": "^0.2.1",
"@ms/container": "^0.2.1",
"@ms/plugin": "^0.2.1",
"@ms/sponge": "^0.2.1"
"@ms/api": "^0.4.0",
"@ms/container": "^0.4.0"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

View File

@@ -1,12 +1,10 @@
import '@ms/ployfill'
let containerStartTime = new Date().getTime()
console.log(`Initialization MiaoScript IOC Container @ms/container. Please wait...`)
let containerStartTime = Date.now();
console.i18n("ms.core.ioc.initialize");
import { plugin, server, task } from '@ms/api'
import { PluginManagerImpl } from '@ms/plugin'
import { DefaultContainer as container, injectable, inject, ContainerInstance } from '@ms/container'
console.log('MiaoScript IOC Container @ms/container loading completed(' + (new Date().getTime() - containerStartTime) / 1000 + 's)!');
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule } from '@ms/container'
console.i18n("ms.core.ioc.completed", { time: (Date.now() - containerStartTime) / 1000 })
@injectable()
@provideSingleton(MiaoScriptCore)
class MiaoScriptCore {
@inject(server.Console)
private Console: Console;
@@ -39,15 +37,16 @@ class MiaoScriptCore {
loadPlugins() {
let loadPluginStartTime = new Date().getTime()
console.log(`Initialization MiaoScript Plugin System. Please wait...`)
console.i18n("ms.core.plugin.initialize")
this.pluginManager.scan(this.pluginFolder);
this.pluginManager.build();
this.pluginManager.load();
this.pluginManager.enable();
console.log('MiaoScript Plugin System loading completed(' + (new Date().getTime() - loadPluginStartTime) / 1000 + 's)!');
console.i18n("ms.core.plugin.completed", { time: (new Date().getTime() - loadPluginStartTime) / 1000 })
}
disable() {
console.i18n("ms.core.engine.disable")
this.pluginManager.disable();
}
}
@@ -82,15 +81,15 @@ function initialize() {
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance());
container.bind(plugin.PluginFolder).toConstantValue('plugins');
let type = detectServer();
console.info(`Detect Compatible Server set ServerType to ${type} ...`)
console.i18n("ms.core.initialize.detect", { type });
container.bind(server.ServerType).toConstantValue(type);
console.log(`Initialization MiaoScript Package @ms/core @ms/${type}. Please wait...`)
console.i18n("ms.core.package.initialize", { type });
require(`@ms/${type}`).default(container);
container.bind(plugin.PluginManager).to(PluginManagerImpl).inSingletonScope();
container.bind(MiaoScriptCore).to(MiaoScriptCore).inSingletonScope();
console.log(`MiaoScript Package @ms/core @ms/${type} loading completed(` + (new Date().getTime() - corePackageStartTime) / 1000 + 's)!');
require('@ms/plugin')
container.load(buildProviderModule());
console.i18n("ms.core.package.completed", { type, time: (Date.now() - corePackageStartTime) / 1000 });
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
console.log('MiaoScript ScriptEngine loading completed... Done (' + (new Date().getTime() - global.NashornEngineStartTime) / 1000 + 's)!');
console.i18n("ms.core.engine.completed", { time: (Date.now() - global.NashornEngineStartTime) / 1000 });
return disable;
}

View File

@@ -0,0 +1,40 @@
ms.ployfill.initialize: "Initialization Java Nashorn ployfill. Please wait..."
ms.ployfill.completed: "Java Nashorn ployfill loading completed... Cost ({time}s)!"
ms.core.ioc.initialize: "Initialization MiaoScript IOC Container @ms/container. Please wait..."
ms.core.ioc.completed: "MiaoScript IOC Container @ms/container loading completed({time}s)!"
ms.core.initialize.detect: "Detect Compatible Server set ServerType to {type} ..."
ms.core.package.initialize: "Initialization MiaoScript Package @ms/core @ms/{type} @ms/plugin. Please wait..."
ms.core.package.completed: "MiaoScript Package @ms/core @ms/{type} @ms/plugin loading completed({time}s)!"
ms.core.plugin.initialize: "Initialization MiaoScript Plugin System. Please wait..."
ms.core.plugin.completed: "MiaoScript Plugin System loading completed({time}s)!"
ms.core.engine.completed: "MiaoScript ScriptEngine loading completed... Done({time}s)!"
ms.core.engine.disable: "Disable MiaoScript Engine..."
ms.api.event.resource.not.found: "Can't Mapping Event Because not found Resources {resource}!"
ms.api.event.empty.event.dir: "base event dir is empty, can't map event name !"
ms.api.event.mapping: "Mapping Event [{canonicalName}] => {simpleName}"
ms.api.event.not.found: "§6Plugin §b{name} §6register {event} error. event not found!"
ms.api.event.execute.slow: "§cWARN! §6Plugin §b{name} §6execute §d{event} §6evnet §ccost §4{cost}ms !"
ms.api.event.execute.error: "§6Plugin §b{name} §6execute §d{event} §6event error §4{ex}"
ms.api.event.listen.plugin.name.empty: "Plugin name can't be empty!"
ms.api.event.register: "[{name}] register event {event}"
ms.api.event.unregister: "[{name}] unregister event {event}"
ms.api.command.register.input.error: "CommandExec Must be a function... Input: {exec}"
ms.api.command.register: "[{plugin}] register command {name}({cmd})..."
ms.api.command.unregister: "[{plugin}] unregister command {name}..."
ms.api.command.execute.error: "§6Player {player} §6exec §b{plugin} §6Plugin Command §d{command} {args} §6error §4{ex}"
ms.api.command.tab.completer.error: "§6Player {player} §6exec §b{plugin} §6Plugin TabComplete §d{command} {args} §6error §4{ex}"
ms.plugin.initialize: "Initialization MiaoScript Plugin System: {plugin} ..."
ms.plugin.event.map: "Total {count} {type} Event Mapping Complate..."
ms.plugin.manager.scan: "Scanning Plugins in {folder} ..."
ms.plugin.manager.initialize.error: "§6Plugin §b{name} §6initialize error §4{ex}"
ms.plugin.manager.stage: "{stage} {plugin} version {version} by {author}"
ms.plugin.manager.stage.load: "Loading"
ms.plugin.manager.stage.enable: "Enabling"
ms.plugin.manager.stage.disable: "Disabling"
ms.plugin.manager.build.update: "Auto Update Plugin {name} ..."
ms.plugin.manager.build.not.extends: "§4Found error plugin §b{source} §4it's not extends interfaces.Plugin, the plugin will be ignore!"
ms.plugin.manager.build.exists: "§4Found duplicate plugin §b{exists} §4and §b{source}§4. the first plugin will be ignore!"
ms.plugin.manager.config.save.default: "[{plugin}] config {name}.{format} not exists. auto create from default variable..."

View File

@@ -0,0 +1,40 @@
ms.ployfill.initialize: "加载 Java Nashorn 补丁. 请稍候..."
ms.ployfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
ms.core.ioc.initialize: "初始化 MiaoScript IOC 容器 @ms/container. 请稍候..."
ms.core.ioc.completed: "MiaoScript IOC 容器 @ms/container 加载完成 耗时({time}s)"
ms.core.initialize.detect: "检测到兼容的服务器类型. 设置 ServerType 值 {type} ..."
ms.core.package.initialize: "初始化 MiaoScript 扩展 @ms/core @ms/{type} @ms/plugin. 请稍候..."
ms.core.package.completed: "MiaoScript 扩展 @ms/core @ms/{type} @ms/plugin 加载完成 耗时({time}s)"
ms.core.plugin.initialize: "MiaoScript 开始引导插件系统. 请稍候..."
ms.core.plugin.completed: "MiaoScript 插件加载完毕 耗时({time}s)!"
ms.core.engine.completed: "MiaoScript 脚本引擎 加载完毕... 耗时({time}s)!"
ms.core.engine.disable: "关闭 MiaoScript 引擎..."
ms.api.event.resource.not.found: "无法映射事件 未找到资源文件 {resource}!"
ms.api.event.empty.event.dir: "事件基础目录为空, 无法映射事件!"
ms.api.event.mapping: "映射事件 [{canonicalName}] => {simpleName}"
ms.api.event.not.found: "§6插件 §b{name} §6注册事件 §c{event} §6失败. §4事件未找到!"
ms.api.event.execute.slow: "§c注意! §6插件 §b{name} §6处理 §d{event} §6事件 §c耗时 §4{cost}ms !"
ms.api.event.execute.error: "§6插件 §b{name} §6处理 §d{event} §6事件时发生异常 §4{ex}"
ms.api.event.listen.plugin.name.empty: "插件名称为空 请检查传入参数!"
ms.api.event.register: "[{name}] 注册事件 {event}"
ms.api.event.unregister: "[{name}] 注销事件 {event}"
ms.api.command.register.input.error: "CommandExec 必须为一个函数... 输入: {exec}"
ms.api.command.register: "[{plugin}] 注册命令 {name}({cmd})..."
ms.api.command.unregister: "[{plugin}] 注销命令 {name}..."
ms.api.command.execute.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6命令时发生异常 §4{ex}"
ms.api.command.tab.completer.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6补全时发生异常 §4{ex}"
ms.plugin.initialize: "初始化 MiaoScript 插件系统: {plugin} ..."
ms.plugin.event.map: "总计 {count} 个 {type} 事件 映射完成..."
ms.plugin.manager.scan: "扫描 {folder} 文件夹中插件..."
ms.plugin.manager.initialize.error: "§6插件 §b{name} §6初始化错误 §4{ex}"
ms.plugin.manager.stage: "{stage} {plugin} 版本 {version} 作者 {author}"
ms.plugin.manager.stage.load: "加载"
ms.plugin.manager.stage.enable: "启用"
ms.plugin.manager.stage.disable: "关闭"
ms.plugin.manager.build.update: "自动更新插件 {name} ..."
ms.plugin.manager.build.not.extends: "§4发现错误的插件 §b{source} §4未继承接口 interfaces.Plugin, 将不会被载入到服务器!"
ms.plugin.manager.build.duplicate: "§4发现已存在插件 §b{exists} §4和 §b{source}§4 存在冲突. 已存在插件将会被替换!"
ms.plugin.manager.config.save.default: "[{plugin}] 配置 {name}.{format} 不存在. 从默认值自动创建保存..."

View File

@@ -1,8 +1,7 @@
{
"private": true,
"name": "@ms/manager",
"version": "0.2.1",
"description": "MiaoScript manager package",
"name": "@ms/i18n",
"version": "0.4.0",
"description": "MiaoScript i18n package",
"keywords": [
"miaoscript",
"minecraft",
@@ -17,23 +16,20 @@
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"scripts": {
"dev": "ts-node-dev --respawn --debounce=1500 src/index.ts",
"clean": "rimraf dist",
"watch": "tsc --watch",
"build": "yarn clean && tsc",
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@cc-server/core": "^0.7.0",
"mongodb": "^3.5.3"
},
"devDependencies": {
"@types/express": "^4.17.2",
"@types/mongodb": "^3.3.16",
"@types/socket.io": "^2.1.4",
"@types/js-yaml": "^3.12.2",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"ts-node-dev": "^1.0.0-pre.44",
"typescript": "^3.8.2"
}
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/nashorn": "^0.4.0",
"js-yaml": "^3.13.1"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

View File

@@ -0,0 +1,51 @@
/// <reference types="@ms/nashorn" />
import * as yaml from 'js-yaml'
const File = Java.type("java.io.File");
const separatorChar = File.separatorChar;
let langMap = {};
let fallbackMap = {};
type TranslateParam = { [key: string]: any }
function translate(name: string, param?: TranslateParam) {
let langText: string = langMap[name] || fallbackMap[name];
if (!langText) { return '[WARN] @ms/i18n miss lang translate: ' + name }
for (const key in param) {
langText = langText.replace("{" + key + "}", param[key])
}
return langText;
}
function initialize(lang: string = 'zh_cn', fallback: string = 'zh_cn') {
langMap = readYamlFile(root, lang) || readYamlFile(concat(__dirname, '..'), lang)
fallbackMap = readYamlFile(root, fallback) || readYamlFile(concat(__dirname, '..'), fallback)
console.i18n = function i18n(name: string, param?: TranslateParam) {
console.log(translate(name, param))
}
}
function readYamlFile(dir: string, name: string) {
let langFile = concat(dir, 'languages', name + '.yml');
return exists(langFile) && yaml.safeLoad(base.read(langFile))
}
function concat(...args: string[]) {
return args.join(separatorChar)
}
function exists(path: string) {
return new File(path).exists()
}
declare global {
interface Console {
i18n(name: string, param?: TranslateParam);
}
}
export default {
initialize,
translate
};

View File

@@ -1,37 +0,0 @@
import { DBClient } from '@cc-server/db'
import { lazyInjectNamed } from '@cc-server/ioc'
import { controller, get, post, requestParam, requestBody, Vaild, NotBlank } from '@cc-server/binding'
class Plugins {
@NotBlank()
name?: string;
author?: string;
version?: string;
source?: string;
type?: string;
dist?: string;
}
type distType = 'npm' | 'git' | 'src'
@controller('/plugin')
class PluginController {
@lazyInjectNamed(DBClient, Plugins.name.toLocaleLowerCase())
private client: DBClient<Plugins>
@get('/')
index() {
return this.client.find({});
}
@get('/:id')
details(@requestParam("id") id: string) {
return this.client.findOneById(id);
}
@post('/')
add(@requestBody() @Vaild() model: Plugins) {
return this.client.insertOne(model);
}
}

View File

@@ -1,22 +0,0 @@
import * as path from 'path'
import { Db, MongoClient } from 'mongodb'
import { DBClient } from '@cc-server/db'
import { interfaces } from '@cc-server/ioc'
import { CcServerBoot } from '@cc-server/core'
import { MongoCollection, TYPE } from '@cc-server/db-mongo';
async function main() {
let server = new CcServerBoot();
let collectionCache = {};
server.container.bind(DBClient).toDynamicValue((context: interfaces.Context) => {
let name = context.currentRequest.target.getNamedTag().value;
if (!name) { return null }
if (!collectionCache[name]) { collectionCache[name] = new MongoCollection(context.container.get<Db>(TYPE.DB).collection(name)) }
return collectionCache[name];
})
let client = await MongoClient.connect("mongodb://192.168.2.5:27017", { useNewUrlParser: true, connectTimeoutMS: 10000 })
server.container.bind("MONGO_DB").toConstantValue(client.db("mspc"));
server.scan(path.join(__dirname, "controller")).start()
}
main()

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/nashorn",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -25,6 +25,6 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
}
}

View File

@@ -38,6 +38,37 @@ declare global {
setPrototypeOf(obj: object, prototype: object);
bindProperties(to: object, from: object);
}
namespace NodeJS {
interface Global {
logger: any;
debug: boolean;
level: string;
NashornEngineStartTime: number;
setGlobal: (key: string, value: any) => void;
noop: () => void;
console: Console;
}
}
var root: string;
var base: Core;
var ScriptEngineContextHolder: any;
function engineLoad(str: string): any;
interface Core {
getClass(name: String): any;
getProxyClass(): any;
getInstance(): any;
read(path: string): string;
save(path: string, content: string): void;
delete(path: string): void;
}
interface Console {
ex(err: Error): void;
stack(err: Error): string[];
sender(...args: any): void;
console(...args: any): void;
i18n(name: string, ...params: any[]);
}
}
export { };

View File

@@ -0,0 +1,33 @@
{
"name": "@ms/nodejs",
"version": "0.4.0",
"description": "MiaoScript nodejs package",
"keywords": [
"miaoscript",
"minecraft",
"bukkit",
"sponge"
],
"author": "MiaoWoo <admin@yumc.pw>",
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
},
"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.8.3"
},
"dependencies": {
"@ms/nashorn": "^0.4.0"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
}

View File

@@ -0,0 +1,455 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
// @ts-ignore
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter(this: any) {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function () {
return defaultMaxListeners;
},
set: function (arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function () {
// @ts-ignore
if (this._events === undefined ||
// @ts-ignore
this._events === Object.getPrototypeOf(this)._events) {
// @ts-ignore
this._events = Object.create(null);
// @ts-ignore
this._eventsCount = 0;
}
// @ts-ignore
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
// @ts-ignore
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
// @ts-ignore
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
// @ts-ignore
w.emitter = target;
// @ts-ignore
w.type = type;
// @ts-ignore
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper(this: any) {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
// @ts-ignore
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function (emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(this: any, type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}

View File

@@ -0,0 +1,51 @@
/// <reference types="@ms/nashorn" />
import * as yaml from 'js-yaml'
const File = Java.type("java.io.File");
const separatorChar = File.separatorChar;
let langMap = {};
let fallbackMap = {};
type TranslateParam = { [key: string]: any }
function translate(name: string, param?: TranslateParam) {
let langText: string = langMap[name] || fallbackMap[name];
if (!langText) { return '[WARN] @ms/i18n miss lang translate: ' + name }
for (const key in param) {
langText = langText.replace("{" + key + "}", param[key])
}
return langText;
}
function initialize(lang: string = 'zh_cn', fallback: string = 'zh_cn') {
langMap = readYamlFile(root, lang) || readYamlFile(concat(__dirname, '..'), lang)
fallbackMap = readYamlFile(root, fallback) || readYamlFile(concat(__dirname, '..'), fallback)
console.i18n = function i18n(name: string, param?: TranslateParam) {
console.log(translate(name, param))
}
}
function readYamlFile(dir: string, name: string) {
let langFile = concat(dir, 'languages', name + '.yml');
return exists(langFile) && yaml.safeLoad(base.read(langFile))
}
function concat(...args: string[]) {
return args.join(separatorChar)
}
function exists(path: string) {
return new File(path).exists()
}
declare global {
interface Console {
i18n(name: string, param?: TranslateParam);
}
}
export default {
initialize,
translate
};

View File

@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "src",
"outDir": "dist"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/nukkit",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript nukkit package",
"keywords": [
"miaoscript",
@@ -24,12 +24,11 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/api": "^0.2.1",
"@ms/common": "^0.2.1",
"@ms/container": "^0.2.1",
"@ms/types": "^0.2.1"
"@ms/api": "^0.4.0",
"@ms/common": "^0.4.0",
"@ms/container": "^0.4.0"
}
}

View File

@@ -1,12 +1,12 @@
import '@ms/nashorn'
import { command, plugin } from '@ms/api'
import { injectable, postConstruct, inject } from '@ms/container'
import { inject, provideSingleton, postConstruct } from '@ms/container'
let PluginCommand = Java.type('cn.nukkit.command.PluginCommand');
let CommandExecutor = Java.type('cn.nukkit.command.CommandExecutor');
@injectable()
@provideSingleton(command.Command)
export class NukkitCommand extends command.Command {
@inject(plugin.PluginInstance)
private pluginInstance: any
@@ -30,7 +30,6 @@ export class NukkitCommand extends command.Command {
}
}
onCommand(plugin: any, command: any, executor: Function) {
// 必须指定需要实现的接口类型 否则MOD服会报错
command.setExecutor(new CommandExecutor({
onCommand: super.setExecutor(plugin, command, executor)
}));

View File

@@ -1,5 +1,5 @@
import { event, server, plugin } from '@ms/api'
import { injectable, inject } from '@ms/container'
import { event, plugin } from '@ms/api'
import { inject, provideSingleton } from '@ms/container'
const Nukkit: cn.nukkit.Server = base.getInstance().getServer();
const Event = Java.type("cn.nukkit.event.Event");
@@ -8,7 +8,7 @@ const Listener = Java.type("cn.nukkit.event.Listener");
const EventPriority = Java.type("cn.nukkit.event.EventPriority");
const EventExecutor = Java.type("cn.nukkit.plugin.EventExecutor");
@injectable()
@provideSingleton(event.Event)
export class NukkitEvent extends event.Event {
@inject(plugin.PluginInstance)
private pluginInstance: any
@@ -42,6 +42,6 @@ export class NukkitEvent extends event.Event {
return listener;
}
unregister(event: any, listener: any): void {
event.getHandlers().unregister(listener);
event.getMethod('getHandlers').invoke(null).unregister(listener);
}
}

View File

@@ -1,18 +1,14 @@
/// <reference types="@ms/types/dist/typings/nukkit" />
import { server, command, event, task } from '@ms/api'
import { server } from '@ms/api'
import { Container } from '@ms/container'
import { NukkitConsole } from './console';
import { NukkitEvent } from './event';
import { NukkitServer } from './server';
import { NukkitCommand } from './command';
import { NukkitTaskManager } from './task';
import './event';
import './server';
import './command';
import './task';
export default function NukkitImpl(container: Container) {
container.bind(server.Console).toConstantValue(NukkitConsole);
container.bind(event.Event).to(NukkitEvent).inSingletonScope();
container.bind(server.Server).to(NukkitServer).inSingletonScope();
container.bind(command.Command).to(NukkitCommand).inSingletonScope();
container.bind(task.TaskManager).to(NukkitTaskManager).inSingletonScope();
}

View File

@@ -1,10 +1,17 @@
import { server } from '@ms/api'
import { injectable } from '@ms/container';
import { provideSingleton } from '@ms/container';
let Nukkit: cn.nukkit.Server = base.getInstance().getServer();
const File = Java.type("java.io.File");
@injectable()
@provideSingleton(server.Server)
export class NukkitServer implements server.Server {
private pluginsFolder: string;
constructor() {
this.pluginsFolder = new File(base.getInstance().getClass().getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile().getCanonicalPath()
}
getPlayer(name: string) {
return Nukkit.getPlayer(name)
}
@@ -29,6 +36,12 @@ export class NukkitServer implements server.Server {
dispatchConsoleCommand(command: string): boolean {
return Nukkit.dispatchCommand(Nukkit.getConsoleSender(), command)
}
getPluginsFolder(): string {
return this.pluginsFolder;
}
getNativePluginManager() {
return Nukkit.getPluginManager() as any;
}
sendJson(sender: string | any, json: object | string): void {
throw new Error("Method not implemented.");
}

View File

@@ -1,11 +1,9 @@
import { task, plugin } from '@ms/api'
import { injectable, inject } from '@ms/container';
import { inject, provideSingleton } from '@ms/container';
const Nukkit: cn.nukkit.Server = base.getInstance().getServer();
const NukkitRunnable = Java.type('cn.nukkit.scheduler.NukkitRunnable');
const Callable = Java.type('java.util.concurrent.Callable')
@injectable()
@provideSingleton(task.TaskManager)
export class NukkitTaskManager implements task.TaskManager {
@inject(plugin.PluginInstance)
private pluginInstance: any;

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/ployfill",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript ployfill package",
"author": "MiaoWoo <admin@yumc.pw>",
"homepage": "https://github.com/circlecloud/ms.git",
@@ -17,12 +17,13 @@
"test": "echo \"Error: run tests from root\" && exit 1"
},
"dependencies": {
"@ms/nashorn": "^0.2.1",
"@ms/i18n": "^0.4.0",
"@ms/nashorn": "^0.4.0",
"core-js": "^3.6.4"
},
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
}
}

View File

@@ -1,32 +0,0 @@
declare global {
namespace NodeJS {
interface Global {
logger: any;
debug: boolean;
level: string;
NashornEngineStartTime: number;
setGlobal: (key: string, value: any) => void;
noop: () => void;
console: Console;
}
}
var root: string;
var base: Core;
var ScriptEngineContextHolder: any;
function engineLoad(str: string): any;
interface Core {
getClass(name: String): any;
getProxyClass(): any;
getInstance(): any;
read(path: string): string;
save(path: string, content: string): void;
delete(path: string): void;
}
interface Console {
ex(err: Error): void;
stack(err: Error): string[];
sender(...args: any): void;
console(...args: any): void;
}
}
export { }

View File

@@ -1,10 +1,12 @@
/// <reference path="./global.ts" />
/// <reference types='@ms/nashorn' />
/// <reference types="@ms/nashorn" />
import i18n from '@ms/i18n'
let ployfillStartTime = new Date().getTime();
console.info('Initialization Java Nashorn ployfill. Please wait...');
i18n.initialize();
console.i18n("ms.ployfill.initialize");
require('./es5-ext');
require('core-js');
global.setGlobal('Proxy', require('./proxy').Proxy)
global.setGlobal('XMLHttpRequest', require('./xml-http-request').XMLHttpRequest)
global.setGlobal('Blob', require('blob-polyfill').Blob)
console.info('Java Nashorn ployfill loading completed... Cost (' + (new Date().getTime() - ployfillStartTime) / 1000 + 's)!');
console.i18n("ms.ployfill.completed", { time: (new Date().getTime() - ployfillStartTime) / 1000 });

View File

@@ -0,0 +1,141 @@
(function nashornEventLoopMain(context) {
'use strict';
var Thread = Java.type('java.lang.Thread');
var Phaser = Java.type('java.util.concurrent.Phaser');
var ArrayDeque = Java.type('java.util.ArrayDeque');
var HashMap = Java.type('java.util.HashMap');
var TimeUnit = Java.type("java.util.concurrent.TimeUnit");
var Runnable = Java.type('java.lang.Runnable');
var globalTimerId;
var timerMap;
var eventLoop;
var phaser = new Phaser();
// __NASHORN_POLYFILL_TIMER__ type is ScheduledExecutorService
var scheduler = context.__NASHORN_POLYFILL_TIMER__;
resetEventLoop();
// console.log('main javasript thread ' + Thread.currentThread().getName());
function resetEventLoop() {
globalTimerId = 1;
if (timerMap) {
timerMap.forEach(function(key, value) {
value.cancel(true);
})
}
timerMap = new HashMap();
eventLoop = new ArrayDeque();
}
function waitForMessages() {
phaser.register();
var wait = !(eventLoop.size() === 0);
phaser.arriveAndDeregister();
return wait;
}
function processNextMessages() {
var remaining = 1;
while (remaining) {
phaser.register();
var message = eventLoop.removeFirst();
remaining = eventLoop.size();
phaser.arriveAndDeregister();
var fn = message.fn;
var args = message.args;
try {
fn.apply(context, args);
} catch (e) {
console.trace(e);
console.trace(fn);
console.trace(args);
}
}
}
context.nashornEventLoop = {
process: function() {
while (waitForMessages()) {
processNextMessages()
}
},
reset: resetEventLoop
};
function createRunnable(fn, timerId, args, repeated) {
return new Runnable({
run: function() {
try {
var phase = phaser.register();
eventLoop.addLast({
fn: fn,
args: args
});
} catch (e) {
console.trace(e);
} finally {
if (!repeated) timerMap.remove(timerId);
phaser.arriveAndDeregister();
}
}
})
}
var setTimeout = function(fn, millis /* [, args...] */) {
var args = [].slice.call(arguments, 2, arguments.length);
var timerId = globalTimerId++;
var runnable = createRunnable(fn, timerId, args, false);
var task = scheduler.schedule(runnable, millis, TimeUnit.MILLISECONDS);
timerMap.put(timerId, task);
return timerId;
};
var setImmediate = function(fn /* [, args...] */) {
var args = [].slice.call(arguments, 1, arguments.length);
// @ts-ignore
return setTimeout(fn, 0, args);
}
var clearImmediate = function(timerId) {
clearTimeout(timerId);
}
var clearTimeout = function(timerId) {
var task = timerMap.get(timerId);
if (task) {
task.cancel(true);
timerMap.remove(timerId);
}
};
var setInterval = function(fn, delay /* [, args...] */) {
var args = [].slice.call(arguments, 2, arguments.length);
var timerId = globalTimerId++;
var runnable = createRunnable(fn, timerId, args, true);
var task = scheduler.scheduleWithFixedDelay(runnable, delay, delay, TimeUnit.MILLISECONDS);
timerMap.put(timerId, task);
return timerId;
};
var clearInterval = function(timerId) {
clearTimeout(timerId);
};
context.setTimeout = setTimeout;
context.clearTimeout = clearTimeout;
context.setImmediate = setImmediate;
context.clearImmediate = clearImmediate;
context.setInterval = setInterval;
context.clearInterval = clearInterval;
// @ts-ignore
})(typeof global !== "undefined" && global || typeof self !== "undefined" && self || this);

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/plugin",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -25,12 +25,13 @@
"@types/js-yaml": "^3.12.2",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/api": "^0.2.1",
"@ms/common": "^0.2.1",
"@ms/container": "^0.2.1",
"@ms/api": "^0.4.0",
"@ms/common": "^0.4.0",
"@ms/container": "^0.4.0",
"@ms/i18n": "^0.4.0",
"js-yaml": "^3.13.1"
}
}

View File

@@ -20,7 +20,13 @@ export namespace interfaces {
public disable() { }
}
interface BaseMetadata {
/**
* 名称 为空则为对象名称
*/
name?: string;
/**
* 支持的服务器列表 为空则代表所有
*/
servers?: string[];
}
export interface PluginMetadata extends BaseMetadata {
@@ -50,19 +56,37 @@ export namespace interfaces {
target?: any;
}
interface ExecMetadata extends BaseMetadata {
/**
* 执行器
*/
executor?: string;
}
export interface CommandMetadata extends ExecMetadata {
/**
* 参数列表
*/
paramtypes?: string[];
}
export interface TabCompleterMetadata extends ExecMetadata {
/**
* 参数列表
*/
paramtypes?: string[];
}
export interface ListenerMetadata extends ExecMetadata {
}
export interface ConfigMetadata extends BaseMetadata {
/**
* 配置文件版本号
*/
version?: number;
/**
* 实体变量名称
*/
variable?: string;
/**
* 配置文件格式 默认 yml
*/
format?: string;
}
export type PluginLike = Plugin | string;

View File

@@ -1,12 +1,13 @@
import i18n from '@ms/i18n'
import { plugin, server, command, event } from '@ms/api'
import { injectable, inject, postConstruct, Container, ContainerInstance } from '@ms/container'
import { inject, provideSingleton, postConstruct, Container, ContainerInstance } from '@ms/container'
import * as fs from '@ms/common/dist/fs'
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPlugin, getPluginTabCompleterMetadata, getPluginConfigMetadata } from './utils'
import { interfaces } from './interfaces'
import { getConfigLoader } from './config'
@injectable()
@provideSingleton(plugin.PluginManager)
export class PluginManagerImpl implements plugin.PluginManager {
@inject(ContainerInstance)
private container: Container
@@ -27,9 +28,9 @@ export class PluginManagerImpl implements plugin.PluginManager {
initialize() {
if (this.pluginInstance !== null) {
// 如果plugin不等于null 则代表是正式环境
console.info(`Initialization MiaoScript Plugin System: ${this.pluginInstance} ...`)
console.i18n('ms.plugin.initialize', { plugin: this.pluginInstance })
this.pluginMap = new Map()
console.info(`${this.EventManager.mapEventName().toFixed(0)} ${this.serverType} Event Mapping Complate...`)
console.i18n('ms.plugin.event.map', { count: this.EventManager.mapEventName().toFixed(0), type: this.serverType });
}
}
@@ -37,9 +38,9 @@ export class PluginManagerImpl implements plugin.PluginManager {
var plugin = fs.file(root, folder)
var files = []
// load common plugin
.concat(this.scanFloder(plugin))
.concat(this.scanFolder(plugin))
// load space plugin
.concat(this.scanFloder(fs.file(plugin, this.serverType)))
.concat(this.scanFolder(fs.file(plugin, this.serverType)))
this.loadPlugins(files)
}
@@ -48,12 +49,12 @@ export class PluginManagerImpl implements plugin.PluginManager {
}
private logStage(plugin: interfaces.Plugin, stage: string) {
console.log(`[${plugin.description.name}] ${stage} ${plugin.description.name} version ${plugin.description.version} by ${plugin.description.author || 'Unknow'}`)
console.i18n("ms.plugin.manager.stage", { stage, plugin: plugin.description.name, version: plugin.description.version, author: plugin.description.author })
}
load(...args: any[]): void {
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
this.logStage(plugin, "Loading")
this.logStage(plugin, i18n.translate("ms.plugin.manager.stage.load"))
this.loadConfig(plugin)
this.runCatch(plugin, 'load')
this.runCatch(plugin, `${this.serverType}load`)
@@ -62,21 +63,21 @@ export class PluginManagerImpl implements plugin.PluginManager {
enable(...args: any[]): void {
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
this.logStage(plugin, "Enabling")
this.runCatch(plugin, 'enable')
this.runCatch(plugin, `${this.serverType}enable`)
this.logStage(plugin, i18n.translate("ms.plugin.manager.stage.enable"))
this.registryCommand(plugin)
this.registryListener(plugin)
this.runCatch(plugin, 'enable')
this.runCatch(plugin, `${this.serverType}enable`)
})
}
disable(...args: any[]): void {
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
this.logStage(plugin, "Disabling")
this.runCatch(plugin, 'disable')
this.runCatch(plugin, `${this.serverType}disable`)
this.logStage(plugin, i18n.translate("ms.plugin.manager.stage.disable"))
this.unregistryCommand(plugin)
this.unregistryListener(plugin)
this.runCatch(plugin, 'disable')
this.runCatch(plugin, `${this.serverType}disable`)
})
}
@@ -98,7 +99,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
try {
if (pl[func]) pl[func].call(pl)
} catch (ex) {
console.console(`§6插件 §b${pl.description.name} §6执行 §d${func} §6方法时发生错误 §4${ex}`)
console.console(`§6Plugin §b${pl.description.name} §6exec §d${func} §6function error §4${ex}`)
console.ex(ex)
}
}
@@ -110,12 +111,12 @@ export class PluginManagerImpl implements plugin.PluginManager {
throw new Error(`Plugin ${JSON.stringify(name)} not exist!`)
}
private scanFloder(plugin: any): string[] {
private scanFolder(folder: any): string[] {
var files = []
console.info(`Scanning Plugins in ${plugin} ...`)
this.checkUpdateFolder(plugin)
console.i18n('ms.plugin.manager.scan', { folder })
this.checkUpdateFolder(folder)
// must check file is exist maybe is a illegal symbolic link file
fs.list(plugin).forEach((file: any) => file.toFile().exists() ? files.push(file.toFile()) : void 0)
fs.list(folder).forEach((file: any) => file.toFile().exists() ? files.push(file.toFile()) : void 0)
return files
}
@@ -146,7 +147,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
this.updatePlugin(file)
this.createPlugin(file)
} catch (ex) {
console.console(`§6插件 §b${file.name} §6初始化时发生错误 §4${ex.message}`)
console.i18n("ms.plugin.manager.initialize.error", { name: file.name, ex })
console.ex(ex)
}
}
@@ -154,14 +155,21 @@ export class PluginManagerImpl implements plugin.PluginManager {
private updatePlugin(file: any) {
var update = fs.file(fs.file(file.parentFile, 'update'), file.name)
if (update.exists()) {
console.info(`Auto Update Plugin ${file.name} ...`)
console.i18n("ms.plugin.manager.build.update", { name: file.name })
fs.move(update, file, true)
}
}
private checkServers(servers: string[]) {
if (!servers) { return true }
return servers?.indexOf(this.serverType) != -1 && servers?.indexOf(`!${this.serverType}`) == -1
private allowProcess(servers: string[]) {
// Not set servers allow
if (!servers) return true
// include !type deny
let denyServers = servers.filter(svr => svr.startsWith("!"))
if (denyServers.length !== 0) {
return !denyServers.includes(`!${this.serverType}`)
} else {
return servers.includes(this.serverType)
}
}
private createPlugin(file: string) {
@@ -172,27 +180,32 @@ export class PluginManagerImpl implements plugin.PluginManager {
private buildPlugins() {
let pluginMetadatas = getPluginMetadatas()
for (const [_, metadata] of pluginMetadatas) {
if (!this.checkServers(metadata.servers)) { continue }
if (!this.allowProcess(metadata.servers)) { continue }
this.buildPlugin(metadata)
}
}
private buildPlugin(metadata: interfaces.PluginMetadata) {
this.bindPlugin(metadata)
let pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
if (!(pluginInstance instanceof interfaces.Plugin)) {
console.console(`§4found error plugin §b${metadata.source} §4it's not extends interfaces.Plugin, the plugin will be ignore!`)
return
try {
this.bindPlugin(metadata)
let pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
if (!(pluginInstance instanceof interfaces.Plugin)) {
console.i18n('ms.plugin.manager.build.not.extends', { source: metadata.source })
return
}
this.pluginMap.set(metadata.name, pluginInstance)
return pluginInstance;
} catch (ex) {
console.i18n("ms.plugin.manager.initialize.error", { name: metadata.name, ex })
console.ex(ex)
}
this.pluginMap.set(metadata.name, pluginInstance)
return pluginInstance
}
private bindPlugin(metadata: interfaces.PluginMetadata) {
try {
let pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
if (pluginInstance.description.source + '' !== metadata.source + '') {
console.console(`§4found duplicate plugin §b${pluginInstance.description.source} §4and §b${metadata.source}§4. the first plugin will be ignore!`)
console.i18n('ms.plugin.manager.build.duplicate', { exists: pluginInstance.description.source, source: metadata.source })
}
this.container.rebind(plugin.Plugin).to(metadata.target).inSingletonScope().whenTargetNamed(metadata.name)
} catch{
@@ -204,11 +217,10 @@ export class PluginManagerImpl implements plugin.PluginManager {
let configs = getPluginConfigMetadata(plugin);
for (let [_, config] of configs) {
let configFile = fs.concat(root, this.pluginFolder, plugin.description.name, config.name + '.' + config.format)
console.log(configFile)
let configFactory = getConfigLoader(config.format);
if (!fs.exists(configFile)) {
base.save(configFile, configFactory.dump(plugin[config.variable]))
console.log(`[${plugin.description.name}] config ${config.name}.${config.format} don't exists auto create from default variable...`)
console.i18n("ms.plugin.manager.config.save.default", { plugin: plugin.description.name, name: config.name, format: config.format })
} else {
plugin[config.variable] = configFactory.load(base.read(configFile));
}
@@ -220,7 +232,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
let tabs = getPluginTabCompleterMetadata(pluginInstance)
for (const [_, cmd] of cmds) {
let tab = tabs.get(cmd.name)
if (!this.checkServers(cmd.servers)) { continue }
if (!this.allowProcess(cmd.servers)) { continue }
this.CommandManager.on(pluginInstance, cmd.name, {
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
tab: tab ? pluginInstance[tab.executor].bind(pluginInstance) : undefined
@@ -232,7 +244,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
let events = getPluginListenerMetadata(pluginInstance)
for (const event of events) {
// ignore space listener
if (!this.checkServers(event.servers)) { continue }
if (!this.allowProcess(event.servers)) { continue }
// here must bind this to pluginInstance
this.EventManager.listen(pluginInstance, event.name, pluginInstance[event.executor].bind(pluginInstance))
}

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@ms/plugins",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript plugins package",
"keywords": [
"miaoscript",
@@ -25,12 +25,11 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/plugin": "^0.2.1",
"axios": "^0.19.2",
"es6-map": "^0.1.5",
"inversify": "^5.0.1"
"@ms/api": "^0.4.0",
"@ms/container": "^0.4.0",
"@ms/plugin": "^0.4.0"
}
}

View File

@@ -23,33 +23,43 @@ export class HelloWorld extends interfaces.Plugin {
}
bukkitload() {
this.logger.log('Load When ServerType is Bukkit!')
this.logger.log('Plugin Load When ServerType is Bukkit!')
}
bukkitenable() {
this.logger.log('Enable When ServerType is Bukkit!')
this.logger.log('Plugin Enable When ServerType is Bukkit!')
}
bukkitdisable() {
this.logger.log('Disable When ServerType is Bukkit!')
this.logger.log('Plugin Disable When ServerType is Bukkit!')
}
spongeload() {
this.logger.log('Load When ServerType is Sponge!')
this.logger.log('Plugin Load When ServerType is Sponge!')
}
spongeenable() {
this.logger.log('Enable When ServerType is Sponge!')
this.logger.log('Plugin Enable When ServerType is Sponge!')
}
spongedisable() {
this.logger.log('Disable When ServerType is Sponge!')
this.logger.log('Plugin Disable When ServerType is Sponge!')
}
bungeeload() {
this.logger.log('Load When ServerType is BungeeCord!')
this.logger.log('Plugin Load When ServerType is BungeeCord!')
}
bungeeenable() {
this.logger.log('Enable When ServerType is BungeeCord!')
this.logger.log('Plugin Enable When ServerType is BungeeCord!')
}
bungeedisable() {
this.logger.log('Disable When ServerType is BungeeCord!')
this.logger.log('Plugin Disable When ServerType is BungeeCord!')
}
nukkitload() {
this.logger.log('Plugin Load When ServerType is Nukkit!')
}
nukkitenable() {
this.logger.log('Plugin Enable When ServerType is Nukkit!')
}
nukkitdisable() {
this.logger.log('Plugin Disable When ServerType is Nukkit!')
}
@cmd()

View File

@@ -2,8 +2,8 @@
/// <reference types="@ms/types/dist/typings/sponge" />
/// <reference types="@ms/types/dist/typings/bungee" />
import { server, plugin as pluginApi } from '@ms/api'
import { inject } from '@ms/container';
import { server, plugin as pluginApi, channel } from '@ms/api'
import { inject, optional } from '@ms/container';
import { plugin, interfaces, cmd, listener, tab, config } from '@ms/plugin'
import Tellraw from '@ms/common/dist/tellraw'
@@ -20,8 +20,6 @@ const BiConsumer = Java.type('java.util.function.BiConsumer')
class MiaoMessage {
// public static final String CHANNEL = "MiaoChat:Default".toLowerCase();
public static CHANNEL: string = "MiaoChat:Default".toLowerCase()
// public static final String NORMAL_CHANNEL = "MiaoChat:Normal".toLowerCase();
public static NORMAL_CHANNEL: string = "MiaoChat:Normal".toLowerCase()
// private static final int MAX_MESSAGE_LENGTH = 32000;
private static MAX_MESSAGE_LENGTH = 32000;
@@ -58,11 +56,10 @@ class MiaoMessage {
export class MiaoChat extends interfaces.Plugin {
@inject(server.Server)
private Server: server.Server
@inject(server.ServerType)
private ServerType: string
@inject(channel.Channel)
@optional() private Channel: channel.Channel
private spongeChannel: any;
private spongeListener: any;
private channelOff: { off: () => void };
@config()
private config = {
@@ -175,6 +172,7 @@ export class MiaoChat extends interfaces.Plugin {
}
disable() {
this.channelOff?.off()
}
bukkitenable() {
@@ -186,20 +184,9 @@ export class MiaoChat extends interfaces.Plugin {
} catch (ex) {
this.logger.console("§cCan't found me.clip.placeholderapi.PlaceholderAPI variable will not be replaced! Err: " + ex)
}
var Bukkit = org.bukkit.Bukkit;
var PluginMessageListener = Java.type("org.bukkit.plugin.messaging.PluginMessageListener")
Bukkit.getMessenger().registerIncomingPluginChannel(base.getInstance(), MiaoMessage.CHANNEL, new PluginMessageListener({
onPluginMessageReceived: (/**String */ var1, /**Player */ var2, /**byte[] */var3) => {
this.sendChatAll(MiaoMessage.decode(var3).json)
}
}));
Bukkit.getMessenger().registerOutgoingPluginChannel(base.getInstance(), MiaoMessage.CHANNEL);
}
bukkitdisable() {
var Bukkit = org.bukkit.Bukkit;
Bukkit.getMessenger().unregisterIncomingPluginChannel(base.getInstance(), MiaoMessage.CHANNEL)
Bukkit.getMessenger().unregisterOutgoingPluginChannel(base.getInstance(), MiaoMessage.CHANNEL)
this.channelOff = this.Channel?.listen(this, MiaoMessage.CHANNEL, (data) => {
this.sendChatAll(MiaoMessage.decode(data).json)
})
}
spongeenable() {
@@ -218,32 +205,25 @@ export class MiaoChat extends interfaces.Plugin {
} catch (ex) {
this.logger.console("§cCan't found me.rojo8399.placeholderapi.PlaceholderService variable will not be replaced! Err: " + ex)
}
var Sponge = org.spongepowered.api.Sponge
var RawDataListener = Java.type("org.spongepowered.api.network.RawDataListener")
var ChannelRegistrar = Sponge.getChannelRegistrar()
this.spongeChannel = ChannelRegistrar.getOrCreateRaw(base.getInstance(), MiaoMessage.CHANNEL)
this.spongeListener = new RawDataListener({
handlePayload: (/* ChannelBuf */ data, /**RemoteConnection */ connection, /**Platform.Type */ side) => {
this.sendChatAll(MiaoMessage.decode(data.readBytes(data.available())).json)
}
this.channelOff = this.Channel?.listen(this, MiaoMessage.CHANNEL, (data) => {
this.sendChatAll(MiaoMessage.decode(data).json)
})
this.spongeChannel.addListener(this.spongeListener)
}
spongedisable() {
this.spongeChannel.removeListener(this.spongeListener)
}
bungeeenable() {
let bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
bungee.registerChannel(MiaoMessage.CHANNEL);
bungee.registerChannel(MiaoMessage.NORMAL_CHANNEL);
}
bungeedisable() {
let bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
bungee.unregisterChannel(MiaoMessage.CHANNEL);
bungee.unregisterChannel(MiaoMessage.NORMAL_CHANNEL);
this.channelOff = this.Channel?.listen(this, MiaoMessage.CHANNEL, (data, event: net.md_5.bungee.api.event.PluginMessageEvent) => {
let bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
if (event.getTag() == MiaoMessage.CHANNEL) {
let origin = event.getSender().getAddress();
bungee.getServers().forEach(new BiConsumer({
accept: (s, server) => {
if (server.getAddress() != origin && server.getPlayers().size() > 0) {
server.sendData(event.getTag(), event.getData())
}
}
}))
}
})
}
@cmd({ servers: ["bungee"] })
@@ -285,22 +265,6 @@ export class MiaoChat extends interfaces.Plugin {
});
}
@listener({ servers: ['bungee'] })
PluginMessageEvent(e: any) {
let bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
let event = e as net.md_5.bungee.api.event.PluginMessageEvent
if (event.getTag() == MiaoMessage.CHANNEL || event.getTag() == MiaoMessage.NORMAL_CHANNEL) {
let origin = event.getSender().getAddress();
bungee.getServers().forEach(new BiConsumer({
accept: (s, server) => {
if (server.getAddress() != origin && server.getPlayers().size() > 0) {
server.sendData(event.getTag(), event.getData())
}
}
}))
}
}
initFormat(chatFormats: any[]) {
chatFormats.forEach(chatFormat => {
var chat_format_str = chatFormat.format;
@@ -336,7 +300,7 @@ export class MiaoChat extends interfaces.Plugin {
chat_format.format_list.forEach((format) => {
var style = this.styleFormats[format];
if (style) {
tr.then(this.replace(player, style.text));
tr.then(this.replace(player, style.text.replace(/&(\w)/g, '§$1')));
if (style.hover) {
tr.tip(this.replace(player, style.hover.join('\n')));
}
@@ -361,27 +325,7 @@ export class MiaoChat extends interfaces.Plugin {
});
let json = tr.then(this.replace(player, plain)).json()
this.sendChatAll(json)
let mm = MiaoMessage.encode(json);
switch (this.ServerType) {
case "bukkit":
if (mm == null) {
player.sendPluginMessage(base.getInstance(), MiaoMessage.NORMAL_CHANNEL, MiaoMessage.encode(tr.string()));
} else {
player.sendPluginMessage(base.getInstance(), MiaoMessage.CHANNEL, mm);
}
break;
case "sponge":
if (mm == null) {
this.spongeChannel.sendTo(player, new Consumer({
accept: (channelBuf) => channelBuf.writeBytes(MiaoMessage.encode(tr.string()))
}))
} else {
this.spongeChannel.sendTo(player, new Consumer({
accept: (channelBuf) => channelBuf.writeBytes(mm)
}))
}
break;
}
this.Channel?.send(player, MiaoMessage.CHANNEL, MiaoMessage.encode(json))
}
sendChatAll(json: string) {

View File

@@ -16,7 +16,7 @@ const refList: Array<{ server: string, future: string }> = [
{ server: 'func_147137_ag', future: 'field_151274_e' }//catserver 1.12.2
]
@plugin({ name: 'MiaoConsole', version: '1.0.0', author: 'MiaoWoo', source: __filename })
@plugin({ name: 'MiaoConsole', version: '1.0.0', author: 'MiaoWoo', servers: ['!nukkit'], source: __filename })
export class MiaoConsole extends interfaces.Plugin {
public static GlobalContainer: Container
public static GlobalLogger: Console
@@ -98,6 +98,7 @@ export class MiaoConsole extends interfaces.Plugin {
}
injectMiaoDetect() {
let MiaoDetectHandler = getMiaoDetectHandler();
this.pipeline.addFirst('miao_detect', new MiaoDetectHandler())
this.container.bind(MessageHandle).toFunction(this.onmessage.bind(this))
this.logger.info('Netty Channel Pipeline Inject MiaoDetectHandler Successful!')
@@ -132,111 +133,118 @@ export class MiaoConsole extends interfaces.Plugin {
}
sendResult(ctx: any, type: string, msg: string) {
let TextWebSocketFrame = getTextWebSocketFrame()
ctx.writeAndFlush(new TextWebSocketFrame(`${type}${SPLIT_LINE}${msg}`))
}
}
const ChannelInboundHandlerAdapter = Java.type('io.netty.channel.ChannelInboundHandlerAdapter')
const CharsetUtil = Java.type('io.netty.util.CharsetUtil')
const TextWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.TextWebSocketFrame')
const MiaoDetectHandler = Java.extend(ChannelInboundHandlerAdapter, {
channelRead: (ctx: any, channel: any) => {
channel.pipeline().addFirst('miaowebsocket', new WebSocketHandler())
ctx.fireChannelRead(channel)
}
})
const TypeParameterMatcher = Java.type('io.netty.util.internal.TypeParameterMatcher')
const DefaultHttpResponse = Java.type('io.netty.handler.codec.http.DefaultHttpResponse')
const DefaultFullHttpResponse = Java.type('io.netty.handler.codec.http.DefaultFullHttpResponse')
const HttpHeaders = Java.type('io.netty.handler.codec.http.HttpHeaders')
const HttpVersion = Java.type('io.netty.handler.codec.http.HttpVersion')
const HttpResponseStatus = Java.type('io.netty.handler.codec.http.HttpResponseStatus')
const LastHttpContent = Java.type('io.netty.handler.codec.http.LastHttpContent')
const HttpServerCodec = Java.type('io.netty.handler.codec.http.HttpServerCodec')
const ChunkedWriteHandler = Java.type('io.netty.handler.stream.ChunkedWriteHandler')
const HttpObjectAggregator = Java.type('io.netty.handler.codec.http.HttpObjectAggregator')
const WebSocketServerProtocolHandler = Java.type('io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler')
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
const FullHttpRequestMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.FullHttpRequest'))
const File = Java.type('java.io.File')
const Runnable = Java.type('java.lang.Runnable')
const RandomAccessFile = Java.type('java.io.RandomAccessFile')
const DefaultFileRegion = Java.type('io.netty.channel.DefaultFileRegion')
const ChannelFutureListener = Java.type('io.netty.channel.ChannelFutureListener')
const HttpRequestHandler = Java.extend(SimpleChannelInboundHandler, {
acceptInboundMessage: (msg: any) => {
return FullHttpRequestMatcher.match(msg)
},
channelRead0: (ctx: any, request: any) => {
if ('/ws' == request.getUri()) {
ctx.fireChannelRead(request.retain())
} else {
ctx.executor().execute(new Runnable({
run: () => {
if (HttpHeaders.is100ContinueExpected(request)) {
ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE))
}
let filename = request.getUri().split('?')[0].substr(1)
let file = new File('/home/project/WebWorkSpace/MiaoConsole', filename || 'index.html')
if (!file.exists() || !file.isFile()) {
ctx.write(new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND))
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE)
return
}
let response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK)
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html charset=UTF-8")
let raf = new RandomAccessFile(file, 'r')
let keepAlive = HttpHeaders.isKeepAlive(request)
if (keepAlive) {
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length())
response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE)
}
ctx.write(response)
ctx.write(new DefaultFileRegion(raf.getChannel(), 0, raf.length()))
let future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT)
if (!keepAlive) {
future.addListener(ChannelFutureListener.CLOSE)
}
}
}))
function getMiaoDetectHandler() {
const ChannelInboundHandlerAdapter = Java.type('io.netty.channel.ChannelInboundHandlerAdapter')
const CharsetUtil = Java.type('io.netty.util.CharsetUtil')
const MiaoDetectHandler = Java.extend(ChannelInboundHandlerAdapter, {
channelRead: (ctx: any, channel: any) => {
channel.pipeline().addFirst('miaowebsocket', new WebSocketHandler())
ctx.fireChannelRead(channel)
}
}
})
const TextWebSocketFrameMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.websocketx.TextWebSocketFrame'))
const TextWebSocketFrameHandler = Java.extend(SimpleChannelInboundHandler, {
userEventTriggered: (ctx: any, evt: any) => {
if (evt == 'HANDSHAKE_COMPLETE') {
clients.push(ctx.channel())
MiaoConsole.GlobalLogger.console(`new client §b${ctx.channel().id()} §aconnected...`)
})
const TypeParameterMatcher = Java.type('io.netty.util.internal.TypeParameterMatcher')
const DefaultHttpResponse = Java.type('io.netty.handler.codec.http.DefaultHttpResponse')
const DefaultFullHttpResponse = Java.type('io.netty.handler.codec.http.DefaultFullHttpResponse')
const HttpHeaders = Java.type('io.netty.handler.codec.http.HttpHeaders')
const HttpVersion = Java.type('io.netty.handler.codec.http.HttpVersion')
const HttpResponseStatus = Java.type('io.netty.handler.codec.http.HttpResponseStatus')
const LastHttpContent = Java.type('io.netty.handler.codec.http.LastHttpContent')
const HttpServerCodec = Java.type('io.netty.handler.codec.http.HttpServerCodec')
const ChunkedWriteHandler = Java.type('io.netty.handler.stream.ChunkedWriteHandler')
const HttpObjectAggregator = Java.type('io.netty.handler.codec.http.HttpObjectAggregator')
const WebSocketServerProtocolHandler = Java.type('io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler')
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
const FullHttpRequestMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.FullHttpRequest'))
const File = Java.type('java.io.File')
const Runnable = Java.type('java.lang.Runnable')
const RandomAccessFile = Java.type('java.io.RandomAccessFile')
const DefaultFileRegion = Java.type('io.netty.channel.DefaultFileRegion')
const ChannelFutureListener = Java.type('io.netty.channel.ChannelFutureListener')
const HttpRequestHandler = Java.extend(SimpleChannelInboundHandler, {
acceptInboundMessage: (msg: any) => {
return FullHttpRequestMatcher.match(msg)
},
channelRead0: (ctx: any, request: any) => {
if ('/ws' == request.getUri()) {
ctx.fireChannelRead(request.retain())
} else {
ctx.executor().execute(new Runnable({
run: () => {
if (HttpHeaders.is100ContinueExpected(request)) {
ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE))
}
let filename = request.getUri().split('?')[0].substr(1)
let file = new File('/home/project/WebWorkSpace/MiaoConsole', filename || 'index.html')
if (!file.exists() || !file.isFile()) {
ctx.write(new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND))
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE)
return
}
let response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK)
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html charset=UTF-8")
let raf = new RandomAccessFile(file, 'r')
let keepAlive = HttpHeaders.isKeepAlive(request)
if (keepAlive) {
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length())
response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE)
}
ctx.write(response)
ctx.write(new DefaultFileRegion(raf.getChannel(), 0, raf.length()))
let future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT)
if (!keepAlive) {
future.addListener(ChannelFutureListener.CLOSE)
}
}
}))
}
}
},
acceptInboundMessage: (msg: any) => {
return TextWebSocketFrameMatcher.match(msg)
},
channelRead0: (ctx: any, msg: any) => {
MiaoConsole.GlobalContainer.get<any>(MessageHandle)(ctx, msg)
}
})
const WebSocketHandler = Java.extend(ChannelInboundHandlerAdapter, {
channelRead: function(ctx: any, msg: any) {
msg.markReaderIndex()
let message: string = msg.toString(CharsetUtil.UTF_8)
let channel = ctx.channel()
let pipeline = channel.pipeline()
if (message.indexOf('HTTP/1.1') > 0) {
pipeline.names().forEach(f => {
if (f == 'miaowebsocket' || f.indexOf('DefaultChannelPipeline') > -1) { return }
pipeline.remove(f)
})
pipeline.addLast('http', new HttpServerCodec())
pipeline.addLast('chunk', new ChunkedWriteHandler())
pipeline.addLast('httpobj', new HttpObjectAggregator(64 * 1024))
pipeline.addLast('http_request', new HttpRequestHandler())
pipeline.addLast('websocket', new WebSocketServerProtocolHandler("/ws"))
pipeline.addLast('websocket_handler', new TextWebSocketFrameHandler())
})
const TextWebSocketFrameMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.websocketx.TextWebSocketFrame'))
const TextWebSocketFrameHandler = Java.extend(SimpleChannelInboundHandler, {
userEventTriggered: (ctx: any, evt: any) => {
if (evt == 'HANDSHAKE_COMPLETE') {
clients.push(ctx.channel())
MiaoConsole.GlobalLogger.console(`new client §b${ctx.channel().id()} §aconnected...`)
}
},
acceptInboundMessage: (msg: any) => {
return TextWebSocketFrameMatcher.match(msg)
},
channelRead0: (ctx: any, msg: any) => {
MiaoConsole.GlobalContainer.get<any>(MessageHandle)(ctx, msg)
}
pipeline.remove('miaowebsocket')
msg.resetReaderIndex()
ctx.fireChannelRead(msg)
}
})
})
const WebSocketHandler = Java.extend(ChannelInboundHandlerAdapter, {
channelRead: function(ctx: any, msg: any) {
msg.markReaderIndex()
let message: string = msg.toString(CharsetUtil.UTF_8)
let channel = ctx.channel()
let pipeline = channel.pipeline()
if (message.indexOf('HTTP/1.1') > 0) {
pipeline.names().forEach(f => {
if (f == 'miaowebsocket' || f.indexOf('DefaultChannelPipeline') > -1) { return }
pipeline.remove(f)
})
pipeline.addLast('http', new HttpServerCodec())
pipeline.addLast('chunk', new ChunkedWriteHandler())
pipeline.addLast('httpobj', new HttpObjectAggregator(64 * 1024))
pipeline.addLast('http_request', new HttpRequestHandler())
pipeline.addLast('websocket', new WebSocketServerProtocolHandler("/ws"))
pipeline.addLast('websocket_handler', new TextWebSocketFrameHandler())
}
pipeline.remove('miaowebsocket')
msg.resetReaderIndex()
ctx.fireChannelRead(msg)
}
})
return MiaoDetectHandler;
}
function getTextWebSocketFrame() {
return Java.type('io.netty.handler.codec.http.websocketx.TextWebSocketFrame')
}

View File

@@ -1,26 +1,97 @@
/// <reference types="@ms/types" />
import { task, server } from "@ms/api";
import { inject } from "@ms/container";
import { plugin, interfaces, cmd } from "@ms/plugin";
import http from '@ms/common/dist/http'
import * as fs from '@ms/common/dist/fs'
@plugin({ name: 'MiaoPluginManager', prefix: 'MPM', version: '1.0.0', author: 'MiaoWoo', source: __filename })
export class MiaoPluginManager extends interfaces.Plugin {
@inject(server.Server)
private server: server.Server;
@inject(task.TaskManager)
private taskManager: task.TaskManager;
private serverPluginsFolder: string;
private resourceAPIs = new Map<string, ResourceAPI>()
enable() {
this.resourceAPIs.set("spigot", new SpigotResourceAPI())
this.resourceAPIs.set("bukkit", new BukkitResourceAPI())
}
@cmd()
mpman(sender: any, command: string, args: string[]) {
}
@cmd()
bktman(sender: any, command: string, args: string[]) {
switch (args[0]) {
case "s":
case "search":
if (args[1]) {
let result = http.get('https://servermods.forgesvc.net/servermods/projects?search=' + args[1])
this.main(sender, "bukkit", args[0], args.slice(1))
}
@cmd()
sptman(sender: any, command: string, args: string[]) {
this.main(sender, "spigot", args[0], args.slice(1))
}
main(sender: any, target: string, command: string, args: string[]) {
let api = this.resourceAPIs.get(target);
this.taskManager.create(() => {
switch (command) {
case "s":
case "search":
this.logger.sender(sender, `§6正在从 §a${api.name()} §6搜索插件 §b${args[0]} §6请稍候...`)
let result = api.search(args[0])
for (let item of result) {
this.logger.sender(sender, "ID:", item.id, "名称:", item.name, JSON.stringify(item))
this.logger.sender(sender, "ID:", item.id, "名称:", item.name)
}
}
break;
default:
}
break;
case "d":
case "download":
http.download(api.download(Number(args[0])), fs.concat(this.server.getPluginsFolder(), args[1] + '.jar'))
break;
default:
}
}).async().submit();
}
}
class Resource {
id: number;
name: string;
}
interface ResourceAPI {
name(): string;
search(name: string): Resource[];
download(id: number): string;
}
class BukkitResourceAPI implements ResourceAPI {
private host = "https://servermods.forgesvc.net/servermods";
name() {
return "BukkitDev"
}
search(name: string) {
return http.get(`${this.host}/projects?search=${name}`);
}
download(id: number) {
let list = JSON.parse(http.get(`${this.host}/files?projectIds=${id}`));
let lastest = list[list.lenght - 1];
return lastest.downloadUrl;
}
}
class SpigotResourceAPI implements ResourceAPI {
private host = "https://api.spiget.org/v2";
name() {
return "SpigotMC"
}
search(name: string) {
return http.get(`${this.host}/search/resources/${name}`);
}
download(id: number) {
return `${this.host}/resources/${id}/download`
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@ms/sponge",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript api package",
"keywords": [
"miaoscript",
@@ -24,12 +24,11 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/api": "^0.2.1",
"@ms/common": "^0.2.1",
"@ms/container": "^0.2.1",
"@ms/types": "^0.2.1"
"@ms/api": "^0.4.0",
"@ms/common": "^0.4.0",
"@ms/container": "^0.4.0"
}
}

View File

@@ -0,0 +1,38 @@
import { channel, plugin } from '@ms/api'
import { inject, provideSingleton } from '@ms/container'
const Sponge = org.spongepowered.api.Sponge
const RawDataListener = Java.type("org.spongepowered.api.network.RawDataListener")
const ChannelRegistrar = Sponge.getChannelRegistrar()
const Consumer = Java.type("java.util.function.Consumer");
@provideSingleton(channel.Channel)
export class SpongeChannel extends channel.Channel {
@inject(plugin.PluginInstance)
private pluginInstance: any;
private channelMap = new Map<string, any>();
send(player: any, channel: string, data: any) {
if (!this.channelMap.has(channel)) { return }
this.channelMap.get(channel).sendTo(player, new Consumer({
accept: (channelBuf: any) => channelBuf.writeBytes(data)
}))
}
register(channel: string, listener: channel.ChannelListener) {
if (!this.channelMap.has(channel)) {
this.channelMap.set(channel, ChannelRegistrar.getOrCreateRaw(this.pluginInstance, channel))
}
let innerListener = new RawDataListener({
handlePayload: (/* ChannelBuf */ data: any, /**RemoteConnection */ connection: any, /**Platform.Type */ side: any) => {
listener(data.readBytes(data.available()), { data, connection, side })
}
})
this.channelMap.get(channel).addListener(innerListener);
return innerListener;
}
unregister(channel: string, listener: any) {
if (!this.channelMap.has(channel)) { return }
this.channelMap.get(channel).removeListener(listener);
}
}

View File

@@ -1,15 +1,43 @@
import { command, plugin } from "@ms/api";
import { inject, injectable } from "@ms/container";
import { inject, provideSingleton } from "@ms/container";
let Sponge = Java.type('org.spongepowered.api.Sponge');
let Text = Java.type('org.spongepowered.api.text.Text');
var CommandCallable = Java.type('org.spongepowered.api.command.CommandCallable');
var CommandResult = Java.type('org.spongepowered.api.command.CommandResult');
let Text = Java.type('org.spongepowered.api.text.Text');
var Optional = Java.type('java.util.Optional');
@provideSingleton(command.Command)
export class SpongeCommand extends command.Command {
@inject(plugin.PluginInstance)
private pluginInstance: any
private commandMapping: any[] = [];
create(plugin: any, command: string) {
let commandKey = this.getCommandKey(plugin, command);
let commandCallable = new SimpleCommandCallable(command);
this.commandMapping[commandKey] = Sponge.getCommandManager().register(this.pluginInstance, commandCallable.callable, command, commandKey).orElse(null);
return commandCallable;
}
remove(plugin: any, command: string) {
var commandKey = this.getCommandKey(plugin, command);
if (this.commandMapping[commandKey]) {
Sponge.getCommandManager().removeMapping(this.commandMapping[commandKey]);
delete this.commandMapping[commandKey];
}
}
onCommand(plugin: any, command: any, executor: Function) {
command.setExecutor(super.setExecutor(plugin, command, executor));
}
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
command.setTabCompleter(super.setTabCompleter(plugin, command, tabCompleter));
}
private getCommandKey(plugin: any, command: string) {
return plugin.description.name.toLowerCase() + ":" + command;
}
}
class SimpleCommandCallable {
public callable: any;
private name: string;
@@ -49,35 +77,4 @@ class SimpleCommandCallable {
setExecutor = (executor: Function) => this.executor = executor;
setTabCompleter = (tabCompleter: Function) => this.tabCompleter = tabCompleter;
toString = () => `Sponge SimpleCommandCallable(${this.name})`
}
@injectable()
export class SpongeCommand extends command.Command {
@inject(plugin.PluginInstance)
private pluginInstance: any
private commandMapping: any[] = [];
create(plugin: any, command: string) {
let commandKey = this.getCommandKey(plugin, command);
let commandCallable = new SimpleCommandCallable(command);
this.commandMapping[commandKey] = Sponge.getCommandManager().register(this.pluginInstance, commandCallable.callable, command, commandKey).orElse(null);
return commandCallable;
}
remove(plugin: any, command: string) {
var commandKey = this.getCommandKey(plugin, command);
if (this.commandMapping[commandKey]) {
Sponge.getCommandManager().removeMapping(this.commandMapping[commandKey]);
delete this.commandMapping[commandKey];
}
}
onCommand(plugin: any, command: any, executor: Function) {
command.setExecutor(super.setExecutor(plugin, command, executor));
}
onTabComplete(plugin: any, command: any, tabCompleter: Function) {
command.setTabCompleter(super.setTabCompleter(plugin, command, tabCompleter));
}
private getCommandKey(plugin: any, command: string) {
return plugin.description.name.toLowerCase() + ":" + command;
}
}
}

View File

@@ -1,5 +1,5 @@
import { event, plugin } from '@ms/api'
import { injectable, inject } from '@ms/container';
import { inject, provideSingleton } from '@ms/container';
let Modifier = Java.type("java.lang.reflect.Modifier");
let Order = Java.type("org.spongepowered.api.event.Order");
@@ -19,7 +19,7 @@ let priorityMap = {
/**
* Sponge Event Impl
*/
@injectable()
@provideSingleton(event.Event)
export class SpongeEvent extends event.Event {
@inject(plugin.PluginInstance)
private pluginInstance: any;

View File

@@ -1,18 +1,15 @@
/// <reference types="@ms/types/dist/typings/sponge" />
import { server, command, event, task } from '@ms/api'
import { server } from '@ms/api'
import { Container } from '@ms/container'
import { SpongeConsole } from './console';
import { SpongeEvent } from './event';
import { SpongeServer } from './server';
import { SpongeCommand } from './command';
import { SpongeTaskManager } from './task';
import './event';
import './server';
import './command';
import './channel';
import './task';
export default function SpongeImpl(container: Container) {
container.bind(server.Console).toConstantValue(SpongeConsole);
container.bind(event.Event).to(SpongeEvent).inSingletonScope();
container.bind(server.Server).to(SpongeServer).inSingletonScope();
container.bind(command.Command).to(SpongeCommand).inSingletonScope();
container.bind(task.TaskManager).to(SpongeTaskManager).inSingletonScope();
}

View File

@@ -1,11 +1,21 @@
import { server } from '@ms/api'
import { injectable } from '@ms/container';
import { provideSingleton } from '@ms/container';
let Sponge = org.spongepowered.api.Sponge;
let TextSerializers = org.spongepowered.api.text.serializer.TextSerializers;
import * as fs from '@ms/common/dist/fs'
@injectable()
const Sponge = org.spongepowered.api.Sponge;
const TextSerializers = org.spongepowered.api.text.serializer.TextSerializers;
const URL = Java.type("java.net.URL");
const File = Java.type("java.io.File");
@provideSingleton(server.Server)
export class SpongeServer implements server.Server {
private pluginsFolder: string;
constructor() {
this.pluginsFolder = new File(base.getInstance().getClass().getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile().getCanonicalPath()
}
getPlayer(name: string) {
return Sponge.getServer().getPlayer(name).orElse(null)
}
@@ -30,6 +40,12 @@ export class SpongeServer implements server.Server {
dispatchConsoleCommand(command: string): boolean {
return Sponge.getCommandManager().process(Sponge.getServer().getConsole(), command).getQueryResult()
}
getPluginsFolder(): string {
return this.pluginsFolder;
}
getNativePluginManager() {
return Sponge.getPluginManager() as any;
}
sendJson(sender: string | any, json: string): void {
if (typeof sender === "string") {
sender = this.getPlayer(sender)

View File

@@ -1,5 +1,5 @@
import { task, plugin } from '@ms/api'
import { injectable, inject } from '@ms/container';
import { inject, provideSingleton } from '@ms/container';
const Sponge = Java.type("org.spongepowered.api.Sponge");
const Task = Java.type("org.spongepowered.api.scheduler.Task");
@@ -7,7 +7,7 @@ const Consumer = Java.type('java.util.function.Consumer');
const Callable = Java.type('java.util.concurrent.Callable');
const TimeUnit = Java.type('java.util.concurrent.TimeUnit');
@injectable()
@provideSingleton(task.TaskManager)
export class SpongeTaskManager implements task.TaskManager {
@inject(plugin.PluginInstance)
private pluginInstance: any;

4
packages/types/dist/index.d.ts vendored Normal file
View File

@@ -0,0 +1,4 @@
/// <reference path="./typings/bukkit/index.d.ts" />
/// <reference path="./typings/bungee/index.d.ts" />
/// <reference path="./typings/nukkit/index.d.ts" />
/// <reference path="./typings/sponge/index.d.ts" />

View File

@@ -1,7 +1,6 @@
{
"private": true,
"name": "@ms/types",
"version": "0.2.1",
"version": "0.4.0",
"description": "MiaoScript types package",
"keywords": [
"miaoscript",
@@ -13,6 +12,7 @@
"homepage": "https://github.com/circlecloud/ms.git",
"license": "ISC",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"publishConfig": {
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
}

View File

@@ -1,7 +1,7 @@
{
"name": "@ms/websocket",
"version": "0.2.1",
"description": "MiaoScript api package",
"version": "0.4.0",
"description": "MiaoScript websocket package",
"keywords": [
"miaoscript",
"minecraft",
@@ -24,11 +24,9 @@
"devDependencies": {
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"typescript": "^3.8.2"
"typescript": "^3.8.3"
},
"dependencies": {
"@ms/api": "^0.2.1",
"@ms/common": "^0.2.1"
},
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
"@ms/nashorn": "^0.4.0"
}
}

View File

@@ -1 +1,3 @@
import '@ms/nashorn'
/// <reference types="@ms/nashorn" />
export * from './socket-io'

View File

@@ -1,21 +1,20 @@
/// <reference types="@ms/ployfill" />
const TypeParameterMatcher = Java.type('io.netty.util.internal.TypeParameterMatcher')
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
const FullHttpRequestMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.FullHttpRequest'))
export default abstract class HttpRequestHandlerAdapter {
export abstract class HttpRequestHandlerAdapter {
private _Handler;
constructor() {
this._Handler == Java.extend(SimpleChannelInboundHandler, {
let HttpRequestHandlerAdapterImpl = Java.extend(SimpleChannelInboundHandler, {
acceptInboundMessage: (msg: any) => {
return FullHttpRequestMatcher.match(msg)
},
channelRead0: this.channelRead0
channelRead0: this.channelRead0.bind(this)
})
this._Handler = new HttpRequestHandlerAdapterImpl();
}
abstract channelRead0(ctx: any, msg: any);
abstract channelRead0(ctx: any, request: any);
getHandler() {
return this._Handler;
}
}
}

View File

@@ -0,0 +1,3 @@
export * from './text_websocket_frame'
export * from './websocket'
export * from './httprequest'

View File

@@ -1,22 +1,23 @@
/// <reference types="@ms/ployfill" />
const TypeParameterMatcher = Java.type('io.netty.util.internal.TypeParameterMatcher')
const TextWebSocketFrameMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.websocketx.TextWebSocketFrame'))
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
export default abstract class TextWebSocketFrameHandlerAdapter {
export abstract class TextWebSocketFrameHandlerAdapter {
private _Handler;
constructor() {
this._Handler == Java.extend(SimpleChannelInboundHandler, {
userEventTriggered: this.userEventTriggered,
let TextWebSocketFrameHandlerAdapterImpl = Java.extend(SimpleChannelInboundHandler, {
userEventTriggered: this.userEventTriggered.bind(this),
acceptInboundMessage: (msg: any) => {
return TextWebSocketFrameMatcher.match(msg)
},
channelRead0: this.channelRead0
channelRead0: this.channelRead0.bind(this),
exceptionCaught: this.exceptionCaught.bind(this)
})
this._Handler = new TextWebSocketFrameHandlerAdapterImpl();
}
abstract userEventTriggered(ctx: any, evt: any);
abstract channelRead0(ctx: any, msg: any);
abstract exceptionCaught(ctx: any, cause: Error);
getHandler() {
return this._Handler;
}

View File

@@ -1,17 +1,14 @@
import '@ms/api'
const MiaoWebSocket = 'miaowebsocket'
const CharsetUtil = Java.type('io.netty.util.CharsetUtil')
const ChannelInboundHandlerAdapter = Java.type('io.netty.channel.ChannelInboundHandlerAdapter')
export default abstract class WebSocketHandlerAdapter {
export abstract class WebSocketHandlerAdapter {
private _Handler;
constructor() {
this._Handler = Java.extend(ChannelInboundHandlerAdapter, {
channelRead: this.channelRead
let ChannelInboundHandlerAdapterImpl = Java.extend(ChannelInboundHandlerAdapter, {
channelRead: this.channelRead.bind(this)
})
this._Handler = new ChannelInboundHandlerAdapterImpl()
}
abstract channelRead(ctx: any, msg: any);
abstract channelRead(ctx: any, channel: any);
getHandler() {
return this._Handler;
}

View File

@@ -0,0 +1,40 @@
import { EventEmitter } from 'events'
import { SocketIO } from 'socket-io/interfaces';
import { Keys, AttributeKeys } from './constants';
const TextWebSocketFrame = Java.type('io.netty.handler.codec.http.websocketx.TextWebSocketFrame')
export class NettyClient extends EventEmitter implements SocketIO.EngineSocket {
private _id: string;
private channel: any
server: any;
readyState: string;
remoteAddress: string;
upgraded: boolean;
request: any;
transport: any;
constructor(server: any, channel: any) {
super();
this.server = server;
this.readyState = 'open';
this.remoteAddress = channel.remoteAddress() + ''
this.upgraded = true;
this.request = channel.attr(AttributeKeys.Request).get();
this.transport = null;
this.channel = channel;
this._id = channel.id();
}
get id() {
return this._id;
}
send(text: string) {
this.channel.writeAndFlush(new TextWebSocketFrame(text))
}
close() {
this.channel.close();
}
}

View File

@@ -0,0 +1,20 @@
export enum ServerEvent {
detect = 'detect',
connect = 'connect',
connection = 'connection',
message = 'message',
error = 'error',
disconnect = 'disconnect'
}
const AttributeKey = Java.type('io.netty.util.AttributeKey');
export enum Keys {
Detect = "miao_detect",
Handler = "miaowebsocket",
Default = "DefaultChannelPipeline"
}
export enum AttributeKeys {
Request = AttributeKey.valueOf('request')
}

View File

@@ -0,0 +1,61 @@
import { HttpRequestHandlerAdapter } from '../netty'
import { AttributeKeys } from './constants'
import { ServerOptions } from 'socket-io'
const DefaultHttpResponse = Java.type('io.netty.handler.codec.http.DefaultHttpResponse')
const DefaultFullHttpResponse = Java.type('io.netty.handler.codec.http.DefaultFullHttpResponse')
const HttpHeaders = Java.type('io.netty.handler.codec.http.HttpHeaders')
const HttpVersion = Java.type('io.netty.handler.codec.http.HttpVersion')
const HttpResponseStatus = Java.type('io.netty.handler.codec.http.HttpResponseStatus')
const LastHttpContent = Java.type('io.netty.handler.codec.http.LastHttpContent')
const File = Java.type('java.io.File')
const Runnable = Java.type('java.lang.Runnable')
const RandomAccessFile = Java.type('java.io.RandomAccessFile')
const DefaultFileRegion = Java.type('io.netty.channel.DefaultFileRegion')
const ChannelFutureListener = Java.type('io.netty.channel.ChannelFutureListener')
export class HttpRequestHandler extends HttpRequestHandlerAdapter {
private ws: string;
private root: string;
constructor(options: ServerOptions) {
super()
this.root = options.root;
this.ws = options.path;
}
channelRead0(ctx: any, request: any) {
if (request.getUri().startsWith(this.ws)) {
ctx.channel().attr(AttributeKeys.Request).set(request);
ctx.fireChannelRead(request.retain())
} else {
ctx.executor().execute(new Runnable({
run: () => {
if (HttpHeaders.is100ContinueExpected(request)) {
ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE))
}
let filename = request.getUri().split('?')[0].substr(1)
let file = new File(this.root, filename || 'index.html')
if (!file.exists() || !file.isFile()) {
ctx.write(new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND))
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT).addListener(ChannelFutureListener.CLOSE)
return
}
let response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK)
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html charset=UTF-8")
let raf = new RandomAccessFile(file, 'r')
let keepAlive = HttpHeaders.isKeepAlive(request)
if (keepAlive) {
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length())
response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE)
}
ctx.write(response)
ctx.write(new DefaultFileRegion(raf.getChannel(), 0, raf.length()))
let future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT)
if (!keepAlive) {
future.addListener(ChannelFutureListener.CLOSE)
}
}
}))
}
}
}

View File

@@ -0,0 +1,48 @@
import { EventEmitter } from 'events'
import { ServerEvent, Keys } from './constants'
import { WebSocketDetect } from './websocket_detect'
import { WebSocketHandler } from './websocket_handler'
import { NettyClient } from './client'
import { ServerOptions, Server } from '../socket-io'
class NettyWebSocketServer extends EventEmitter {
private pipeline: any;
private allClients: { [key: string]: NettyClient };
constructor(pipeline: any, options: ServerOptions) {
super()
this.allClients = {};
this.pipeline = pipeline;
let connectEvent = options.event;
try { this.pipeline.remove(Keys.Detect) } catch (error) { }
this.pipeline.addFirst(Keys.Detect, new WebSocketDetect(connectEvent).getHandler())
connectEvent.on(ServerEvent.detect, (ctx, channel) => {
channel.pipeline().addFirst(Keys.Handler, new WebSocketHandler(options).getHandler())
ctx.fireChannelRead(channel)
})
connectEvent.on(ServerEvent.connect, (ctx) => {
let nettyClient = new NettyClient(this, ctx.channel());
this.allClients[nettyClient.id] = nettyClient;
this.emit(ServerEvent.connect, nettyClient);
})
connectEvent.on(ServerEvent.message, (ctx, msg) => {
this.emit(ServerEvent.message, this.allClients[ctx.channel().id()], msg.text())
})
connectEvent.on(ServerEvent.error, (ctx, cause) => {
this.emit(ServerEvent.error, this.allClients[ctx.channel().id()], cause)
})
}
close() {
if (this.pipeline.names().contains(Keys.Detect)) {
this.pipeline.remove(Keys.Detect)
}
Object.values(this.allClients).forEach(client => client.close())
}
}
export {
NettyWebSocketServer,
ServerEvent,
NettyClient
};

View File

@@ -0,0 +1,23 @@
import { TextWebSocketFrameHandlerAdapter } from '../netty'
import { EventEmitter } from 'events'
import { ServerEvent } from './constants'
import { ServerOptions } from '../socket-io';
export class TextWebSocketFrameHandler extends TextWebSocketFrameHandlerAdapter {
private event: EventEmitter;
constructor(options: ServerOptions) {
super()
this.event = options.event;
}
userEventTriggered(ctx: any, evt: any) {
if (evt == 'HANDSHAKE_COMPLETE') {
this.event.emit(ServerEvent.connect, ctx)
}
}
channelRead0(ctx: any, msg: any) {
this.event.emit(ServerEvent.message, ctx, msg)
}
exceptionCaught(ctx: any, cause: Error) {
this.event.emit(ServerEvent.error, ctx, cause)
}
}

View File

@@ -0,0 +1,14 @@
import { EventEmitter } from 'events'
import { WebSocketHandlerAdapter } from "../netty"
import { ServerEvent } from './constants'
export class WebSocketDetect extends WebSocketHandlerAdapter {
private event: EventEmitter;
constructor(event: EventEmitter) {
super()
this.event = event;
}
channelRead(ctx: any, channel: any) {
this.event.emit(ServerEvent.detect, ctx, channel);
}
}

View File

@@ -0,0 +1,43 @@
import { EventEmitter } from 'events'
import { Keys } from './constants'
import { WebSocketHandlerAdapter } from "../netty"
import { HttpRequestHandler } from './httprequest'
import { TextWebSocketFrameHandler } from './text_websocket_frame'
import { ServerOptions } from '../socket-io'
const CharsetUtil = Java.type('io.netty.util.CharsetUtil')
const HttpServerCodec = Java.type('io.netty.handler.codec.http.HttpServerCodec')
const ChunkedWriteHandler = Java.type('io.netty.handler.stream.ChunkedWriteHandler')
const HttpObjectAggregator = Java.type('io.netty.handler.codec.http.HttpObjectAggregator')
const WebSocketServerProtocolHandler = Java.type('io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler')
export class WebSocketHandler extends WebSocketHandlerAdapter {
private options: ServerOptions;
constructor(options: ServerOptions) {
super()
this.options = options;
}
channelRead(ctx: any, msg: any) {
msg.markReaderIndex()
let message: string = msg.toString(CharsetUtil.UTF_8)
let channel = ctx.channel()
let pipeline = channel.pipeline()
if (message.indexOf('HTTP/1.1') > 0) {
pipeline.names().forEach(f => {
if (f == Keys.Handler || f.indexOf(Keys.Default) > -1) { return }
pipeline.remove(f)
})
pipeline.addLast('http', new HttpServerCodec())
pipeline.addLast('chunk', new ChunkedWriteHandler())
pipeline.addLast('httpobj', new HttpObjectAggregator(64 * 1024))
pipeline.addLast('http_request', new HttpRequestHandler(this.options).getHandler())
pipeline.addLast('websocket', new WebSocketServerProtocolHandler(this.options.path, true))
pipeline.addLast('websocket_handler', new TextWebSocketFrameHandler(this.options).getHandler())
}
pipeline.remove(Keys.Handler)
msg.resetReaderIndex()
ctx.fireChannelRead(msg)
}
}

View File

@@ -0,0 +1,127 @@
import { EventEmitter } from 'events'
import { SocketIO } from './interfaces';
import { Namespace } from './namespace';
import { Parser } from './parser';
import { Socket } from './socket';
export class Adapter extends EventEmitter implements SocketIO.Adapter {
nsp: Namespace;
rooms: Rooms;
sids: { [id: string]: { [room: string]: boolean; }; };
parser: Parser
constructor(nsp: Namespace) {
super()
this.nsp = nsp;
this.rooms = new Rooms();
this.sids = {};
this.parser = nsp.server.parser;
}
add(id: string, room: string, callback?: (err?: any) => void): void {
return this.addAll(id, [room], callback);
}
/**
* Adds a socket to a list of room.
*
* @param {String} socket id
* @param {String} rooms
* @param {Function} callback
* @api public
*/
addAll(id: string, rooms: string | any[], fn: { (err?: any): void; bind?: any; }) {
for (var i = 0; i < rooms.length; i++) {
var room = rooms[i];
this.sids[id] = this.sids[id] || {};
this.sids[id][room] = true;
this.rooms[room] = this.rooms[room] || new Room();
this.rooms[room].add(id);
}
fn && fn.bind(null, null)
};
del(id: string, room: string, callback?: (err?: any) => void): void {
if (this.sids[id]) delete this.sids[id][room];
if (this.rooms.hasOwnProperty(room)) {
this.rooms[room].del(id);
if (this.rooms[room].length === 0) delete this.rooms[room];
}
callback && callback.bind(null, null)
}
delAll(id: string): void {
var rooms = this.sids[id];
if (rooms) {
for (var room in rooms) {
if (this.rooms.hasOwnProperty(room)) {
this.rooms[room].del(id);
if (this.rooms[room].length === 0) delete this.rooms[room];
}
}
}
delete this.sids[id];
}
broadcast(packet: any, opts: { rooms?: string[]; except?: string[]; flags?: { [flag: string]: boolean; }; }): void {
var rooms = opts.rooms || [];
var except = opts.except || [];
var flags = opts.flags || {};
var packetOpts = {
preEncoded: true,
volatile: flags.volatile,
compress: flags.compress
};
var ids = {};
var self = this;
var socket: Socket;
packet.nsp = this.nsp.name;
// let encodedPackets = this.parser.encode(packet)
if (rooms.length) {
for (var i = 0; i < rooms.length; i++) {
var room = self.rooms[rooms[i]];
if (!room) continue;
var sockets = room.sockets;
for (var id in sockets) {
if (sockets.hasOwnProperty(id)) {
if (ids[id] || ~except.indexOf(id)) continue;
socket = self.nsp.connected[id];
if (socket) {
socket.packet(packet, packetOpts);
ids[id] = true;
}
}
}
}
} else {
for (var id in self.sids) {
if (self.sids.hasOwnProperty(id)) {
if (~except.indexOf(id)) continue;
socket = self.nsp.connected[id];
if (socket) socket.packet(packet, packetOpts);
}
}
}
}
}
class Rooms implements SocketIO.Rooms {
[room: string]: Room;
}
class Room implements SocketIO.Room {
sockets: { [id: string]: boolean; };
length: number;
constructor() {
this.sockets = {};
this.length = 0;
}
add(id) {
if (!this.sockets.hasOwnProperty(id)) {
this.sockets[id] = true;
this.length++;
}
}
del(id) {
if (this.sockets.hasOwnProperty(id)) {
delete this.sockets[id];
this.length--;
}
}
}

View File

@@ -0,0 +1,103 @@
import { EventEmitter } from 'events'
import { Parser } from './parser'
import { Packet } from './packet';
import { NettyClient } from '../server';
import { SocketIO } from './interfaces'
import { Server, Socket } from './index';
import { PacketTypes, SubPacketTypes } from './types';
const parser = new Parser();
export class Client extends EventEmitter implements SocketIO.Client {
id: string;
server: Server;
conn: NettyClient;
request: any;
sockets: { [id: string]: Socket; };
nsps: { [nsp: string]: SocketIO.Socket; };
connectBuffer: any;
constructor(server: Server, nettyClient: NettyClient) {
super();
this.server = server;
this.conn = nettyClient;
this.id = this.conn.id + '';
this.request = nettyClient.request;
this.sockets = {};
this.nsps = {};
}
connect(name, query) {
if (this.server.nsps[name]) {
// console.debug(`connecting to namespace ${name}`);
return this.doConnect(name, query);
}
this.server.checkNamespace(name, query, (dynamicNsp) => {
if (dynamicNsp) {
// console.debug('dynamic namespace %s was created', dynamicNsp.name);
this.doConnect(name, query);
} else {
// console.debug('creation of namespace %s was denied', name);
this.packet({
type: PacketTypes.MESSAGE,
sub_type: SubPacketTypes.ERROR,
nsp: name,
data: 'Invalid namespace'
});
}
})
}
doConnect(name, query) {
var nsp = this.server.of(name);
if ('/' != name && !this.nsps['/']) {
this.connectBuffer.push(name);
return;
}
var socket = nsp.add(this, query, () => {
this.sockets[socket.id] = socket;
this.nsps[nsp.name] = socket;
if ('/' == nsp.name && this.connectBuffer.length > 0) {
this.connectBuffer.forEach(this.connect, this);
this.connectBuffer = [];
}
});
}
packet(packet: Packet, opts?: any) {
this.conn.send(parser.encode(packet))
}
onclose(reason?: string) {
// debug('client close with reason %s', reason);
// ignore a potential subsequent `close` event
this.destroy();
// `nsps` and `sockets` are cleaned up seamlessly
for (var id in this.sockets) {
if (this.sockets.hasOwnProperty(id)) {
this.sockets[id].onclose(reason);
}
}
this.sockets = {};
// this.decoder.destroy(); // clean up decoder
}
disconnect() {
// if ('open' == this.conn.readyState) {
// debug('forcing transport close');
this.conn.close();
this.onclose('forced server close');
// }
}
remove(socket: Socket) {
if (this.sockets.hasOwnProperty(socket.id)) {
var nsp = this.sockets[socket.id].nsp.name;
delete this.sockets[socket.id];
delete this.nsps[nsp];
} else {
// debug('ignoring remove for %s', socket.id);
}
}
destroy() {
// this.conn.removeListener('data', this.ondata);
// this.conn.removeListener('error', this.onerror);
// this.conn.removeListener('close', this.onclose);
// this.decoder.removeListener('decoded', this.ondecoded);
};
}

View File

@@ -0,0 +1,210 @@
import { EventEmitter } from 'events'
import { NettyWebSocketServer, NettyClient } from '../server'
import { ServerEvent } from '../server/constants';
import { Namespace } from './namespace';
import { Client } from './client';
import { SocketIO } from './interfaces'
import { Parser } from './parser'
import { PacketTypes, SubPacketTypes } from './types';
import { Packet } from './packet';
import { Socket } from './socket';
import { Adapter } from './adapter';
interface ServerOptions extends SocketIO.ServerOptions {
event?: EventEmitter;
root?: string;
}
const defaultOptions: ServerOptions = {
event: new EventEmitter(),
path: '/socket.io',
root: root + '/wwwroot'
}
class Server implements SocketIO.Server {
private nettyServer: NettyWebSocketServer;
private allClients: { [key: string]: Client };
engine: { ws: any; };
nsps: { [namespace: string]: Namespace; };
sockets: Namespace;
json: SocketIO.Server;
volatile: SocketIO.Server;
local: SocketIO.Server;
parser = new Parser();
_adapter: Adapter;
options: ServerOptions;
constructor(pipeline: any, options: ServerOptions) {
if (!pipeline) { throw new Error('Netty Pipeline can\'t be undefiend!') }
this.allClients = {};
this.nsps = {};
this.sockets = new Namespace('/', this);
this.nsps['/'] = this.sockets;
this.initNettyServer(pipeline, Object.assign(defaultOptions, options));
}
checkRequest(req: any, fn: (err: any, success: boolean) => void): void {
throw new Error("Method not implemented.");
}
serveClient(): boolean;
serveClient(v: boolean): SocketIO.Server;
serveClient(v?: any): boolean | SocketIO.Server {
throw new Error("Method not implemented.");
}
path(): string;
path(v: string): SocketIO.Server;
path(v?: any): string | SocketIO.Server {
if (!arguments.length) return this.options.path;
this.options.path = v.replace(/\/$/, '');
return this;
}
adapter(): Adapter;
adapter(v: any): SocketIO.Server;
adapter(v?: any): Adapter | SocketIO.Server {
if (!arguments.length) return this._adapter;
this._adapter = v;
for (var i in this.nsps) {
if (this.nsps.hasOwnProperty(i)) {
this.nsps[i].initAdapter();
}
}
return this;
}
origins(): string | string[];
origins(v: string | string[]): SocketIO.Server;
origins(fn: (origin: string, callback: (error: string, success: boolean) => void) => void): SocketIO.Server;
origins(fn?: any): string | string[] | SocketIO.Server {
throw new Error("Method not implemented.");
}
attach(srv: any, opts?: SocketIO.ServerOptions): SocketIO.Server;
attach(port: number, opts?: SocketIO.ServerOptions): SocketIO.Server;
attach(port: any, opts?: any): SocketIO.Server {
throw new Error("Method not implemented.");
}
listen(srv: any, opts?: SocketIO.ServerOptions): SocketIO.Server;
listen(port: number, opts?: SocketIO.ServerOptions): SocketIO.Server;
listen(port: any, opts?: any): SocketIO.Server {
throw new Error("Method not implemented.");
}
bind(srv: any): SocketIO.Server {
throw new Error("Method not implemented.");
}
onconnection(socket: Client): SocketIO.Server {
this.allClients[socket.id] = socket;
socket.packet({
type: PacketTypes.OPEN,
data: {
sid: socket.id,
upgrades: [],
pingInterval: 25000,
pingTimeout: 5000
}
})
this.sockets.add(socket);
return this;
}
of(nsp: string): Namespace {
if (!this.nsps[nsp]) {
this.nsps[nsp] = new Namespace(nsp, this);
}
return this.nsps[nsp];
}
close(fn?: () => void): void {
for (let socket in this.sockets.sockets) {
this.sockets.sockets[socket].onclose()
}
this.nettyServer.close();
}
on(event: "connection", listener: (socket: SocketIO.Socket) => void): SocketIO.Namespace;
on(event: "connect", listener: (socket: SocketIO.Socket) => void): SocketIO.Namespace;
on(event: string, listener: Function): SocketIO.Namespace;
on(event: any, listener: any): SocketIO.Namespace {
return this.sockets.on(event, listener);
}
to(room: string): SocketIO.Namespace {
return this.sockets.to(room);
}
in(room: string): SocketIO.Namespace {
return this.sockets.in(room);
}
use(fn: (socket: SocketIO.Socket, fn: (err?: any) => void) => void): SocketIO.Namespace {
return this.sockets.use(fn);
}
emit(event: string, ...args: any[]): SocketIO.Namespace {
// @ts-ignore
return this.sockets.emit(event, ...args);
}
send(...args: any[]): SocketIO.Namespace {
return this.sockets.send(...args);
}
write(...args: any[]): SocketIO.Namespace {
return this.sockets.write(...args);
}
clients(...args: any[]): SocketIO.Namespace {
return this.sockets.clients(args[0]);
}
compress(...args: any[]): SocketIO.Namespace {
return this.sockets.compress(args[0])
}
// ===============================
checkNamespace(name, query, fn) {
fn(false);
};
private initNettyServer(pipeline, options) {
this.nettyServer = new NettyWebSocketServer(pipeline, options);
this.nettyServer.on(ServerEvent.connect, (nettyClient: NettyClient) => {
let client = new Client(this, nettyClient);
this.onconnection(client);
})
this.nettyServer.on(ServerEvent.message, (nettyClient: NettyClient, text) => {
this.processPacket(this.parser.decode(text), this.allClients[nettyClient.id]);
})
this.nettyServer.on(ServerEvent.error, (nettyClient: NettyClient, cause) => {
console.error(`Client ${nettyClient.id} cause error: ` + cause)
console.ex(cause)
})
}
private processPacket(packet: Packet, client: Client) {
switch (packet.type) {
case PacketTypes.PING:
client.packet({
type: PacketTypes.PONG,
data: packet.data
})
break;
case PacketTypes.UPGRADE:
break;
case PacketTypes.MESSAGE:
this.processSubPacket(packet, client);
break;
case PacketTypes.CLOSE:
client.onclose()
break;
}
}
private processSubPacket(packet: Packet, client: Client) {
let namespace = this.nsps[packet.nsp]
if (!namespace) {
client.packet({
type: PacketTypes.MESSAGE,
sub_type: SubPacketTypes.ERROR,
data: 'not support dynamic namespace: ' + packet.nsp
});
client.disconnect();
return;
}
namespace.process(packet, client);
}
}
export {
Server,
Socket,
Client,
ServerOptions
}

View File

@@ -0,0 +1,824 @@
export declare namespace SocketIO {
interface Server {
engine: { ws: any };
/**
* A dictionary of all the namespaces currently on this Server
*/
nsps: { [namespace: string]: Namespace };
/**
* The default '/' Namespace
*/
sockets: Namespace;
/**
* Sets the 'json' flag when emitting an event
*/
json: Server;
/**
* Sets a modifier for a subsequent event emission that the event data may be lost if the clients are not ready to receive messages
*/
volatile: Server;
/**
* Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node
*/
local: Server;
/**
* Server request verification function, that checks for allowed origins
* @param req The http.IncomingMessage request
* @param fn The callback to be called. It should take one parameter, err,
* which will be null if there was no problem, and one parameter, success,
* of type boolean
*/
checkRequest(req: any, fn: (err: any, success: boolean) => void): void;
/**
* Gets whether we're serving the client.js file or not
* @default true
*/
serveClient(): boolean;
/**
* Sets whether we're serving the client.js file or not
* @param v True if we want to serve the file, false otherwise
* @default true
* @return This Server
*/
serveClient(v: boolean): Server;
/**
* Gets the client serving path
* @default '/socket.io'
*/
path(): string;
/**
* Sets the client serving path
* @param v The path to serve the client file on
* @default '/socket.io'
* @return This Server
*/
path(v: string): Server;
/**
* Gets the adapter that we're going to use for handling rooms
* @default typeof Adapter
*/
adapter(): any;
/**
* Sets the adapter (class) that we're going to use for handling rooms
* @param v The class for the adapter to create
* @default typeof Adapter
* @return This Server
*/
adapter(v: any): Server;
/**
* Gets the allowed origins for requests
* @default "*:*"
*/
origins(): string | string[];
/**
* Sets the allowed origins for requests
* @param v The allowed origins, in host:port form
* @default "*:*"
* return This Server
*/
origins(v: string | string[]): Server;
/**
* Provides a function taking two arguments origin:String
* and callback(error, success), where success is a boolean
* value indicating whether origin is allowed or not. If
* success is set to false, error must be provided as a string
* value that will be appended to the server response, e.g. “Origin not allowed”.
* @param fn The function that will be called to check the origin
* return This Server
*/
origins(fn: (origin: string, callback: (error: string | null, success: boolean) => void) => void): Server;
/**
* Attaches socket.io to a server
* @param srv The http.Server that we want to attach to
* @param opts An optional parameters object
* @return This Server
*/
attach(srv: any, opts?: ServerOptions): Server;
/**
* Attaches socket.io to a port
* @param port The port that we want to attach to
* @param opts An optional parameters object
* @return This Server
*/
attach(port: number, opts?: ServerOptions): Server;
/**
* @see attach( srv, opts )
*/
listen(srv: any, opts?: ServerOptions): Server;
/**
* @see attach( port, opts )
*/
listen(port: number, opts?: ServerOptions): Server;
/**
* Binds socket.io to an engine.io instance
* @param src The Engine.io (or compatible) server to bind to
* @return This Server
*/
bind(srv: any): Server;
/**
* Called with each incoming connection
* @param socket The Engine.io Socket
* @return This Server
*/
onconnection(socket: any): Server;
/**
* Looks up/creates a Namespace
* @param nsp The name of the NameSpace to look up/create. Should start
* with a '/'
* @return The Namespace
*/
of(nsp: string | RegExp | Function): Namespace;
/**
* Closes the server connection
*/
close(fn?: () => void): void;
/**
* The event fired when we get a new connection
* @param event The event being fired: 'connection'
* @param listener A listener that should take one parameter of type Socket
* @return The default '/' Namespace
*/
on(event: 'connection', listener: (socket: Socket) => void): Namespace;
/**
* @see on( 'connection', listener )
*/
on(event: 'connect', listener: (socket: Socket) => void): Namespace;
/**
* Base 'on' method to add a listener for an event
* @param event The event that we want to add a listener for
* @param listener The callback to call when we get the event. The parameters
* for the callback depend on the event
* @return The default '/' Namespace
*/
on(event: string, listener: Function): Namespace;
/**
* Targets a room when emitting to the default '/' Namespace
* @param room The name of the room that we're targeting
* @return The default '/' Namespace
*/
to(room: string): Namespace;
/**
* @see to( room )
*/
in(room: string): Namespace;
/**
* Registers a middleware function, which is a function that gets executed
* for every incoming Socket, on the default '/' Namespace
* @param fn The function to call when we get a new incoming socket. It should
* take one parameter of type Socket, and one callback function to call to
* execute the next middleware function. The callback can take one optional
* parameter, err, if there was an error. Errors passed to middleware callbacks
* are sent as special 'error' packets to clients
* @return The default '/' Namespace
*/
use(fn: (socket: Socket, fn: (err?: any) => void) => void): Namespace;
/**
* Emits an event to the default Namespace
* @param event The event that we want to emit
* @param args Any number of optional arguments to pass with the event. If the
* last argument is a function, it will be called as an ack. The ack should
* take whatever data was sent with the packet
* @return The default '/' Namespace
*/
emit(event: string, ...args: any[]): Namespace;
/**
* Sends a 'message' event
* @see emit( event, ...args )
* @return The default '/' Namespace
*/
send(...args: any[]): Namespace;
/**
* @see send( ...args )
*/
write(...args: any[]): Namespace;
/**
* Gets a list of clients
* @return The default '/' Namespace
*/
clients(...args: any[]): Namespace;
/**
* Sets the compress flag
* @return The default '/' Namespace
*/
compress(...args: any[]): Namespace;
}
/**
* Options to pass to our server when creating it
*/
interface ServerOptions {
/**
* The path to server the client file to
* @default '/socket.io'
*/
path?: string;
/**
* Should we serve the client file?
* @default true
*/
serveClient?: boolean;
/**
* The adapter to use for handling rooms. NOTE: this should be a class,
* not an object
* @default typeof Adapter
*/
adapter?: Adapter;
/**
* Accepted origins
* @default '*:*'
*/
origins?: string | string[];
/**
* How many milliseconds without a pong packed to consider the connection closed (engine.io)
* @default 60000
*/
pingTimeout?: number;
/**
* How many milliseconds before sending a new ping packet (keep-alive) (engine.io)
* @default 25000
*/
pingInterval?: number;
/**
* How many bytes or characters a message can be when polling, before closing the session
* (to avoid Dos) (engine.io)
* @default 10E7
*/
maxHttpBufferSize?: number;
/**
* A function that receives a given handshake or upgrade request as its first parameter,
* and can decide whether to continue or not. The second argument is a function that needs
* to be called with the decided information: fn( err, success ), where success is a boolean
* value where false means that the request is rejected, and err is an error code (engine.io)
* @default null
*/
allowRequest?: (request: any, callback: (err: number, success: boolean) => void) => void;
/**
* Transports to allow connections to (engine.io)
* @default ['polling','websocket']
*/
transports?: string[];
/**
* Whether to allow transport upgrades (engine.io)
* @default true
*/
allowUpgrades?: boolean;
/**
* parameters of the WebSocket permessage-deflate extension (see ws module).
* Set to false to disable (engine.io)
* @default true
*/
perMessageDeflate?: Object | boolean;
/**
* Parameters of the http compression for the polling transports (see zlib).
* Set to false to disable, or set an object with parameter "threshold:number"
* to only compress data if the byte size is above this value (1024) (engine.io)
* @default true|1024
*/
httpCompression?: Object | boolean;
/**
* Name of the HTTP cookie that contains the client sid to send as part of
* handshake response headers. Set to false to not send one (engine.io)
* @default "io"
*/
cookie?: string | boolean;
/**
* Whether to let engine.io handle the OPTIONS requests.
* You can also pass a custom function to handle the requests
* @default true
*/
handlePreflightRequest?: ((req: any, res: any) => void) | boolean;
}
/**
* The Namespace, sandboxed environments for sockets, each connection
* to a Namespace requires a new Socket
*/
interface Namespace extends NodeJS.EventEmitter {
/**
* The name of the NameSpace
*/
name: string;
/**
* The controller Server for this Namespace
*/
server: Server;
/**
* A dictionary of all the Sockets connected to this Namespace, where
* the Socket ID is the key
*/
sockets: { [id: string]: Socket };
/**
* A dictionary of all the Sockets connected to this Namespace, where
* the Socket ID is the key
*/
connected: { [id: string]: Socket };
/**
* The Adapter that we're using to handle dealing with rooms etc
*/
adapter: Adapter;
/**
* Sets the 'json' flag when emitting an event
*/
json: Namespace;
/**
* Registers a middleware function, which is a function that gets executed
* for every incoming Socket
* @param fn The function to call when we get a new incoming socket. It should
* take one parameter of type Socket, and one callback function to call to
* execute the next middleware function. The callback can take one optional
* parameter, err, if there was an error. Errors passed to middleware callbacks
* are sent as special 'error' packets to clients
* @return This Namespace
*/
use(fn: (socket: Socket, fn: (err?: any) => void) => void): Namespace;
/**
* Targets a room when emitting
* @param room The name of the room that we're targeting
* @return This Namespace
*/
to(room: string): Namespace;
/**
* @see to( room )
*/
in(room: string): Namespace;
/**
* Sends a 'message' event
* @see emit( event, ...args )
* @return This Namespace
*/
send(...args: any[]): Namespace;
/**
* @see send( ...args )
*/
write(...args: any[]): Namespace;
/**
* The event fired when we get a new connection
* @param event The event being fired: 'connection'
* @param listener A listener that should take one parameter of type Socket
* @return This Namespace
*/
on(event: 'connection', listener: (socket: Socket) => void): this;
/**
* @see on( 'connection', listener )
*/
on(event: 'connect', listener: (socket: Socket) => void): this;
/**
* Base 'on' method to add a listener for an event
* @param event The event that we want to add a listener for
* @param listener The callback to call when we get the event. The parameters
* for the callback depend on the event
* @ This Namespace
*/
on(event: string, listener: Function): this;
/**
* Gets a list of clients.
* @return This Namespace
*/
clients(fn: Function): Namespace;
/**
* Sets the compress flag.
* @param compress If `true`, compresses the sending data
* @return This Namespace
*/
compress(compress: boolean): Namespace;
}
interface Packet extends Array<any> {
/**
* Event name
*/
[0]: string;
/**
* Packet data
*/
[1]: any;
/**
* Ack function
*/
[2]: (...args: any[]) => void;
}
/**
* The socket, which handles our connection for a namespace. NOTE: while
* we technically extend NodeJS.EventEmitter, we're not putting it here
* as we have a problem with the emit() event (as it's overridden with a
* different return)
*/
interface Socket extends NodeJS.EventEmitter {
/**
* The namespace that this socket is for
*/
nsp: Namespace;
/**
* The Server that our namespace is in
*/
server: Server;
/**
* The Adapter that we use to handle our rooms
*/
adapter: Adapter;
/**
* The unique ID for this Socket. Regenerated at every connection. This is
* also the name of the room that the Socket automatically joins on connection
*/
id: string;
/**
* The http.IncomingMessage request sent with the connection. Useful
* for recovering headers etc
*/
request: any;
/**
* The Client associated with this Socket
*/
client: Client;
/**
* The underlying Engine.io Socket instance
*/
conn: EngineSocket;
/**
* The list of rooms that this Socket is currently in, where
* the ID the the room ID
*/
rooms: { [id: string]: string };
/**
* Is the Socket currently connected?
*/
connected: boolean;
/**
* Is the Socket currently disconnected?
*/
disconnected: boolean;
/**
* The object used when negociating the handshake
*/
handshake: Handshake;
/**
* Sets the 'json' flag when emitting an event
*/
json: Socket;
/**
* Sets the 'volatile' flag when emitting an event. Volatile messages are
* messages that can be dropped because of network issues and the like. Use
* for high-volume/real-time messages where you don't need to receive *all*
* of them
*/
volatile: Socket;
/**
* Sets the 'broadcast' flag when emitting an event. Broadcasting an event
* will send it to all the other sockets in the namespace except for yourself
*/
broadcast: Socket;
/**
* Targets a room when broadcasting
* @param room The name of the room that we're targeting
* @return This Socket
*/
to(room: string): Socket;
/**
* @see to( room )
*/
in(room: string): Socket;
/**
* Registers a middleware, which is a function that gets executed for every incoming Packet and receives as parameter the packet and a function to optionally defer execution to the next registered middleware.
*
* Errors passed to middleware callbacks are sent as special error packets to clients.
*/
use(fn: (packet: Packet, next: (err?: any) => void) => void): Socket;
/**
* Sends a 'message' event
* @see emit( event, ...args )
*/
send(...args: any[]): Socket;
/**
* @see send( ...args )
*/
write(...args: any[]): Socket;
/**
* Joins a room. You can join multiple rooms, and by default, on connection,
* you join a room with the same name as your ID
* @param name The name of the room that we want to join
* @param fn An optional callback to call when we've joined the room. It should
* take an optional parameter, err, of a possible error
* @return This Socket
*/
join(name: string | string[], fn?: (err?: any) => void): Socket;
/**
* Leaves a room
* @param name The name of the room to leave
* @param fn An optional callback to call when we've left the room. It should
* take on optional parameter, err, of a possible error
*/
leave(name: string, fn?: Function): Socket;
/**
* Leaves all the rooms that we've joined
*/
leaveAll(): void;
/**
* Disconnects this Socket
* @param close If true, also closes the underlying connection
* @return This Socket
*/
disconnect(close?: boolean): Socket;
/**
* Returns all the callbacks for a particular event
* @param event The event that we're looking for the callbacks of
* @return An array of callback Functions, or an empty array if we don't have any
*/
listeners(event: string): Function[];
/**
* Sets the compress flag
* @param compress If `true`, compresses the sending data
* @return This Socket
*/
compress(compress: boolean): Socket;
/**
* Emits the error
* @param err Error message=
*/
error(err: any): void;
}
interface Handshake {
/**
* The headers passed along with the request. e.g. 'host',
* 'connection', 'accept', 'referer', 'cookie'
*/
headers: any;
/**
* The current time, as a string
*/
time: string;
/**
* The remote address of the connection request
*/
address: string;
/**
* Is this a cross-domain request?
*/
xdomain: boolean;
/**
* Is this a secure request?
*/
secure: boolean;
/**
* The timestamp for when this was issued
*/
issued: number;
/**
* The request url
*/
url: string;
/**
* Any query string parameters in the request url
*/
query: any;
}
/**
* The interface describing a room
*/
interface Room {
sockets: { [id: string]: boolean };
length: number;
}
/**
* The interface describing a dictionary of rooms
* Where room is the name of the room
*/
interface Rooms {
[room: string]: Room;
}
/**
* The interface used when dealing with rooms etc
*/
interface Adapter extends NodeJS.EventEmitter {
/**
* The namespace that this adapter is for
*/
nsp: Namespace;
/**
* A dictionary of all the rooms that we have in this namespace
*/
rooms: Rooms;
/**
* A dictionary of all the socket ids that we're dealing with, and all
* the rooms that the socket is currently in
*/
sids: { [id: string]: { [room: string]: boolean } };
/**
* Adds a socket to a room. If the room doesn't exist, it's created
* @param id The ID of the socket to add
* @param room The name of the room to add the socket to
* @param callback An optional callback to call when the socket has been
* added. It should take an optional parameter, error, if there was a problem
*/
add(id: string, room: string, callback?: (err?: any) => void): void;
/**
* Removes a socket from a room. If there are no more sockets in the room,
* the room is deleted
* @param id The ID of the socket that we're removing
* @param room The name of the room to remove the socket from
* @param callback An optional callback to call when the socket has been
* removed. It should take on optional parameter, error, if there was a problem
*/
del(id: string, room: string, callback?: (err?: any) => void): void;
/**
* Removes a socket from all the rooms that it's joined
* @param id The ID of the socket that we're removing
*/
delAll(id: string): void;
/**
* Broadcasts a packet
* @param packet The packet to broadcast
* @param opts Any options to send along:
* - rooms: An optional list of rooms to broadcast to. If empty, the packet is broadcast to all sockets
* - except: A list of Socket IDs to exclude
* - flags: Any flags that we want to send along ('json', 'volatile', 'broadcast')
*/
broadcast(packet: any, opts: { rooms?: string[]; except?: string[]; flags?: { [flag: string]: boolean } }): void;
}
/**
* The client behind each socket (can have multiple sockets)
*/
interface Client {
/**
* The Server that this client belongs to
*/
server: Server;
/**
* The underlying Engine.io Socket instance
*/
conn: EngineSocket;
/**
* The ID for this client. Regenerated at every connection
*/
id: string;
/**
* The http.IncomingMessage request sent with the connection. Useful
* for recovering headers etc
*/
request: any;
/**
* The dictionary of sockets currently connect via this client (i.e. to different
* namespaces) where the Socket ID is the key
*/
sockets: { [id: string]: Socket };
/**
* A dictionary of all the namespaces for this client, with the Socket that
* deals with that namespace
*/
nsps: { [nsp: string]: Socket };
}
/**
* A reference to the underlying engine.io Socket connection.
*/
interface EngineSocket extends NodeJS.EventEmitter {
/**
* The ID for this socket - matches Client.id
*/
id: string;
/**
* The Engine.io Server for this socket
*/
server: any;
/**
* The ready state for the client. Either 'opening', 'open', 'closing', or 'closed'
*/
readyState: string;
/**
* The remote IP for this connection
*/
remoteAddress: string;
/**
* whether the transport has been upgraded
*/
upgraded: boolean;
/**
* (http.IncomingMessage): request that originated the Socket
*/
request: any;
/**
* (Transport): transport reference
*/
transport: any;
}
}

View File

@@ -0,0 +1,136 @@
import { EventEmitter } from 'events'
import { Client } from './client'
import { SocketIO } from './interfaces';
import { ServerEvent } from '../server';
import { Socket } from './socket';
import { Adapter } from './adapter';
import { Server } from './index'
import { Packet } from './packet';
import { SubPacketTypes } from './types';
export class Namespace extends EventEmitter implements SocketIO.Namespace {
name: string;
server: Server;
sockets: { [id: string]: Socket; };
connected: { [id: string]: Socket; };
adapter: SocketIO.Adapter;
json: SocketIO.Namespace;
fns: any[];
ids: number;
rooms: string[];
flags: { [key: string]: boolean };
private events = ['connect', 'connection', 'newListener']
constructor(name: string, server: Server) {
super();
this.name = name;
this.server = server;
this.sockets = {};
this.connected = {};
this.fns = [];
this.ids = 0;
this.rooms = [];
this.flags = {};
this.adapter = new Adapter(this);
}
initAdapter() {
// @ts-ignore
this.adapter = new (this.server.adapter())()
}
add(client: Client, query?: any, callback?: () => void) {
// client.conn.request.url();
let socket = new Socket(this, client, {});
this.sockets[client.id] = socket;
client.nsps[this.name] = socket;
this.onconnection(socket);
return socket;
}
del(client: Client) {
let socket = this.sockets[client.id];
socket.disconnect();
delete this.sockets[client.id];
}
use(fn: (socket: SocketIO.Socket, fn: (err?: any) => void) => void): SocketIO.Namespace {
throw new Error("Method not implemented.");
}
to(room: string): SocketIO.Namespace {
if (!~this.rooms.indexOf(room)) this.rooms.push(room);
return this;
}
in(room: string): SocketIO.Namespace {
return this.to(room);
}
send(...args: any[]): SocketIO.Namespace {
super.emit('message', ...args)
return this;
}
write(...args: any[]): SocketIO.Namespace {
return this.send(...args);
}
emit(event: string, ...args: any[]): boolean {
if (~this.events.indexOf(event)) {
super.emit(event, ...args);
// @ts-ignore
return this;
}
// set up packet object
var packet = {
type: (this.flags.binary !== undefined ? this.flags.binary : this.hasBin(args)) ? SubPacketTypes.BINARY_EVENT : SubPacketTypes.EVENT,
data: args
}
if ('function' == typeof args[args.length - 1]) {
throw new Error('Callbacks are not supported when broadcasting');
}
var rooms = this.rooms.slice(0);
var flags = Object.assign({}, this.flags);
// reset flags
this.rooms = [];
this.flags = {};
this.adapter.broadcast(packet, {
rooms: rooms,
flags: flags
});
// @ts-ignore
return this;
}
hasBin(args: any[]) {
return false;
}
clients(fn: Function): SocketIO.Namespace {
return fn(Object.values(this.sockets))
}
compress(compress: boolean): SocketIO.Namespace {
throw new Error("Method not implemented.");
}
process(packet: Packet, client: Client) {
switch (packet.sub_type) {
case SubPacketTypes.CONNECT:
this.add(client);
break;
default:
this.sockets[client.id].onpacket(packet);
break;
}
}
remove(socket: Socket) {
if (this.sockets.hasOwnProperty(socket.id)) {
delete this.sockets[socket.id];
} else {
// debug('ignoring remove for %s', socket.id);
}
}
private onconnection(socket: any) {
let client = socket as Socket;
this.sockets[client.id] = client;
client.onconnect()
this.emit(ServerEvent.connect, socket);
this.emit(ServerEvent.connection, socket);
}
}

View File

@@ -0,0 +1,11 @@
import { PacketTypes, SubPacketTypes } from './types'
export interface Packet {
type: PacketTypes;
sub_type?: SubPacketTypes;
nsp?: string;
id?: number;
name?: string;
data?: any;
attachments?: any;
}

View File

@@ -0,0 +1,158 @@
import { Packet } from "./packet";
import { PacketTypes, SubPacketTypes } from "./types";
export class Parser {
encode(packet: Packet): string {
let origin = JSON.stringify(packet)
// first is type
let str = '' + packet.type;
if (packet.type == PacketTypes.PONG) {
if (packet.data) { str += packet.data };
return str;
}
if (packet.sub_type != undefined) {
str += packet.sub_type;
}
// attachments if we have them
if ([SubPacketTypes.BINARY_EVENT, SubPacketTypes.BINARY_ACK].includes(packet.sub_type)) {
str += packet.attachments + '-';
}
// if we have a namespace other than `/`
// we append it followed by a comma `,`
if (packet.nsp && '/' !== packet.nsp) {
str += packet.nsp + ',';
}
// immediately followed by the id
if (null != packet.id) {
str += packet.id;
}
if (packet.sub_type == SubPacketTypes.EVENT) {
if (packet.name == undefined) { throw new Error(`SubPacketTypes.EVENT name can't be empty!`) }
packet.data = [packet.name, ...packet.data]
}
// json data
if (null != packet.data) {
let payload = this.tryStringify(packet.data);
if (payload !== false) {
str += payload;
} else {
return '4"encode error"'
}
}
console.debug(`encoded ${origin} as ${str}`);
return str;
}
tryStringify(str) {
try {
return JSON.stringify(str);
} catch (e) {
return false;
}
}
decode(str: string): Packet {
let i = 0;
// ignore parse binary
// if ((frame.getByte(0) == 'b' && frame.getByte(1) == '4')
// || frame.getByte(0) == 4 || frame.getByte(0) == 1) {
// return parseBinary(head, frame);
// }
// look up type
let p: Packet = {
type: Number(str.charAt(i))
};
if (null == PacketTypes[p.type]) {
return this.error('unknown packet type ' + p.type);
}
// if str empty return
if (str.length == i + 1) {
return p;
}
// if is ping packet read data and return
if (PacketTypes.PING == p.type) {
p.data = str.substr(++i);
return p;
}
// look up sub type
p.sub_type = Number(str.charAt(++i));
if (null == PacketTypes[p.sub_type]) {
return this.error('unknown sub packet type ' + p.type);
}
// look up attachments if type binary
if ([SubPacketTypes.BINARY_ACK, SubPacketTypes.BINARY_EVENT].includes(p.sub_type)) {
let buf = '';
while (str.charAt(++i) !== '-') {
buf += str.charAt(i);
if (i == str.length) break;
}
if (buf != `${Number(buf)}` || str.charAt(i) !== '-') {
return this.error('Illegal attachments');
}
p.attachments = Number(buf);
}
// look up namespace (if any)
if ('/' === str.charAt(i + 1)) {
p.nsp = '';
while (++i) {
let c = str.charAt(i);
if (',' === c) break;
p.nsp += c;
if (i === str.length) break;
}
} else {
p.nsp = '/';
}
// look up id
let next = str.charAt(i + 1);
if ('' !== next && !isNaN(Number(next))) {
let id = ''
while (++i) {
let c = str.charAt(i);
if (null == c || isNaN(Number(c))) {
--i;
break;
}
id += str.charAt(i);
if (i === str.length) break;
}
p.id = Number(id);
}
// ignore binary packet
if (p.sub_type == SubPacketTypes.BINARY_EVENT) {
return this.error('not support binary parse...')
}
// look up json data
if (str.charAt(++i)) {
let payload = this.tryParse(str.substr(i));
let isPayloadValid = payload !== false && (p.sub_type == SubPacketTypes.ERROR || Array.isArray(payload));
if (isPayloadValid) {
p.name = payload[0];
p.data = payload.slice(1);
} else {
return this.error('invalid payload ' + str.substr(i));
}
}
console.debug(`decoded ${str} as ${JSON.stringify(p)}`);
return p;
}
tryParse(str) {
try {
return JSON.parse(str);
} catch (e) {
return false;
}
}
error(error: string): Packet {
return {
type: PacketTypes.MESSAGE,
sub_type: SubPacketTypes.ERROR,
data: 'parser error: ' + error
};
}
}

View File

@@ -0,0 +1,294 @@
import { EventEmitter } from 'events'
import { SocketIO } from "./interfaces";
import { Packet } from './packet';
import { PacketTypes, SubPacketTypes } from './types';
import { Client } from './client';
import { Namespace } from './namespace';
export class Socket extends EventEmitter implements SocketIO.Socket {
nsp: Namespace;
server: SocketIO.Server;
adapter: SocketIO.Adapter;
id: string;
request: any;
client: Client;
conn: SocketIO.EngineSocket;
rooms: { [id: string]: string; };
acks: { [id: string]: Function; };
connected: boolean;
disconnected: boolean;
handshake: SocketIO.Handshake;
fns: any[];
flags: { [key: string]: boolean };
_rooms: string[];
private events = [
'error',
'connect',
'disconnect',
'disconnecting',
'newListener',
'removeListener'
]
constructor(nsp: Namespace, client: Client, query = {}) {
super();
this.nsp = nsp;
this.server = nsp.server;
this.adapter = this.nsp.adapter;
this.id = nsp.name !== '/' ? nsp.name + '#' + client.id : client.id;
this.client = client;
this.request = client.request;
this.conn = client.conn;
this.rooms = {};
this.acks = {};
this.connected = true;
this.disconnected = false;
// this.handshake = this.buildHandshake(query);
this.fns = [];
this.flags = {};
this._rooms = [];
}
get json() {
this.flags.json = true;
return this
}
get volatile() {
this.flags.volatile = true;
return this
}
get broadcast() {
this.flags.broadcast = true;
return this
}
get local() {
this.flags.local = true;
return this
}
to(room: string): SocketIO.Socket {
if (!~this._rooms.indexOf(room)) this._rooms.push(room);
return this;
}
in(room: string): SocketIO.Socket {
return this.to(room);
}
use(fn: (packet: SocketIO.Packet, next: (err?: any) => void) => void): SocketIO.Socket {
throw new Error("Method not implemented.");
}
send(...args: any[]): SocketIO.Socket {
this.emit("message", ...args)
return this;
}
write(...args: any[]): SocketIO.Socket {
return this.send(...args);
}
join(rooms: string | string[], fn?: (err?: any) => void): SocketIO.Socket {
if (!Array.isArray(rooms)) {
rooms = [rooms];
}
rooms = rooms.filter((room) => {
return !this.rooms.hasOwnProperty(room);
});
if (!rooms.length) {
fn && fn(null);
return this;
}
return this;
}
leave(name: string, fn?: Function): SocketIO.Socket {
delete this.rooms[name];
fn && fn(null)
return this;
}
leaveAll(): void {
this.adapter.delAll(this.id);
this.rooms = {};
}
disconnect(close?: boolean): SocketIO.Socket {
if (!this.connected) return this;
if (close) {
this.client.disconnect();
} else {
this.packet({ type: PacketTypes.MESSAGE, sub_type: SubPacketTypes.DISCONNECT });
this.onclose('server namespace disconnect');
}
return this;
}
compress(compress: boolean): SocketIO.Socket {
throw new Error("Method not implemented.");
}
error(err: any): void {
this.packet({ type: PacketTypes.MESSAGE, sub_type: SubPacketTypes.ERROR, data: err });
}
// ==========================================
buildHandshake(query): SocketIO.Handshake {
let requestQuery = this.request.uri();
return {
headers: this.request.headers(),
time: (new Date) + '',
address: this.conn.remoteAddress,
xdomain: !!this.request.headers.origin,
secure: !!this.request.connection.encrypted,
issued: +(new Date),
url: this.request.url,
query: Object.assign(query, requestQuery)
}
}
emit(event: string, ...args: any[]): boolean {
if (~this.events.indexOf(event)) {
super.emit(event, ...args);
// @ts-ignore
return this;
}
let packet: Packet = {
type: PacketTypes.MESSAGE,
sub_type: (this.flags.binary !== undefined ? this.flags.binary : this.hasBin(args)) ? SubPacketTypes.BINARY_EVENT : SubPacketTypes.EVENT,
name: event,
data: args
}
// access last argument to see if it's an ACK callback
if (typeof args[args.length - 1] === 'function') {
if (this._rooms.length || this.flags.broadcast) {
throw new Error('Callbacks are not supported when broadcasting');
}
// debug('emitting packet with ack id %d', this.nsp.ids);
this.acks[this.nsp.ids] = args.pop();
packet.id = this.nsp.ids++;
}
let rooms = this._rooms.slice(0);
let flags = Object.assign({}, this.flags);
// reset flags
this._rooms = [];
this.flags = {};
if (rooms.length || flags.broadcast) {
this.adapter.broadcast(packet, {
except: [this.id],
rooms: rooms,
flags: flags
});
} else {
// dispatch packet
this.packet(packet, flags);
}
// @ts-ignore
return this;
}
packet(packet: Packet, opts?: any) {
packet.nsp = this.nsp.name;
opts = opts || {};
opts.compress = false !== opts.compress;
this.client.packet(packet, opts);
}
onconnect() {
this.nsp.connected[this.id] = this;
this.client.sockets[this.id] = this;
this.join(this.id);
// let skip = this.nsp.name === '/' && this.nsp.fns.length === 0;
// if (skip) {
// debug('packet already sent in initial handshake');
// } else {
this.packet({
type: PacketTypes.MESSAGE,
sub_type: SubPacketTypes.CONNECT
});
// }
}
onclose(reason?: string) {
if (!this.connected) return this;
// debug('closing socket - reason %s', reason);
this.emit('disconnecting', reason);
this.leaveAll();
this.nsp.remove(this);
this.client.remove(this);
this.connected = false;
this.disconnected = true;
delete this.nsp.connected[this.id];
this.emit('disconnect', reason);
}
onpacket(packet: Packet) {
switch (packet.sub_type) {
// 2
case SubPacketTypes.EVENT:
this.onevent(packet);
break;
// 5
case SubPacketTypes.BINARY_EVENT:
this.onevent(packet);
break;
// 3
case SubPacketTypes.ACK:
this.onack(packet);
break;
// 6
case SubPacketTypes.BINARY_ACK:
this.onack(packet);
break;
// 1
case SubPacketTypes.DISCONNECT:
this.ondisconnect();
break;
// 4
case SubPacketTypes.ERROR:
this.onerror(new Error(packet.data));
}
}
onerror(err: Error) {
if (this.listeners('error').length) {
this.emit('error', err);
} else {
console.error('Missing error handler on `socket`.');
console.error(err.stack);
}
}
ondisconnect() {
this.onclose('client namespace disconnect')
}
onevent(packet: Packet) {
if (null != packet.id) {
// debug('attaching ack callback to event');
this.dispatch(packet, this.ack(packet.id));
} else {
this.dispatch(packet);
}
}
ack(id: number) {
let sent = false;
return (...args: any[]) => {
if (sent) return;
this.packet({
id: id,
type: PacketTypes.MESSAGE,
sub_type: this.hasBin(args) ? SubPacketTypes.BINARY_ACK : SubPacketTypes.ACK,
data: args
});
sent = true;
}
}
onack(packet: Packet) {
let ack = this.acks[packet.id];
if ('function' == typeof ack) {
// debug('calling ack %s with %j', packet.id, packet.data);
ack.apply(this, packet.data);
delete this.acks[packet.id];
} else {
// debug('bad ack %s', packet.id);
}
}
dispatch(packet: Packet, ack?: Function) {
if (ack) { this.acks[packet.id] = ack; }
super.emit(packet.name, ...packet.data, ack)
}
private hasBin(obj: any) {
return false;
}
}

Some files were not shown because too many files have changed in this diff Show More