Compare commits
61 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| edf8410cd1 | |||
| b0b4bbcc2b | |||
| e68689c560 | |||
| 58353cb5b8 | |||
| 8c6b75ff10 | |||
| d53287fc51 | |||
| 13a3611ebd | |||
| 6d90980726 | |||
| 42de3700ba | |||
| 5991662764 | |||
| 1c98c19e37 | |||
| c596280d8d | |||
| 77301e0130 | |||
| 90878fc7df | |||
| a0a4c13e7b | |||
| 0e92a9c795 | |||
| 0c69462bb4 | |||
| 78a5ed31b3 | |||
| f4e9b2627d | |||
| 9dd7abe6fd | |||
| 12743bbbe0 | |||
| d9a2ea9c78 | |||
| c505cda10b | |||
| 100ccbcde3 | |||
| c6575ed481 | |||
| 83359d8cb9 | |||
| cca4979f16 | |||
| 251c9366f5 | |||
| 8f01dcc8e8 | |||
| c25a616dba | |||
| aa9169b043 | |||
| d87e152f3b | |||
| 2fcadeda4e | |||
| b7927830ae | |||
| 2dbd2182c2 | |||
| 01df79eaf1 | |||
| 16fe9ba9bd | |||
| 950ce69b83 | |||
| fa8e44d838 | |||
| b7af785273 | |||
| 6c9f7bbcf6 | |||
| c4c4c7f301 | |||
| 6538c4b7bb | |||
| a4e6d1660d | |||
| 511b042eba | |||
| 6f0b5a5572 | |||
| e9ac46487c | |||
| 9371823d30 | |||
| c86f0d9ec1 | |||
| c2d94ef104 | |||
| 6ada3e41d0 | |||
| 8c12319dc9 | |||
| 395d2d8816 | |||
| 6f628a3d7e | |||
| 2232e82c36 | |||
| 291b5010e7 | |||
| 3595294444 | |||
| e38358ef98 | |||
| 4c418c33c0 | |||
| 65d112be09 | |||
| 15a75dffe2 |
17
README.MD
17
README.MD
@@ -11,19 +11,24 @@
|
|||||||
├─api 全平台兼容的接口
|
├─api 全平台兼容的接口
|
||||||
├─core 核心代码 用于引导加载
|
├─core 核心代码 用于引导加载
|
||||||
├─common 公共类库代码 例如 http reflect 模块
|
├─common 公共类库代码 例如 http reflect 模块
|
||||||
├─compile 实时编译模块 自动编译TS文件为js
|
├─client NodeJS的Minecraft客户端 用于调试插件
|
||||||
├─container IOC容器 用于注入具体实现
|
├─container IOC容器 用于注入具体实现
|
||||||
|
├─ployfill Nashorn 的一些自定义增强
|
||||||
├─nashorn Nashorn 的类型定义
|
├─nashorn Nashorn 的类型定义
|
||||||
├─ployfill Java Nashorn的补丁
|
|
||||||
├─bungee BungeeCordAPI内部实现
|
├─bungee BungeeCordAPI内部实现
|
||||||
├─bukkit BukkitAPI内部实现
|
├─bukkit BukkitAPI内部实现
|
||||||
├─sponge SpongeAPI内部实现
|
├─sponge SpongeAPI内部实现
|
||||||
|
├─nukkit NukkitAPI内部实现
|
||||||
├─plugin 插件管理器
|
├─plugin 插件管理器
|
||||||
├─manager 插件管理中心后端服务
|
├─websocket Netty的WebSocket注入
|
||||||
├─types Java在TypeScript的类型定义文件
|
├─type Java的类型定义
|
||||||
├─websocket Netty的WebSocket的MiaoScript实现(兼容socket.io)
|
| ├─bungee BungeeCord类型定义
|
||||||
|
| ├─bukkit Bukkit类型定义
|
||||||
|
| ├─sponge Sponge类型定义
|
||||||
|
| └─nukkit Nukkit类型定义
|
||||||
└─plugins 这里当然是插件啦
|
└─plugins 这里当然是插件啦
|
||||||
├─bungee 只兼容BungeeCord的插件
|
├─bungee 只兼容BungeeCord的插件
|
||||||
├─bukkit 只兼容Bukkit的插件
|
├─bukkit 只兼容Bukkit的插件
|
||||||
└─sponge 只兼容Sponge的插件
|
├─sponge 只兼容Sponge的插件
|
||||||
|
└─nukkit 只兼容Nukkit的插件
|
||||||
```
|
```
|
||||||
|
|||||||
62
cli.sh
62
cli.sh
@@ -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
|
|
||||||
|
|
||||||
90
doc/MCBBS.MD
90
doc/MCBBS.MD
@@ -5,10 +5,55 @@
|
|||||||
|
|
||||||
### 更新日志
|
### 更新日志
|
||||||
|
|
||||||
|
- 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
|
- 2019-09-25
|
||||||
- 完善 `Sponge` 类型自动补全
|
- 新增 `@ms/type` 的 `sponge` 类型自动补全
|
||||||
- 2019-09-24
|
- 2019-09-24
|
||||||
- 完善 `Bukkit` 类型自动补全
|
- 新增 `@ms/type` 的 `bukkit` 类型自动补全
|
||||||
|
|
||||||
## 插件简介
|
## 插件简介
|
||||||
|
|
||||||
@@ -65,6 +110,8 @@
|
|||||||
- 完整的服务端Java类自动补全
|
- 完整的服务端Java类自动补全
|
||||||
- 全新的 IOC容器 注入功能
|
- 全新的 IOC容器 注入功能
|
||||||
- 注解式 注册命令 注册事件
|
- 注解式 注册命令 注册事件
|
||||||
|
- 2020年3月2日 发布0.3.0版本
|
||||||
|
- 支持 Bukkit Nukkit BungeeCord Sponge
|
||||||
|
|
||||||
### 进展
|
### 进展
|
||||||
|
|
||||||
@@ -98,14 +145,15 @@
|
|||||||
├─bungee BungeeCordAPI内部实现
|
├─bungee BungeeCordAPI内部实现
|
||||||
├─bukkit BukkitAPI内部实现
|
├─bukkit BukkitAPI内部实现
|
||||||
├─sponge SpongeAPI内部实现
|
├─sponge SpongeAPI内部实现
|
||||||
|
├─nukkit NukkitAPI内部实现
|
||||||
├─ployfill JS环境的相关环境补全
|
├─ployfill JS环境的相关环境补全
|
||||||
├─plugin 插件管理器
|
├─plugin 插件管理器
|
||||||
|
├─websocket Netty的WebSocket注入
|
||||||
├─type Java的类型定义
|
├─type Java的类型定义
|
||||||
| ├─bungee BungeeCord类型定义
|
| ├─bungee BungeeCord类型定义
|
||||||
| ├─bukkit Bukkit类型定义
|
| ├─bukkit Bukkit类型定义
|
||||||
| ├─sponge Sponge类型定义
|
| ├─sponge Sponge类型定义
|
||||||
| └─nukkit Nukkit类型定义
|
| └─nukkit Nukkit类型定义
|
||||||
├─websocket Netty的WebSocket注入
|
|
||||||
└─plugins 这里当然是插件啦
|
└─plugins 这里当然是插件啦
|
||||||
├─bungee 只兼容BungeeCord的插件
|
├─bungee 只兼容BungeeCord的插件
|
||||||
├─bukkit 只兼容Bukkit的插件
|
├─bukkit 只兼容Bukkit的插件
|
||||||
@@ -132,8 +180,12 @@ YUMC: https://git.yumc.pw/circlecloud/ms
|
|||||||
- 进入目录 `ms`
|
- 进入目录 `ms`
|
||||||
- 安装 npm 包
|
- 安装 npm 包
|
||||||
- `yarn`
|
- `yarn`
|
||||||
|
- 建立内部依赖链接
|
||||||
|
- `yarn bs`
|
||||||
- 编译一次生成对应的类库
|
- 编译一次生成对应的类库
|
||||||
- `yarn build`
|
- `yarn build`
|
||||||
|
- 编译插件
|
||||||
|
- `yarn build:plugins`
|
||||||
|
|
||||||
### 直接在 MiaoScript Online WebIDE 开发
|
### 直接在 MiaoScript Online WebIDE 开发
|
||||||
|
|
||||||
@@ -146,10 +198,7 @@ YUMC: https://git.yumc.pw/circlecloud/ms
|
|||||||
先来一个 `HelloWorld.ts` 插件示范!
|
先来一个 `HelloWorld.ts` 插件示范!
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
/// <reference types="@ms/types/dist/typings/bukkit" />
|
/// <reference types="@ms/types" />
|
||||||
/// <reference types="@ms/types/dist/typings/sponge" />
|
|
||||||
/// <reference types="@ms/types/dist/typings/bungee" />
|
|
||||||
/// <reference types="@ms/types/dist/typings/nukkit" />
|
|
||||||
|
|
||||||
import { server } from '@ms/api';
|
import { server } from '@ms/api';
|
||||||
import { inject } from '@ms/container';
|
import { inject } from '@ms/container';
|
||||||
@@ -159,6 +208,10 @@ import { plugin, interfaces, cmd, listener, tab } from '@ms/plugin'
|
|||||||
export class HelloWorld extends interfaces.Plugin {
|
export class HelloWorld extends interfaces.Plugin {
|
||||||
@inject(server.Server)
|
@inject(server.Server)
|
||||||
private Server: server.Server
|
private Server: server.Server
|
||||||
|
@config()
|
||||||
|
private config = {
|
||||||
|
version: 1.0.0
|
||||||
|
}
|
||||||
|
|
||||||
load() {
|
load() {
|
||||||
this.logger.log('Plugin load from MiaoScript Plugin System...');
|
this.logger.log('Plugin load from MiaoScript Plugin System...');
|
||||||
@@ -275,6 +328,10 @@ export interface PluginMetadata {
|
|||||||
* 插件名称
|
* 插件名称
|
||||||
*/
|
*/
|
||||||
name: string;
|
name: string;
|
||||||
|
/**
|
||||||
|
* 支持的服务器列表 为空则代表所有
|
||||||
|
*/
|
||||||
|
servers?: string[];
|
||||||
/**
|
/**
|
||||||
* 前缀
|
* 前缀
|
||||||
*/
|
*/
|
||||||
@@ -300,10 +357,10 @@ export interface PluginMetadata {
|
|||||||
|
|
||||||
### 插件生命周期
|
### 插件生命周期
|
||||||
|
|
||||||
MiaoScript的生命周期遵循了 Bukkit 的生命周期
|
MiaoScript 的生命周期遵循了 Bukkit 的生命周期
|
||||||
|
|
||||||
MiaoScript针对不同的服务端 提供了扩展的周期
|
MiaoScript 针对不同的服务端 提供了扩展的周期
|
||||||
以服务端类型开头阶段名结束 例如 `bukkitload` `spongeenbale`
|
以服务端类型开头阶段名结束 例如 `bukkitload` `spongeenbale` `bungeedisable`
|
||||||
扩展的生命周期只会在特定的服务器执行
|
扩展的生命周期只会在特定的服务器执行
|
||||||
|
|
||||||
### load 加载阶段
|
### load 加载阶段
|
||||||
@@ -401,6 +458,19 @@ ServerConnected(e: any) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 配置文件
|
||||||
|
|
||||||
|
配置文件 默认读取的是 `MiaoScript根目录/plugins/插件名称/配置名称.配置格式`
|
||||||
|
|
||||||
|
例如下面文件 默认处理的是 `plugins/MiaoScript/plugins/HelloWorld/config.yml`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
@config()
|
||||||
|
private config = {
|
||||||
|
version: 1.0.0
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## 插件列表
|
## 插件列表
|
||||||
|
|
||||||
暂无
|
暂无
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"useWorkspaces": true,
|
"useWorkspaces": true,
|
||||||
"npmClient": "yarn",
|
"npmClient": "yarn",
|
||||||
"packages": [
|
"packages": [
|
||||||
|
|||||||
@@ -8,8 +8,8 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"bs": "lerna bootstrap",
|
"bs": "lerna bootstrap",
|
||||||
"clean": "lerna run clean",
|
"clean": "lerna run clean",
|
||||||
"watch": "lerna run watch --parallel --scope=\"@ms/!(manager)\"",
|
"watch": "lerna run watch --parallel",
|
||||||
"build": "lerna run build --scope=\"@ms/!(plugins|manager)\"",
|
"build": "lerna run build --scope=\"@ms/!(plugins)\"",
|
||||||
"build:plugins": "lerna run build --scope=\"@ms/plugins\"",
|
"build:plugins": "lerna run build --scope=\"@ms/plugins\"",
|
||||||
"ug": "yarn upgrade-interactive --latest",
|
"ug": "yarn upgrade-interactive --latest",
|
||||||
"lp": "lerna publish"
|
"lp": "lerna publish"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/api",
|
"name": "@ms/api",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,13 +22,15 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/container": "^0.3.0",
|
"@ms/container": "^0.5.0",
|
||||||
"@ms/ployfill": "^0.3.0",
|
"@ms/ployfill": "^0.5.0",
|
||||||
|
"base64-js": "^1.3.1",
|
||||||
"source-map-builder": "^0.0.7"
|
"source-map-builder": "^0.0.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/base64-js": "^1.2.5",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,12 +5,17 @@ export namespace channel {
|
|||||||
* handle plugin message
|
* handle plugin message
|
||||||
* @param data byte[]
|
* @param data byte[]
|
||||||
*/
|
*/
|
||||||
export type ChannelListener = (data: any) => void
|
export type ChannelListener = (data: any, exts?: any) => void
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class Channel {
|
export abstract class Channel {
|
||||||
private listenerMap = [];
|
private listenerMap = [];
|
||||||
|
/**
|
||||||
|
* 注册通道
|
||||||
|
* @param plugin 插件
|
||||||
|
* @param channel 通道
|
||||||
|
* @param exec 执行器
|
||||||
|
*/
|
||||||
listen(plugin: any, channel: string, exec: ChannelListener) {
|
listen(plugin: any, channel: string, exec: ChannelListener) {
|
||||||
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!');
|
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError('Plugin can\'t be undefiend!');
|
||||||
let name = plugin.description.name;
|
let name = plugin.description.name;
|
||||||
@@ -29,6 +34,10 @@ export namespace channel {
|
|||||||
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`);
|
console.debug(`[${name}] register channel ${channel} => ${exec.name || '[anonymous]'}`);
|
||||||
return off;
|
return off;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* 关闭插件注册的通道
|
||||||
|
* @param plugin 插件
|
||||||
|
*/
|
||||||
disable(plugin: any) {
|
disable(plugin: any) {
|
||||||
var channelCache = this.listenerMap[plugin.description.name];
|
var channelCache = this.listenerMap[plugin.description.name];
|
||||||
if (channelCache) {
|
if (channelCache) {
|
||||||
@@ -36,7 +45,6 @@ export namespace channel {
|
|||||||
delete this.listenerMap[plugin.description.name];
|
delete this.listenerMap[plugin.description.name];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send Channel Message
|
* Send Channel Message
|
||||||
* @param player recover target
|
* @param player recover target
|
||||||
|
|||||||
@@ -4,6 +4,12 @@ import { injectable } from "@ms/container";
|
|||||||
export namespace command {
|
export namespace command {
|
||||||
@injectable()
|
@injectable()
|
||||||
export abstract class Command {
|
export abstract class Command {
|
||||||
|
/**
|
||||||
|
* 注册插件命令
|
||||||
|
* @param plugin 插件
|
||||||
|
* @param name 命令
|
||||||
|
* @param exec 执行器
|
||||||
|
*/
|
||||||
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
|
on(plugin: any, name: string, exec: { cmd: Function, tab?: Function }) {
|
||||||
var cmd = this.create(plugin, name);
|
var cmd = this.create(plugin, name);
|
||||||
console.debug(i18n.translate("ms.api.command.register", { plugin: plugin.description.name, name, cmd }))
|
console.debug(i18n.translate("ms.api.command.register", { plugin: plugin.description.name, name, cmd }))
|
||||||
@@ -16,31 +22,34 @@ export namespace command {
|
|||||||
this.onTabComplete(plugin, cmd, exec.tab);
|
this.onTabComplete(plugin, cmd, exec.tab);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* 取消命令注册
|
||||||
|
* @param plugin 插件
|
||||||
|
* @param name 命令
|
||||||
|
*/
|
||||||
off(plugin: any, name: string) {
|
off(plugin: any, name: string) {
|
||||||
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
|
console.debug(i18n.translate("ms.api.command.unregister", { plugin: plugin.description.name, name }))
|
||||||
this.remove(plugin, name);
|
this.remove(plugin, name);
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
* Create Server Command Object
|
|
||||||
*/
|
|
||||||
protected abstract create(plugin: any, command: string);
|
protected abstract create(plugin: any, command: string);
|
||||||
protected abstract remove(plugin: any, command: string);
|
protected abstract remove(plugin: any, command: string);
|
||||||
protected abstract onCommand(plugin: any, command: any, executor: Function);
|
protected abstract onCommand(plugin: any, command: any, executor: Function);
|
||||||
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
|
protected abstract onTabComplete(plugin: any, command: any, tabCompleter: Function);
|
||||||
|
|
||||||
protected setExecutor(plugin: any, command: any, executor: Function) {
|
protected setExecutor(plugin: any, command: any, executor: Function) {
|
||||||
return (sender: any, _: any, command: string, args: string[]) => {
|
return (sender: any, _: any, command: string, args: string[]) => {
|
||||||
try {
|
try {
|
||||||
return executor(sender, command, Java.from(args));
|
return executor(sender, command, Java.from(args));
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.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", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex })
|
||||||
console.ex(ex);
|
console.ex(ex);
|
||||||
console.sender(sender, [`§6执行 §b${plugin.description.name} §6插件 §d${command} ${Java.from(args).join(' ')} §6命令时发生异常`, ...console.stack(ex)])
|
if (sender.name != 'CONSOLE') {
|
||||||
|
console.sender(sender, [i18n.translate("ms.api.command.execute.error", { player: sender.name, plugin: plugin.description.name, command, args: Java.from(args).join(' '), ex }), ...console.stack(ex)])
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
|
protected setTabCompleter(plugin: any, command: any, tabCompleter: Function) {
|
||||||
return (sender: any, _: any, command: string, args: string[]) => {
|
return (sender: any, _: any, command: string, args: string[]) => {
|
||||||
try {
|
try {
|
||||||
@@ -48,17 +57,16 @@ export namespace command {
|
|||||||
var complete = tabCompleter(sender, command, Java.from(args)) || [];
|
var complete = tabCompleter(sender, command, Java.from(args)) || [];
|
||||||
return this.copyPartialMatches(complete, token);
|
return this.copyPartialMatches(complete, token);
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.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.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 [];
|
return [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected copyPartialMatches(complete: string[], token: string, array: string[] = []): string[] {
|
protected copyPartialMatches(complete: string[], token: string, array: string[] = []): string[] {
|
||||||
if (!token) { return complete }
|
if (!token) { return complete }
|
||||||
complete.forEach(function(e) {
|
complete.forEach(function (e) {
|
||||||
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
|
if (typeof e === "string" && e.toLowerCase().startsWith(token.toLowerCase())) {
|
||||||
array.push(e)
|
array.push(e)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
import i18m from '@ms/i18n'
|
import i18m from '@ms/i18n'
|
||||||
import { SourceMapBuilder } from 'source-map-builder'
|
import { SourceMapBuilder } from 'source-map-builder'
|
||||||
|
import * as base64 from 'base64-js'
|
||||||
|
|
||||||
const Arrays = Java.type('java.util.Arrays');
|
const Arrays = Java.type('java.util.Arrays');
|
||||||
const Level = Java.type('java.util.logging.Level');
|
const Level = Java.type('java.util.logging.Level');
|
||||||
const JavaString = Java.type('java.lang.String');
|
|
||||||
const Files = Java.type('java.nio.file.Files');
|
|
||||||
const Paths = Java.type('java.nio.file.Paths');
|
const Paths = Java.type('java.nio.file.Paths');
|
||||||
const ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.'];
|
const ignoreLogPrefix = ['java.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'io.netty.', 'org.spongepowered.'];
|
||||||
|
|
||||||
@@ -23,6 +22,7 @@ export class MiaoScriptConsole implements Console {
|
|||||||
Console: NodeJS.ConsoleConstructor;
|
Console: NodeJS.ConsoleConstructor;
|
||||||
|
|
||||||
private sourceMaps: { [key: string]: SourceMapBuilder } = {};
|
private sourceMaps: { [key: string]: SourceMapBuilder } = {};
|
||||||
|
private sourceFileMaps: { [key: string]: string } = {};
|
||||||
private _name: string = '';
|
private _name: string = '';
|
||||||
private _level: LogLevel = LogLevel.INFO;
|
private _level: LogLevel = LogLevel.INFO;
|
||||||
|
|
||||||
@@ -83,7 +83,7 @@ export class MiaoScriptConsole implements Console {
|
|||||||
this.console(i18m.translate(name, param))
|
this.console(i18m.translate(name, param))
|
||||||
}
|
}
|
||||||
object(obj) {
|
object(obj) {
|
||||||
for (var i in obj) {
|
for (const i in obj) {
|
||||||
this.info(i, '=>', obj[i])
|
this.info(i, '=>', obj[i])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -93,23 +93,31 @@ export class MiaoScriptConsole implements Console {
|
|||||||
readSourceMap(fileName: string, lineNumber: number) {
|
readSourceMap(fileName: string, lineNumber: number) {
|
||||||
try {
|
try {
|
||||||
if (fileName.endsWith('js')) {
|
if (fileName.endsWith('js')) {
|
||||||
var file = Paths.get(fileName + '.map');
|
|
||||||
if (this.sourceMaps[fileName] === undefined) {
|
if (this.sourceMaps[fileName] === undefined) {
|
||||||
if (file.toFile().exists()) {
|
this.sourceMaps[fileName] = null
|
||||||
var sourceMapObj = JSON.parse(new JavaString(Files.readAllBytes(file), "UTF-8"))
|
let sourceLine = base.read(fileName).split('\n');
|
||||||
this.sourceMaps[fileName] = new SourceMapBuilder(sourceMapObj)
|
let lastLine = sourceLine[sourceLine.length - 1]
|
||||||
|
if (lastLine.startsWith('//# sourceMappingURL=')) {
|
||||||
|
let sourceContent = null;
|
||||||
|
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1];
|
||||||
|
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
||||||
|
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
||||||
|
} else if (sourceMappingURL.startsWith('http')) {
|
||||||
|
// TODO
|
||||||
} else {
|
} else {
|
||||||
this.sourceMaps[fileName] = null;
|
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile();
|
||||||
|
if (file.exists()) { sourceContent = base.read(file) }
|
||||||
|
}
|
||||||
|
if (sourceContent) {
|
||||||
|
this.sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
||||||
|
this.sourceFileMaps[fileName] = Paths.get(fileName, '..', this.sourceMaps[fileName].sources[0]).toFile().getCanonicalPath();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (this.sourceMaps[fileName]) {
|
if (this.sourceMaps[fileName]) {
|
||||||
var sourceMapping = this.sourceMaps[fileName].getSource(lineNumber, lineNumber);
|
let sourceMapping = this.sourceMaps[fileName].getSource(lineNumber, 25, true, true);
|
||||||
if (sourceMapping) {
|
fileName = this.sourceFileMaps[fileName]
|
||||||
if (lineNumber != sourceMapping.mapping.sourceLine) {
|
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine; }
|
||||||
fileName = fileName.replace(".js", ".ts");
|
|
||||||
lineNumber = sourceMapping.mapping.sourceLine;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -121,32 +129,32 @@ export class MiaoScriptConsole implements Console {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
stack(ex: Error): string[] {
|
stack(ex: Error): string[] {
|
||||||
var stack = ex.getStackTrace();
|
let stack = ex.getStackTrace();
|
||||||
var cache = ['§4' + ex];
|
let cache = ['§c' + ex];
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
if (stack.class) {
|
if (stack.class) {
|
||||||
stack = Arrays.asList(stack)
|
stack = Arrays.asList(stack)
|
||||||
}
|
}
|
||||||
stack.forEach(trace => {
|
stack.forEach(trace => {
|
||||||
if (trace.className.startsWith('<')) {
|
if (trace.className.startsWith('<')) {
|
||||||
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
let { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||||
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${lineNumber}`)
|
cache.push(` §e->§c ${fileName} => §4${trace.methodName}:${lineNumber}`)
|
||||||
} else {
|
} else {
|
||||||
var className = trace.className;
|
let className = trace.className;
|
||||||
var fileName = trace.fileName as string;
|
var fileName = trace.fileName as string;
|
||||||
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
if (className.startsWith('jdk.nashorn.internal.scripts')) {
|
||||||
className = className.substr(className.lastIndexOf('$') + 1)
|
className = className.substr(className.lastIndexOf('$') + 1)
|
||||||
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
var { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||||
} else {
|
} else {
|
||||||
for (var prefix in ignoreLogPrefix) {
|
for (let prefix in ignoreLogPrefix) {
|
||||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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;
|
return cache;
|
||||||
|
|||||||
16
packages/api/src/constants.ts
Normal file
16
packages/api/src/constants.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
export namespace constants {
|
||||||
|
export namespace Reflect {
|
||||||
|
export const Method = {
|
||||||
|
getServerConnection: [/*spigot 1.8.8*/'aq',/*spigot 1.12.2*/ 'an', /*spigot 1.14.4+*/'getServerConnection', /*catserver 1.12.2*/'func_147137_ag']
|
||||||
|
}
|
||||||
|
export const Field = {
|
||||||
|
listeningChannels: [/*spigot 1.8.8-1.12.2*/'g', /*spigot 1.14.4*/'f', /*spigot 1.15.2+*/'listeningChannels', /*catserver 1.12.2*/'field_151274_e']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export enum ServerType {
|
||||||
|
Bukkit = 'bukkit',
|
||||||
|
Sponge = 'sponge',
|
||||||
|
Nukkit = 'nukkit',
|
||||||
|
Bungee = 'bungee'
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
/// <reference types='@ms/nashorn' />
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* MiaoScript Event处理类
|
* MiaoScript Event处理类
|
||||||
*/
|
*/
|
||||||
@@ -9,6 +7,9 @@ import { injectable, unmanaged } from '@ms/container'
|
|||||||
const Thread = Java.type('java.lang.Thread');
|
const Thread = Java.type('java.lang.Thread');
|
||||||
|
|
||||||
export namespace event {
|
export namespace event {
|
||||||
|
/**
|
||||||
|
* 事件监听优先级
|
||||||
|
*/
|
||||||
export enum EventPriority {
|
export enum EventPriority {
|
||||||
LOWEST = "LOWEST",
|
LOWEST = "LOWEST",
|
||||||
LOW = "LOW",
|
LOW = "LOW",
|
||||||
@@ -61,8 +62,8 @@ export namespace event {
|
|||||||
return count;
|
return count;
|
||||||
}
|
}
|
||||||
|
|
||||||
getJarFile(resource: string) {
|
getJarFile(resource: string, loader?: any) {
|
||||||
let dirs = Thread.currentThread().getContextClassLoader().getResources(resource);
|
let dirs = (loader || Thread.currentThread().getContextClassLoader()).getResources(resource);
|
||||||
if (dirs.hasMoreElements()) {
|
if (dirs.hasMoreElements()) {
|
||||||
let url = dirs.nextElement();
|
let url = dirs.nextElement();
|
||||||
if (url.protocol === "jar") { return url.openConnection().jarFile; }
|
if (url.protocol === "jar") { return url.openConnection().jarFile; }
|
||||||
@@ -146,6 +147,10 @@ export namespace event {
|
|||||||
return off;
|
return off;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭插件监听任务
|
||||||
|
* @param plugin 插件
|
||||||
|
*/
|
||||||
disable(plugin: any) {
|
disable(plugin: any) {
|
||||||
var eventCache = this.listenerMap[plugin.description.name];
|
var eventCache = this.listenerMap[plugin.description.name];
|
||||||
if (eventCache) {
|
if (eventCache) {
|
||||||
@@ -154,8 +159,24 @@ export namespace event {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断
|
||||||
|
* @param clazz 事件类
|
||||||
|
*/
|
||||||
abstract isValidEvent(clazz: any): boolean;
|
abstract isValidEvent(clazz: any): boolean;
|
||||||
|
/**
|
||||||
|
* 注册事件
|
||||||
|
* @param eventCls 事件类
|
||||||
|
* @param exec 执行器
|
||||||
|
* @param priority 优先级
|
||||||
|
* @param ignoreCancel 是否忽略已取消的事件
|
||||||
|
*/
|
||||||
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any;
|
abstract register(eventCls: any, exec: Function, priority: any, ignoreCancel: boolean): any;
|
||||||
|
/**
|
||||||
|
* 取消监听事件
|
||||||
|
* @param event 事件
|
||||||
|
* @param listener 监听器
|
||||||
|
*/
|
||||||
abstract unregister(event: any, listener: any): void;
|
abstract unregister(event: any, listener: any): void;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import "@ms/ployfill"
|
import "@ms/nashorn"
|
||||||
export * from './task'
|
export * from './task'
|
||||||
export * from './event'
|
export * from './event'
|
||||||
export * from './console'
|
export * from './console'
|
||||||
export * from './channel'
|
export * from './channel'
|
||||||
export * from './command'
|
export * from './command'
|
||||||
|
export * from './constants'
|
||||||
export * from './interfaces'
|
export * from './interfaces'
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ export namespace plugin {
|
|||||||
*/
|
*/
|
||||||
export const Plugin = Symbol("Plugin");
|
export const Plugin = Symbol("Plugin");
|
||||||
/**
|
/**
|
||||||
* MiaoScript Plugin
|
* MiaoScript Plugin Folder
|
||||||
*/
|
*/
|
||||||
export const PluginFolder = Symbol("PluginFolder");
|
export const PluginFolder = Symbol("PluginFolder");
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { NativePluginManager } from './native_plugin'
|
||||||
|
|
||||||
export namespace server {
|
export namespace server {
|
||||||
/**
|
/**
|
||||||
* Runtime ServerType
|
* Runtime ServerType
|
||||||
@@ -26,6 +28,9 @@ export namespace server {
|
|||||||
getService(service: string): any;
|
getService(service: string): any;
|
||||||
dispatchCommand(sender: string | any, command: string): boolean;
|
dispatchCommand(sender: string | any, command: string): boolean;
|
||||||
dispatchConsoleCommand(command: string): boolean;
|
dispatchConsoleCommand(command: string): boolean;
|
||||||
|
getPluginsFolder(): string;
|
||||||
|
getNativePluginManager(): NativePluginManager;
|
||||||
|
getNettyPipeline(): any;
|
||||||
sendJson(sender: string | any, json: object | string): void;
|
sendJson(sender: string | any, json: object | string): void;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
6
packages/api/src/interfaces/server/native_plugin.ts
Normal file
6
packages/api/src/interfaces/server/native_plugin.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export interface NativePluginManager {
|
||||||
|
load(name: string): boolean;
|
||||||
|
unload(name: string): boolean;
|
||||||
|
reload(name: string): boolean;
|
||||||
|
delete(name: string): boolean;
|
||||||
|
}
|
||||||
@@ -1,10 +1,20 @@
|
|||||||
import { injectable, DefaultContainer as container } from "@ms/container";
|
|
||||||
|
|
||||||
export namespace task {
|
export namespace task {
|
||||||
export const TaskManager = Symbol('TaskManager')
|
export const TaskManager = Symbol('TaskManager')
|
||||||
export interface TaskManager {
|
export interface TaskManager {
|
||||||
|
/**
|
||||||
|
* 创建任务
|
||||||
|
* @param func 任务内容
|
||||||
|
*/
|
||||||
create(func: Function): task.Task;
|
create(func: Function): task.Task;
|
||||||
|
/**
|
||||||
|
* 在主线程执行代码
|
||||||
|
* @param func 执行内容
|
||||||
|
*/
|
||||||
callSyncMethod(func: Function): any;
|
callSyncMethod(func: Function): any;
|
||||||
|
/**
|
||||||
|
* 关闭任务管理器
|
||||||
|
*/
|
||||||
|
disable();
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 任务抽象
|
* 任务抽象
|
||||||
@@ -21,16 +31,28 @@ export namespace task {
|
|||||||
this.func = func;
|
this.func = func;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置任务异步执行
|
||||||
|
* @param isAsync 是否异步
|
||||||
|
*/
|
||||||
async(isAsync: boolean = true): task.Task {
|
async(isAsync: boolean = true): task.Task {
|
||||||
this.isAsync = isAsync;
|
this.isAsync = isAsync;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置任务延时执行
|
||||||
|
* @param tick 延时 Tick
|
||||||
|
*/
|
||||||
later(tick: number): task.Task {
|
later(tick: number): task.Task {
|
||||||
this.laterTime = tick;
|
this.laterTime = tick;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置任务循环执行
|
||||||
|
* @param tick 循环时间 Tick
|
||||||
|
*/
|
||||||
timer(tick: number): task.Task {
|
timer(tick: number): task.Task {
|
||||||
this.interval = tick;
|
this.interval = tick;
|
||||||
return this;
|
return this;
|
||||||
@@ -45,6 +67,9 @@ export namespace task {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交任务
|
||||||
|
*/
|
||||||
abstract submit(): Cancelable;
|
abstract submit(): Cancelable;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/bukkit",
|
"name": "@ms/bukkit",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript bukkit package",
|
"description": "MiaoScript bukkit package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -24,12 +24,11 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/api": "^0.3.0",
|
"@ms/api": "^0.5.0",
|
||||||
"@ms/common": "^0.3.0",
|
"@ms/common": "^0.5.0",
|
||||||
"@ms/container": "^0.3.0",
|
"@ms/container": "^0.5.0"
|
||||||
"@ms/types": "^0.3.0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,8 +15,8 @@ export class BukkitChannel extends channel.Channel {
|
|||||||
}
|
}
|
||||||
register(channel: string, listener: channel.ChannelListener) {
|
register(channel: string, listener: channel.ChannelListener) {
|
||||||
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, new PluginMessageListener({
|
Messenger.registerIncomingPluginChannel(this.pluginInstance, channel, new PluginMessageListener({
|
||||||
onPluginMessageReceived: (/**String */ var1, /**Player */ var2, /**byte[] */var3) => {
|
onPluginMessageReceived: (/**String */ channel, /**Player */ player, /**byte[] */data) => {
|
||||||
listener(var3)
|
listener(data, { channel, player, data })
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel);
|
Messenger.registerOutgoingPluginChannel(this.pluginInstance, channel);
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ export class BukkitEvent extends event.Event {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getJarFile(resource: string) {
|
getJarFile(resource: string) {
|
||||||
return super.getJarFile('org/bukkit/Bukkit.class')
|
return super.getJarFile('org/bukkit/Bukkit.class', Bukkit.class.classLoader)
|
||||||
}
|
}
|
||||||
isValidEvent(clazz: any): boolean {
|
isValidEvent(clazz: any): boolean {
|
||||||
// 继承于 org.bukkit.event.Event
|
// 继承于 org.bukkit.event.Event
|
||||||
|
|||||||
@@ -1,12 +1,21 @@
|
|||||||
import { server } from '@ms/api'
|
import { server, constants } from '@ms/api'
|
||||||
import { provideSingleton } from '@ms/container';
|
import { provideSingleton } from '@ms/container';
|
||||||
|
|
||||||
|
import * as reflect from '@ms/common/dist/reflect'
|
||||||
import chat from './enhance/chat'
|
import chat from './enhance/chat'
|
||||||
|
|
||||||
let Bukkit = org.bukkit.Bukkit;
|
let Bukkit = org.bukkit.Bukkit;
|
||||||
|
|
||||||
@provideSingleton(server.Server)
|
@provideSingleton(server.Server)
|
||||||
export class BukkitServer implements server.Server {
|
export class BukkitServer implements server.Server {
|
||||||
|
private pluginsFolder: string;
|
||||||
|
private pipeline: any;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.pluginsFolder = Bukkit.getUpdateFolderFile().getParentFile().getCanonicalPath();
|
||||||
|
this.reflectPipeline()
|
||||||
|
}
|
||||||
|
|
||||||
getPlayer(name: string) {
|
getPlayer(name: string) {
|
||||||
return Bukkit.getPlayer(name)
|
return Bukkit.getPlayer(name)
|
||||||
}
|
}
|
||||||
@@ -31,6 +40,15 @@ export class BukkitServer implements server.Server {
|
|||||||
dispatchConsoleCommand(command: string): boolean {
|
dispatchConsoleCommand(command: string): boolean {
|
||||||
return Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)
|
return Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)
|
||||||
}
|
}
|
||||||
|
getPluginsFolder(): string {
|
||||||
|
return this.pluginsFolder;
|
||||||
|
}
|
||||||
|
getNativePluginManager() {
|
||||||
|
return Bukkit.getPluginManager() as any;
|
||||||
|
}
|
||||||
|
getNettyPipeline() {
|
||||||
|
return this.pipeline;
|
||||||
|
}
|
||||||
sendJson(sender: string | any, json: object | string): void {
|
sendJson(sender: string | any, json: object | string): void {
|
||||||
if (typeof sender === "string") {
|
if (typeof sender === "string") {
|
||||||
sender = this.getPlayer(sender)
|
sender = this.getPlayer(sender)
|
||||||
@@ -40,4 +58,27 @@ export class BukkitServer implements server.Server {
|
|||||||
this.dispatchConsoleCommand(result)
|
this.dispatchConsoleCommand(result)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private reflectPipeline() {
|
||||||
|
let consoleServer = reflect.on(Bukkit.getServer()).get('console').get()
|
||||||
|
let connection: any;
|
||||||
|
let promise: any;
|
||||||
|
for (const method of constants.Reflect.Method.getServerConnection) {
|
||||||
|
try {
|
||||||
|
connection = reflect.on(consoleServer).call(method).get()
|
||||||
|
if (connection.class.name.indexOf('ServerConnection') !== -1) { break; }
|
||||||
|
connection = undefined;
|
||||||
|
} catch (error) { }
|
||||||
|
}
|
||||||
|
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
||||||
|
for (const field of constants.Reflect.Field.listeningChannels) {
|
||||||
|
try {
|
||||||
|
promise = reflect.on(connection).get(field).get().get(0);
|
||||||
|
if (promise.class.name.indexOf('Promise') !== -1) { break; }
|
||||||
|
promise = undefined;
|
||||||
|
} catch (error) { }
|
||||||
|
}
|
||||||
|
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
||||||
|
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,9 @@ export class BukkitTaskManager implements task.TaskManager {
|
|||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return Bukkit.getScheduler().callSyncMethod(this.pluginInstance, new Callable({ call: () => func() })).get()
|
return Bukkit.getScheduler().callSyncMethod(this.pluginInstance, new Callable({ call: () => func() })).get()
|
||||||
}
|
}
|
||||||
|
disable() {
|
||||||
|
Bukkit.getScheduler().cancelTasks(this.pluginInstance);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BukkitTask extends task.Task {
|
export class BukkitTask extends task.Task {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/bungee",
|
"name": "@ms/bungee",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript bungee package",
|
"description": "MiaoScript bungee package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -24,12 +24,11 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/api": "^0.3.0",
|
"@ms/api": "^0.5.0",
|
||||||
"@ms/common": "^0.3.0",
|
"@ms/common": "^0.5.0",
|
||||||
"@ms/container": "^0.3.0",
|
"@ms/container": "^0.5.0"
|
||||||
"@ms/types": "^0.3.0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,25 @@
|
|||||||
import { channel } from '@ms/api'
|
import { channel, event } from '@ms/api'
|
||||||
import { provideSingleton } from '@ms/container'
|
import { provideSingleton, inject } from '@ms/container'
|
||||||
|
|
||||||
const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
const Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy()
|
||||||
|
|
||||||
@provideSingleton(channel.Channel)
|
@provideSingleton(channel.Channel)
|
||||||
export class BungeeChannel extends channel.Channel {
|
export class BungeeChannel extends channel.Channel {
|
||||||
|
@inject(event.Event)
|
||||||
|
private eventManager: event.Event;
|
||||||
|
|
||||||
send(player: any, channel: string, data: any) {
|
send(player: any, channel: string, data: any) {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
register(channel: string, listener: channel.ChannelListener) {
|
register(channel: string, listener: channel.ChannelListener) {
|
||||||
Bungee.registerChannel(channel);
|
Bungee.registerChannel(channel);
|
||||||
console.console('§6[§eWARN§6] §eBungeeCord Channel only registerChannel you need self hanler PluginMessageEvent!')
|
// console.console('§6[§eWARN§6] §eMiaoScript channel in BungeeCord only register. you need self hanler PluginMessageEvent!')
|
||||||
|
return this.eventManager.listen({ description: { name: channel } }, "PluginMessageEvent", (event: net.md_5.bungee.api.event.PluginMessageEvent) => {
|
||||||
|
listener(event.getData(), event)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
unregister(channel: string, listener: any) {
|
unregister(channel: string, listener: any) {
|
||||||
Bungee.unregisterChannel(channel);
|
Bungee.unregisterChannel(channel);
|
||||||
|
listener.off();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,42 @@
|
|||||||
import { server } from '@ms/api'
|
import { server, task } from '@ms/api'
|
||||||
import { provideSingleton } from '@ms/container';
|
import { provideSingleton, inject, postConstruct } from '@ms/container'
|
||||||
|
|
||||||
|
import * as reflect from '@ms/common/dist/reflect'
|
||||||
|
|
||||||
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
let Bungee: net.md_5.bungee.api.ProxyServer = base.getInstance().getProxy();
|
||||||
|
|
||||||
@provideSingleton(server.Server)
|
@provideSingleton(server.Server)
|
||||||
export class BungeeServer implements server.Server {
|
export class BungeeServer implements server.Server {
|
||||||
|
private pluginsFolder: string;
|
||||||
|
private pipeline: any;
|
||||||
|
|
||||||
|
@inject(task.TaskManager)
|
||||||
|
private task: task.TaskManager
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.pluginsFolder = Bungee.getPluginsFolder().getCanonicalPath();
|
||||||
|
}
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
|
initialize() {
|
||||||
|
let count = 0;
|
||||||
|
let wait = this.task.create(() => {
|
||||||
|
try {
|
||||||
|
// @ts-ignore
|
||||||
|
this.pipeline = reflect.on(base.getInstance().getProxy()).get('listeners').get().toArray()[0].pipeline()
|
||||||
|
wait.cancel();
|
||||||
|
} catch (ex) {
|
||||||
|
count++
|
||||||
|
if (count > 50) {
|
||||||
|
console.error('Reflect BungeeCord netty channel pipeline error time > 50times. Err: ' + ex)
|
||||||
|
wait.cancel()
|
||||||
|
} else {
|
||||||
|
console.warn('Wait BungeeCord start ready to get netty channel pipeline. Err: ' + ex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}).later(10).timer(20).submit()
|
||||||
|
}
|
||||||
|
|
||||||
getPlayer(name: string) {
|
getPlayer(name: string) {
|
||||||
return Bungee.getPlayer(name);
|
return Bungee.getPlayer(name);
|
||||||
}
|
}
|
||||||
@@ -29,6 +61,15 @@ export class BungeeServer implements server.Server {
|
|||||||
dispatchConsoleCommand(command: string): boolean {
|
dispatchConsoleCommand(command: string): boolean {
|
||||||
return Bungee.getPluginManager().dispatchCommand(Bungee.getConsole(), command)
|
return Bungee.getPluginManager().dispatchCommand(Bungee.getConsole(), command)
|
||||||
}
|
}
|
||||||
|
getPluginsFolder(): string {
|
||||||
|
return this.pluginsFolder;
|
||||||
|
}
|
||||||
|
getNativePluginManager() {
|
||||||
|
return Bungee.getPluginManager() as any
|
||||||
|
}
|
||||||
|
getNettyPipeline() {
|
||||||
|
return this.pipeline;
|
||||||
|
}
|
||||||
sendJson(sender: string | any, json: string): void {
|
sendJson(sender: string | any, json: string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,9 @@ export class BungeeTaskManager implements task.TaskManager {
|
|||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return func();
|
return func();
|
||||||
}
|
}
|
||||||
|
disable() {
|
||||||
|
this.pluginInstance.getProxy().getScheduler().cancel(this.pluginInstance)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class BungeeTask extends task.Task {
|
export class BungeeTask extends task.Task {
|
||||||
@@ -25,9 +28,9 @@ export class BungeeTask extends task.Task {
|
|||||||
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
return this.plugin.getProxy().getScheduler().runAsync(this.plugin, run)
|
||||||
}
|
}
|
||||||
if (this.interval) {
|
if (this.interval) {
|
||||||
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime, this.interval, TimeUnit.MILLISECONDS)
|
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, this.interval * 50, TimeUnit.MILLISECONDS)
|
||||||
} else {
|
} else {
|
||||||
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime, TimeUnit.MILLISECONDS)
|
return this.plugin.getProxy().getScheduler().schedule(this.plugin, run, this.laterTime * 50, TimeUnit.MILLISECONDS)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
"private": true,
|
||||||
"name": "@ms/client",
|
"name": "@ms/client",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript client package",
|
"description": "MiaoScript client package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -28,8 +28,7 @@
|
|||||||
"minecraft-protocol": "^1.11.0"
|
"minecraft-protocol": "^1.11.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@nestjs/cli": "^6.14.2",
|
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,12 @@ import { attachForge } from './forge'
|
|||||||
import { attachEvents } from './event'
|
import { attachEvents } from './event'
|
||||||
|
|
||||||
let username = process.argv[2] || 'Mr_jtb'
|
let username = process.argv[2] || 'Mr_jtb'
|
||||||
|
let version = process.argv[3] || '1.12.2'
|
||||||
let client = createConnection('192.168.2.5', 25577, username)
|
let client = createConnection('192.168.2.5', 25577, username)
|
||||||
|
|
||||||
function createConnection(host: string, port: number, username: string) {
|
function createConnection(host: string, port: number, username: string) {
|
||||||
let client = createClient({
|
let client = createClient({
|
||||||
version: '1.12.2',
|
version,
|
||||||
host,
|
host,
|
||||||
port,
|
port,
|
||||||
username,
|
username,
|
||||||
@@ -21,6 +22,10 @@ function createConnection(host: string, port: number, username: string) {
|
|||||||
return client;
|
return client;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
client.on('error', (error) => {
|
||||||
|
console.log("Client Error", error)
|
||||||
|
})
|
||||||
|
|
||||||
client.on('end', (resone) => {
|
client.on('end', (resone) => {
|
||||||
console.log("Client End Resone:", resone)
|
console.log("Client End Resone:", resone)
|
||||||
client = createConnection('192.168.2.5', 25577, username)
|
client = createConnection('192.168.2.5', 25577, username)
|
||||||
@@ -29,19 +34,31 @@ client.on('end', (resone) => {
|
|||||||
const rl = createInterface({
|
const rl = createInterface({
|
||||||
input: process.stdin,
|
input: process.stdin,
|
||||||
output: process.stdout,
|
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,
|
terminal: true,
|
||||||
prompt: ''
|
prompt: ''
|
||||||
})
|
})
|
||||||
|
|
||||||
rl.on('line', function(line) {
|
rl.on('line', function (line) {
|
||||||
switch (line) {
|
switch (line) {
|
||||||
case "":
|
case "":
|
||||||
break;
|
break;
|
||||||
|
case "eval":
|
||||||
|
break;
|
||||||
|
case "write":
|
||||||
|
break;
|
||||||
case "/respawn":
|
case "/respawn":
|
||||||
client.write('client_command', { payload: 0 })
|
client.write('client_command', { payload: 0 })
|
||||||
// client.write("respawn", {
|
|
||||||
|
|
||||||
// })
|
|
||||||
break;
|
break;
|
||||||
case "//reco":
|
case "//reco":
|
||||||
client.end("")
|
client.end("")
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/common",
|
"name": "@ms/common",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -24,11 +24,10 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/nashorn": "^0.3.0",
|
"@ms/nashorn": "^0.5.0"
|
||||||
"@ms/ployfill": "^0.3.0"
|
|
||||||
},
|
},
|
||||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 =
|
export type Method =
|
||||||
| 'get' | 'GET'
|
| 'get' | 'GET'
|
||||||
@@ -31,8 +34,14 @@ function request(config: RequestConfig) {
|
|||||||
return xhr.get();
|
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) {
|
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 });
|
return request({ url, method, data, ...config });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -40,5 +49,6 @@ function _proxy(method: Method) {
|
|||||||
export default {
|
export default {
|
||||||
get: _proxy('GET'),
|
get: _proxy('GET'),
|
||||||
post: _proxy('POST'),
|
post: _proxy('POST'),
|
||||||
request
|
request,
|
||||||
|
download
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import '@ms/core'
|
|
||||||
/**
|
/**
|
||||||
* 反射工具类
|
* 反射工具类
|
||||||
* Created by MiaoWoo on 2017/2/9 0009.
|
* Created by MiaoWoo on 2017/2/9 0009.
|
||||||
@@ -199,4 +198,4 @@ export = {
|
|||||||
accessible,
|
accessible,
|
||||||
declaredMethods,
|
declaredMethods,
|
||||||
mapToObject
|
mapToObject
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/compile",
|
"name": "@ms/compile",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript compile package",
|
"description": "MiaoScript compile package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -24,6 +24,6 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/container",
|
"name": "@ms/container",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript container package",
|
"description": "MiaoScript container package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -24,9 +24,10 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"inversify": "^5.0.1",
|
||||||
"inversify-binding-decorators": "^4.0.0"
|
"inversify-binding-decorators": "^4.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/core",
|
"name": "@ms/core",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -24,15 +24,11 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/api": "^0.3.0",
|
"@ms/api": "^0.5.0",
|
||||||
"@ms/bukkit": "^0.3.0",
|
"@ms/container": "^0.5.0"
|
||||||
"@ms/common": "^0.3.0",
|
|
||||||
"@ms/container": "^0.3.0",
|
|
||||||
"@ms/plugin": "^0.3.0",
|
|
||||||
"@ms/sponge": "^0.3.0"
|
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
/// <reference types="@ms/nashorn" />
|
|
||||||
import '@ms/i18n'
|
|
||||||
|
|
||||||
let containerStartTime = Date.now();
|
let containerStartTime = Date.now();
|
||||||
console.i18n("ms.core.ioc.initialize");
|
console.i18n("ms.core.ioc.initialize");
|
||||||
import { plugin, server, task } from '@ms/api'
|
import { plugin, server, task, constants } from '@ms/api'
|
||||||
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule } from '@ms/container'
|
import { DefaultContainer as container, inject, provideSingleton, ContainerInstance, buildProviderModule } from '@ms/container'
|
||||||
console.i18n("ms.core.ioc.completed", { time: (Date.now() - containerStartTime) / 1000 })
|
console.i18n("ms.core.ioc.completed", { time: (Date.now() - containerStartTime) / 1000 })
|
||||||
|
|
||||||
@@ -27,15 +24,13 @@ class MiaoScriptCore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
loadServerConsole() {
|
loadServerConsole() {
|
||||||
// @ts-ignore
|
//@ts-ignore
|
||||||
console = new this.Console();
|
global.setGlobal('console', new this.Console())
|
||||||
}
|
}
|
||||||
|
|
||||||
loadTaskFunction() {
|
loadTaskFunction() {
|
||||||
//@ts-ignore
|
global.setGlobal('setTimeout', (func: Function, tick: number, async: boolean = false) => this.taskManager.create(func).later(tick).async(async).submit())
|
||||||
global.setTimeout = (func: Function, tick: number, async: boolean = false) => this.taskManager.create(func).later(tick).async(async).submit()
|
global.setGlobal('setInterval', (func: Function, tick: number, async: boolean = false) => this.taskManager.create(func).timer(tick).async(async).submit())
|
||||||
//@ts-ignore
|
|
||||||
global.setInterval = (func: Function, tick: number, async: boolean = false) => this.taskManager.create(func).timer(tick).async(async).submit()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
loadPlugins() {
|
loadPlugins() {
|
||||||
@@ -51,34 +46,38 @@ class MiaoScriptCore {
|
|||||||
disable() {
|
disable() {
|
||||||
console.i18n("ms.core.engine.disable")
|
console.i18n("ms.core.engine.disable")
|
||||||
this.pluginManager.disable();
|
this.pluginManager.disable();
|
||||||
|
this.taskManager.disable();
|
||||||
|
//@ts-ignore
|
||||||
|
require.disable()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function detectServer() {
|
function detectServer(): constants.ServerType {
|
||||||
try {
|
try {
|
||||||
Java.type("org.bukkit.Bukkit");
|
Java.type("org.bukkit.Bukkit");
|
||||||
return 'bukkit'
|
return constants.ServerType.Bukkit
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Java.type("org.spongepowered.api.Sponge");
|
Java.type("org.spongepowered.api.Sponge");
|
||||||
return 'sponge'
|
return constants.ServerType.Sponge
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Java.type("cn.nukkit.Nukkit");
|
Java.type("cn.nukkit.Nukkit");
|
||||||
return 'nukkit'
|
return constants.ServerType.Nukkit
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Java.type("net.md_5.bungee.api.ProxyServer");
|
Java.type("net.md_5.bungee.api.ProxyServer");
|
||||||
return 'bungee'
|
return constants.ServerType.Bungee
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
}
|
}
|
||||||
throw Error('Unknow Server Type...')
|
throw Error('Unknow Server Type...')
|
||||||
}
|
}
|
||||||
|
|
||||||
function initialize() {
|
function initialize() {
|
||||||
|
try {
|
||||||
let corePackageStartTime = new Date().getTime()
|
let corePackageStartTime = new Date().getTime()
|
||||||
container.bind(ContainerInstance).toConstantValue(container);
|
container.bind(ContainerInstance).toConstantValue(container);
|
||||||
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance());
|
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance());
|
||||||
@@ -94,6 +93,11 @@ function initialize() {
|
|||||||
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
||||||
console.i18n("ms.core.engine.completed", { time: (Date.now() - global.NashornEngineStartTime) / 1000 });
|
console.i18n("ms.core.engine.completed", { time: (Date.now() - global.NashornEngineStartTime) / 1000 });
|
||||||
return disable;
|
return disable;
|
||||||
|
} catch (error) {
|
||||||
|
console.i18n("ms.core.initialize.error", { error });
|
||||||
|
console.ex(error)
|
||||||
|
return () => console.i18n('ms.core.engine.disable.abnormal')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default initialize();
|
export default initialize();
|
||||||
|
|||||||
@@ -4,12 +4,14 @@ 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.initialize: "Initialization MiaoScript IOC Container @ms/container. Please wait..."
|
||||||
ms.core.ioc.completed: "MiaoScript IOC Container @ms/container loading completed({time}s)!"
|
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.initialize.detect: "Detect Compatible Server set ServerType to {type} ..."
|
||||||
|
ms.core.initialize.error: "MiaoScript Engine Initialization Error: {error} ..."
|
||||||
ms.core.package.initialize: "Initialization MiaoScript Package @ms/core @ms/{type} @ms/plugin. Please wait..."
|
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.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.initialize: "Initialization MiaoScript Plugin System. Please wait..."
|
||||||
ms.core.plugin.completed: "MiaoScript Plugin System loading completed({time}s)!"
|
ms.core.plugin.completed: "MiaoScript Plugin System loading completed({time}s)!"
|
||||||
ms.core.engine.completed: "MiaoScript ScriptEngine loading completed... Done({time}s)!"
|
ms.core.engine.completed: "MiaoScript ScriptEngine loading completed... Done({time}s)!"
|
||||||
ms.core.engine.disable: "Disable MiaoScript Engine..."
|
ms.core.engine.disable: "Disable MiaoScript Engine..."
|
||||||
|
ms.core.engine.disable.abnormal: "abnormal Initialization MiaoScript Engine. Skip disable step..."
|
||||||
|
|
||||||
ms.api.event.resource.not.found: "Can't Mapping Event Because not found Resources {resource}!"
|
ms.api.event.resource.not.found: "Can't Mapping Event Because not found Resources {resource}!"
|
||||||
ms.api.event.empty.event.dir: "base event dir is empty, can't map event name !"
|
ms.api.event.empty.event.dir: "base event dir is empty, can't map event name !"
|
||||||
@@ -23,12 +25,16 @@ ms.api.event.unregister: "[{name}] unregister event {event}"
|
|||||||
ms.api.command.register.input.error: "CommandExec Must be a function... Input: {exec}"
|
ms.api.command.register.input.error: "CommandExec Must be a function... Input: {exec}"
|
||||||
ms.api.command.register: "[{plugin}] register command {name}({cmd})..."
|
ms.api.command.register: "[{plugin}] register command {name}({cmd})..."
|
||||||
ms.api.command.unregister: "[{plugin}] unregister command {name}..."
|
ms.api.command.unregister: "[{plugin}] unregister command {name}..."
|
||||||
|
ms.api.command.execute.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.initialize: "Initialization MiaoScript Plugin System: Plugin: {plugin} Loader: {loader}..."
|
||||||
ms.plugin.event.map: "Total {count} {type} Event Mapping Complate..."
|
ms.plugin.event.map: "Total {count} {type} Event Mapping Complate..."
|
||||||
ms.plugin.manager.scan: "Scanning Plugins in {folder} ..."
|
ms.plugin.manager.scan: "Scanning Plugins in {folder} ..."
|
||||||
ms.plugin.manager.initialize.error: "§6Plugin §b{name} §6initialize error §4{ex}"
|
ms.plugin.manager.initialize.error: "§6Plugin §b{name} §6initialize error §4{ex}"
|
||||||
ms.plugin.manager.stage: "{stage} {plugin} version {version} by {author}"
|
ms.plugin.manager.stage: "{stage} {plugin} version {version} by {author}"
|
||||||
|
ms.plugin.manager.stage.exec: "[{plugin}] Exec {name} Stage {stage} When servers is {servers}..."
|
||||||
|
ms.plugin.manager.stage.exec.error: "§6Plugin §b{plugin} §6exec §d{executor} §6function error §4{error}"
|
||||||
ms.plugin.manager.stage.load: "Loading"
|
ms.plugin.manager.stage.load: "Loading"
|
||||||
ms.plugin.manager.stage.enable: "Enabling"
|
ms.plugin.manager.stage.enable: "Enabling"
|
||||||
ms.plugin.manager.stage.disable: "Disabling"
|
ms.plugin.manager.stage.disable: "Disabling"
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
ms.ployfill.initialize: "初始化 Java Nashorn 补丁. 请稍候..."
|
ms.ployfill.initialize: "加载 Java Nashorn 补丁. 请稍候..."
|
||||||
ms.ployfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
|
ms.ployfill.completed: "Java Nashorn 补丁 加载完成... 耗时 ({time}s)!"
|
||||||
|
|
||||||
ms.core.ioc.initialize: "初始化 MiaoScript IOC 容器 @ms/container. 请稍候..."
|
ms.core.ioc.initialize: "初始化 MiaoScript IOC 容器 @ms/container. 请稍候..."
|
||||||
ms.core.ioc.completed: "MiaoScript IOC 容器 @ms/container 加载完成 耗时({time}s)"
|
ms.core.ioc.completed: "MiaoScript IOC 容器 @ms/container 加载完成 耗时({time}s)"
|
||||||
ms.core.initialize.detect: "检测到兼容的服务器类型. 设置 ServerType 值 {type} ..."
|
ms.core.initialize.detect: "检测到兼容的服务器类型. 设置 ServerType 值 {type} ..."
|
||||||
|
ms.core.initialize.error: "§4MiaoScript 系统初始化失败 §c{error} ..."
|
||||||
ms.core.package.initialize: "初始化 MiaoScript 扩展 @ms/core @ms/{type} @ms/plugin. 请稍候..."
|
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.package.completed: "MiaoScript 扩展 @ms/core @ms/{type} @ms/plugin 加载完成 耗时({time}s)"
|
||||||
ms.core.plugin.initialize: "MiaoScript 开始引导插件系统. 请稍候..."
|
ms.core.plugin.initialize: "MiaoScript 开始引导插件系统. 请稍候..."
|
||||||
ms.core.plugin.completed: "MiaoScript 插件加载完毕 耗时({time}s)!"
|
ms.core.plugin.completed: "MiaoScript 插件加载完毕 耗时({time}s)!"
|
||||||
ms.core.engine.completed: "MiaoScript 脚本引擎 加载完毕... 耗时({time}s)!"
|
ms.core.engine.completed: "MiaoScript 脚本引擎 加载完毕... 耗时({time}s)!"
|
||||||
ms.core.engine.disable: "关闭 MiaoScript 引擎..."
|
ms.core.engine.disable: "关闭 MiaoScript 引擎..."
|
||||||
|
ms.core.engine.disable.abnormal: "引擎异常启动或初始化未完成 跳过关闭流程..."
|
||||||
|
|
||||||
ms.api.event.resource.not.found: "无法映射事件 未找到资源文件 {resource}!"
|
ms.api.event.resource.not.found: "无法映射事件 未找到资源文件 {resource}!"
|
||||||
ms.api.event.empty.event.dir: "事件基础目录为空, 无法映射事件!"
|
ms.api.event.empty.event.dir: "事件基础目录为空, 无法映射事件!"
|
||||||
@@ -23,12 +25,16 @@ ms.api.event.unregister: "[{name}] 注销事件 {event}"
|
|||||||
ms.api.command.register.input.error: "CommandExec 必须为一个函数... 输入: {exec}"
|
ms.api.command.register.input.error: "CommandExec 必须为一个函数... 输入: {exec}"
|
||||||
ms.api.command.register: "[{plugin}] 注册命令 {name}({cmd})..."
|
ms.api.command.register: "[{plugin}] 注册命令 {name}({cmd})..."
|
||||||
ms.api.command.unregister: "[{plugin}] 注销命令 {name}..."
|
ms.api.command.unregister: "[{plugin}] 注销命令 {name}..."
|
||||||
|
ms.api.command.execute.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.initialize: "初始化 MiaoScript 插件系统: 实例: {plugin} 加载器: {loader}..."
|
||||||
ms.plugin.event.map: "总计 {count} 个 {type} 事件 映射完成..."
|
ms.plugin.event.map: "总计 {count} 个 {type} 事件 映射完成..."
|
||||||
ms.plugin.manager.scan: "在 {folder} 文件夹中扫描插件..."
|
ms.plugin.manager.scan: "扫描 {folder} 文件夹中插件..."
|
||||||
ms.plugin.manager.initialize.error: "§6插件 §b{name} §6初始化错误 §4{ex}"
|
ms.plugin.manager.initialize.error: "§6插件 §b{name} §6初始化错误 §4{ex}"
|
||||||
ms.plugin.manager.stage: "{stage} {plugin} 版本 {version} 作者 {author}"
|
ms.plugin.manager.stage: "{stage} {plugin} 版本 {version} 作者 {author}"
|
||||||
|
ms.plugin.manager.stage.exec: "[{plugin}] 执行 {stage} 阶段函数 {name} 匹配类型 {servers}..."
|
||||||
|
ms.plugin.manager.stage.exec.error: "§6插件 §b{plugin} §6执行 §d{executor} §6函数发生异常 错误: §4{error}"
|
||||||
ms.plugin.manager.stage.load: "加载"
|
ms.plugin.manager.stage.load: "加载"
|
||||||
ms.plugin.manager.stage.enable: "启用"
|
ms.plugin.manager.stage.enable: "启用"
|
||||||
ms.plugin.manager.stage.disable: "关闭"
|
ms.plugin.manager.stage.disable: "关闭"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/i18n",
|
"name": "@ms/i18n",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript i18n package",
|
"description": "MiaoScript i18n package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,15 +22,13 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/js-yaml": "^3.12.2",
|
"@types/js-yaml": "^3.12.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/common": "^0.3.0",
|
"@ms/nashorn": "^0.5.0",
|
||||||
"@ms/container": "^0.3.0",
|
|
||||||
"@ms/ployfill": "^0.3.0",
|
|
||||||
"js-yaml": "^3.13.1"
|
"js-yaml": "^3.13.1"
|
||||||
},
|
},
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
|
|||||||
@@ -1,42 +1,69 @@
|
|||||||
import '@ms/ployfill'
|
/// <reference types="@ms/nashorn" />
|
||||||
import * as yaml from 'js-yaml'
|
import * as yaml from 'js-yaml'
|
||||||
|
|
||||||
import * as fs from '@ms/common/dist/fs'
|
const File = Java.type("java.io.File");
|
||||||
|
const separatorChar = File.separatorChar;
|
||||||
let langMap = {};
|
|
||||||
let fallbackMap = {};
|
|
||||||
|
|
||||||
type TranslateParam = { [key: string]: any }
|
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(fs.concat(__dirname, '..'), lang)
|
|
||||||
fallbackMap = readYamlFile(root, fallback) || readYamlFile(fs.concat(__dirname, '..'), fallback)
|
|
||||||
console.i18n = function i18n(name: string, param?: TranslateParam) {
|
|
||||||
console.log(translate(name, param))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function readYamlFile(dir: string, name: string) {
|
|
||||||
let langFile = fs.concat(dir, 'languages', name + '.yml');
|
|
||||||
return fs.exists(langFile) && yaml.safeLoad(base.read(langFile))
|
|
||||||
}
|
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
interface Console {
|
interface Console {
|
||||||
i18n(name: string, param?: TranslateParam);
|
i18n(name: string, param?: TranslateParam);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type TranslateContent = {
|
||||||
|
langMap: TranslateParam,
|
||||||
|
fallbackMap?: TranslateParam
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Translate {
|
||||||
|
private root = '';
|
||||||
|
private langMap = {};
|
||||||
|
private fallbackMap = {};
|
||||||
|
|
||||||
|
constructor(root: string | TranslateContent) {
|
||||||
|
if (typeof root == 'string') {
|
||||||
|
this.root = root;
|
||||||
|
} else {
|
||||||
|
this.langMap = root.langMap;
|
||||||
|
this.fallbackMap = root.fallbackMap || {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
translate(name: string, param?: TranslateParam) {
|
||||||
|
let langText: string = this.langMap[name] || this.fallbackMap[name];
|
||||||
|
if (!langText) { return '[WARN] @ms/i18n miss lang translate: ' + name }
|
||||||
|
for (const key in param) {
|
||||||
|
langText = langText.replace("{" + key + "}", param[key])
|
||||||
|
}
|
||||||
|
return langText;
|
||||||
|
}
|
||||||
|
|
||||||
|
initialize(lang: string = 'zh_cn', fallback: string = 'zh_cn') {
|
||||||
|
this.langMap = this.readYamlFile(this.root, lang) || this.readYamlFile(this.concat(__dirname, '..'), lang)
|
||||||
|
this.fallbackMap = this.readYamlFile(this.root, fallback) || this.readYamlFile(this.concat(__dirname, '..'), fallback)
|
||||||
|
console.i18n = (name: string, param?: TranslateParam) => {
|
||||||
|
console.log(this.translate(name, param))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
readYamlFile(dir: string, name: string) {
|
||||||
|
let langFile = this.concat(dir, 'languages', name + '.yml');
|
||||||
|
return this.exists(langFile) && yaml.safeLoad(base.read(langFile))
|
||||||
|
}
|
||||||
|
|
||||||
|
concat(...args: string[]) {
|
||||||
|
return args.join(separatorChar)
|
||||||
|
}
|
||||||
|
|
||||||
|
exists(path: string) {
|
||||||
|
return new File(path).exists()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let systemTranslate = new Translate(root)
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
initialize,
|
initialize: systemTranslate.initialize.bind(systemTranslate),
|
||||||
translate
|
translate: systemTranslate.translate.bind(systemTranslate)
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -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);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -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()
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/nashorn",
|
"name": "@ms/nashorn",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -25,6 +25,6 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,6 +38,37 @@ declare global {
|
|||||||
setPrototypeOf(obj: object, prototype: object);
|
setPrototypeOf(obj: object, prototype: object);
|
||||||
bindProperties(to: object, from: 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 { };
|
export { };
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
"name": "@ms/nodejs",
|
||||||
"name": "@ms/manager",
|
"version": "0.5.0",
|
||||||
"version": "0.3.0",
|
"description": "MiaoScript nodejs package",
|
||||||
"description": "MiaoScript manager package",
|
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
"minecraft",
|
"minecraft",
|
||||||
@@ -17,23 +16,18 @@
|
|||||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "ts-node-dev --respawn --debounce=1500 src/index.ts",
|
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"watch": "tsc --watch",
|
"watch": "tsc --watch",
|
||||||
"build": "yarn clean && tsc",
|
"build": "yarn clean && tsc",
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
|
||||||
"@cc-server/core": "^0.7.0",
|
|
||||||
"mongodb": "^3.5.3"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/express": "^4.17.2",
|
|
||||||
"@types/mongodb": "^3.3.16",
|
|
||||||
"@types/socket.io": "^2.1.4",
|
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"ts-node-dev": "^1.0.0-pre.44",
|
"typescript": "^3.8.3"
|
||||||
"typescript": "^3.8.2"
|
},
|
||||||
}
|
"dependencies": {
|
||||||
|
"@ms/nashorn": "^0.5.0"
|
||||||
|
},
|
||||||
|
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||||
}
|
}
|
||||||
455
packages/nodejs/src/events/index.ts
Normal file
455
packages/nodejs/src/events/index.ts
Normal 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;
|
||||||
|
}
|
||||||
101
packages/nodejs/src/fs/index.ts
Normal file
101
packages/nodejs/src/fs/index.ts
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
import '@ms/nashorn'
|
||||||
|
import { URL } from "url";
|
||||||
|
|
||||||
|
const Path = Java.type("java.nio.file.Path");
|
||||||
|
const JavaString = Java.type("java.lang.String");
|
||||||
|
const File = Java.type("java.io.File");
|
||||||
|
const Files = Java.type("java.nio.file.Files");
|
||||||
|
const Collector = Java.type("java.util.stream.Collector")
|
||||||
|
const separatorChar = File.separatorChar;
|
||||||
|
const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valid types for path values in "fs".
|
||||||
|
*/
|
||||||
|
type PathLike = string | Buffer | URL;
|
||||||
|
|
||||||
|
function javaFile(...opts: any[]) {
|
||||||
|
if (!opts[0]) {
|
||||||
|
console.warn("文件名称不得为 undefined 或者 null !");
|
||||||
|
}
|
||||||
|
switch (opts.length) {
|
||||||
|
case 1:
|
||||||
|
var f = opts[0];
|
||||||
|
if (f instanceof File) {
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
if (typeof f === "string") {
|
||||||
|
return new File(f);
|
||||||
|
}
|
||||||
|
if (f instanceof Path) {
|
||||||
|
return f.toFile();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return new File(javaFile(opts[0]), opts[1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renameSync(oldPath: PathLike, newPath: PathLike): void {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function truncateSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function chownSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function chmodSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function statSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function symlinkSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function readlinkSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function realpathSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function unlinkSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function rmdirSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function mkdirSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function mkdtempSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function readdirSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function readFileSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function writeFileSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function appendFileSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function watchFile() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function unwatchFile() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function existsSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function accessSync() {
|
||||||
|
|
||||||
|
}
|
||||||
|
export function copyFileSync() {
|
||||||
|
|
||||||
|
}
|
||||||
1
packages/nodejs/src/index.ts
Normal file
1
packages/nodejs/src/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export { }
|
||||||
626
packages/nodejs/src/path/index.ts
Normal file
626
packages/nodejs/src/path/index.ts
Normal file
@@ -0,0 +1,626 @@
|
|||||||
|
// 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';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
var isWindows = java.lang.System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1;
|
||||||
|
// @ts-ignore
|
||||||
|
var util = require('util');
|
||||||
|
|
||||||
|
// resolves . and .. elements in a path array with directory names there
|
||||||
|
// must be no slashes or device names (c:\) in the array
|
||||||
|
// (so also no leading and trailing slashes - it does not distinguish
|
||||||
|
// relative and absolute paths)
|
||||||
|
function normalizeArray(parts, allowAboveRoot) {
|
||||||
|
var res = [];
|
||||||
|
for (var i = 0; i < parts.length; i++) {
|
||||||
|
var p = parts[i];
|
||||||
|
|
||||||
|
// ignore empty parts
|
||||||
|
if (!p || p === '.')
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (p === '..') {
|
||||||
|
if (res.length && res[res.length - 1] !== '..') {
|
||||||
|
res.pop();
|
||||||
|
} else if (allowAboveRoot) {
|
||||||
|
res.push('..');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
res.push(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
// returns an array with empty elements removed from either end of the input
|
||||||
|
// array or the original array if no elements need to be removed
|
||||||
|
function trimArray(arr) {
|
||||||
|
var lastIndex = arr.length - 1;
|
||||||
|
var start = 0;
|
||||||
|
for (; start <= lastIndex; start++) {
|
||||||
|
if (arr[start])
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
var end = lastIndex;
|
||||||
|
for (; end >= 0; end--) {
|
||||||
|
if (arr[end])
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start === 0 && end === lastIndex)
|
||||||
|
return arr;
|
||||||
|
if (start > end)
|
||||||
|
return [];
|
||||||
|
return arr.slice(start, end + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Regex to split a windows path into three parts: [*, device, slash,
|
||||||
|
// tail] windows-only
|
||||||
|
var splitDeviceRe =
|
||||||
|
/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
|
||||||
|
|
||||||
|
// Regex to split the tail part of the above into [*, dir, basename, ext]
|
||||||
|
var splitTailRe =
|
||||||
|
/^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
|
||||||
|
|
||||||
|
var win32: any = {};
|
||||||
|
|
||||||
|
// Function to split a filename into [root, dir, basename, ext]
|
||||||
|
function win32SplitPath(filename) {
|
||||||
|
// Separate device+slash from tail
|
||||||
|
var result = splitDeviceRe.exec(filename),
|
||||||
|
device = (result[1] || '') + (result[2] || ''),
|
||||||
|
tail = result[3] || '';
|
||||||
|
// Split the tail into dir, basename and extension
|
||||||
|
var result2 = splitTailRe.exec(tail),
|
||||||
|
dir = result2[1],
|
||||||
|
basename = result2[2],
|
||||||
|
ext = result2[3];
|
||||||
|
return [device, dir, basename, ext];
|
||||||
|
}
|
||||||
|
|
||||||
|
function win32StatPath(path) {
|
||||||
|
var result = splitDeviceRe.exec(path),
|
||||||
|
device = result[1] || '',
|
||||||
|
isUnc = !!device && device[1] !== ':';
|
||||||
|
return {
|
||||||
|
device: device,
|
||||||
|
isUnc: isUnc,
|
||||||
|
isAbsolute: isUnc || !!result[2], // UNC paths are always absolute
|
||||||
|
tail: result[3]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeUNCRoot(device) {
|
||||||
|
return '\\\\' + device.replace(/^[\\\/]+/, '').replace(/[\\\/]+/g, '\\');
|
||||||
|
}
|
||||||
|
|
||||||
|
// path.resolve([from ...], to)
|
||||||
|
win32.resolve = function () {
|
||||||
|
var resolvedDevice = '',
|
||||||
|
resolvedTail = '',
|
||||||
|
resolvedAbsolute = false;
|
||||||
|
|
||||||
|
for (var i = arguments.length - 1; i >= -1; i--) {
|
||||||
|
var path;
|
||||||
|
if (i >= 0) {
|
||||||
|
path = arguments[i];
|
||||||
|
} else if (!resolvedDevice) {
|
||||||
|
path = process.cwd();
|
||||||
|
} else {
|
||||||
|
// Windows has the concept of drive-specific current working
|
||||||
|
// directories. If we've resolved a drive letter but not yet an
|
||||||
|
// absolute path, get cwd for that drive. We're sure the device is not
|
||||||
|
// an unc path at this points, because unc paths are always absolute.
|
||||||
|
path = process.env['=' + resolvedDevice];
|
||||||
|
// Verify that a drive-local cwd was found and that it actually points
|
||||||
|
// to our drive. If not, default to the drive's root.
|
||||||
|
if (!path || path.substr(0, 3).toLowerCase() !==
|
||||||
|
resolvedDevice.toLowerCase() + '\\') {
|
||||||
|
path = resolvedDevice + '\\';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip empty and invalid entries
|
||||||
|
if (!util.isString(path)) {
|
||||||
|
throw new TypeError('Arguments to path.resolve must be strings');
|
||||||
|
} else if (!path) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = win32StatPath(path),
|
||||||
|
device = result.device,
|
||||||
|
isUnc = result.isUnc,
|
||||||
|
isAbsolute = result.isAbsolute,
|
||||||
|
tail = result.tail;
|
||||||
|
|
||||||
|
if (device &&
|
||||||
|
resolvedDevice &&
|
||||||
|
device.toLowerCase() !== resolvedDevice.toLowerCase()) {
|
||||||
|
// This path points to another device so it is not applicable
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!resolvedDevice) {
|
||||||
|
resolvedDevice = device;
|
||||||
|
}
|
||||||
|
if (!resolvedAbsolute) {
|
||||||
|
resolvedTail = tail + '\\' + resolvedTail;
|
||||||
|
resolvedAbsolute = isAbsolute;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resolvedDevice && resolvedAbsolute) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert slashes to backslashes when `resolvedDevice` points to an UNC
|
||||||
|
// root. Also squash multiple slashes into a single one where appropriate.
|
||||||
|
if (isUnc) {
|
||||||
|
resolvedDevice = normalizeUNCRoot(resolvedDevice);
|
||||||
|
}
|
||||||
|
|
||||||
|
// At this point the path should be resolved to a full absolute path,
|
||||||
|
// but handle relative paths to be safe (might happen when process.cwd()
|
||||||
|
// fails)
|
||||||
|
|
||||||
|
// Normalize the tail path
|
||||||
|
resolvedTail = normalizeArray(resolvedTail.split(/[\\\/]+/),
|
||||||
|
!resolvedAbsolute).join('\\');
|
||||||
|
|
||||||
|
return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) ||
|
||||||
|
'.';
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
win32.normalize = function (path) {
|
||||||
|
var result = win32StatPath(path),
|
||||||
|
device = result.device,
|
||||||
|
isUnc = result.isUnc,
|
||||||
|
isAbsolute = result.isAbsolute,
|
||||||
|
tail = result.tail,
|
||||||
|
trailingSlash = /[\\\/]$/.test(tail);
|
||||||
|
|
||||||
|
// Normalize the tail path
|
||||||
|
tail = normalizeArray(tail.split(/[\\\/]+/), !isAbsolute).join('\\');
|
||||||
|
|
||||||
|
if (!tail && !isAbsolute) {
|
||||||
|
tail = '.';
|
||||||
|
}
|
||||||
|
if (tail && trailingSlash) {
|
||||||
|
tail += '\\';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert slashes to backslashes when `device` points to an UNC root.
|
||||||
|
// Also squash multiple slashes into a single one where appropriate.
|
||||||
|
if (isUnc) {
|
||||||
|
device = normalizeUNCRoot(device);
|
||||||
|
}
|
||||||
|
|
||||||
|
return device + (isAbsolute ? '\\' : '') + tail;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
win32.isAbsolute = function (path) {
|
||||||
|
return win32StatPath(path).isAbsolute;
|
||||||
|
};
|
||||||
|
|
||||||
|
win32.join = function () {
|
||||||
|
var paths = [];
|
||||||
|
for (var i = 0; i < arguments.length; i++) {
|
||||||
|
var arg = arguments[i];
|
||||||
|
if (!util.isString(arg)) {
|
||||||
|
throw new TypeError('Arguments to path.join must be strings');
|
||||||
|
}
|
||||||
|
if (arg) {
|
||||||
|
paths.push(arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var joined = paths.join('\\');
|
||||||
|
|
||||||
|
// Make sure that the joined path doesn't start with two slashes, because
|
||||||
|
// normalize() will mistake it for an UNC path then.
|
||||||
|
//
|
||||||
|
// This step is skipped when it is very clear that the user actually
|
||||||
|
// intended to point at an UNC path. This is assumed when the first
|
||||||
|
// non-empty string arguments starts with exactly two slashes followed by
|
||||||
|
// at least one more non-slash character.
|
||||||
|
//
|
||||||
|
// Note that for normalize() to treat a path as an UNC path it needs to
|
||||||
|
// have at least 2 components, so we don't filter for that here.
|
||||||
|
// This means that the user can use join to construct UNC paths from
|
||||||
|
// a server name and a share name; for example:
|
||||||
|
// path.join('//server', 'share') -> '\\\\server\\share\')
|
||||||
|
if (!/^[\\\/]{2}[^\\\/]/.test(paths[0])) {
|
||||||
|
joined = joined.replace(/^[\\\/]{2,}/, '\\');
|
||||||
|
}
|
||||||
|
|
||||||
|
return win32.normalize(joined);
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
// path.relative(from, to)
|
||||||
|
// it will solve the relative path from 'from' to 'to', for instance:
|
||||||
|
// from = 'C:\\orandea\\test\\aaa'
|
||||||
|
// to = 'C:\\orandea\\impl\\bbb'
|
||||||
|
// The output of the function should be: '..\\..\\impl\\bbb'
|
||||||
|
win32.relative = function (from, to) {
|
||||||
|
from = win32.resolve(from);
|
||||||
|
to = win32.resolve(to);
|
||||||
|
|
||||||
|
// windows is not case sensitive
|
||||||
|
var lowerFrom = from.toLowerCase();
|
||||||
|
var lowerTo = to.toLowerCase();
|
||||||
|
|
||||||
|
var toParts = trimArray(to.split('\\'));
|
||||||
|
|
||||||
|
var lowerFromParts = trimArray(lowerFrom.split('\\'));
|
||||||
|
var lowerToParts = trimArray(lowerTo.split('\\'));
|
||||||
|
|
||||||
|
var length = Math.min(lowerFromParts.length, lowerToParts.length);
|
||||||
|
var samePartsLength = length;
|
||||||
|
for (var i = 0; i < length; i++) {
|
||||||
|
if (lowerFromParts[i] !== lowerToParts[i]) {
|
||||||
|
samePartsLength = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (samePartsLength == 0) {
|
||||||
|
return to;
|
||||||
|
}
|
||||||
|
|
||||||
|
var outputParts = [];
|
||||||
|
for (var i = samePartsLength; i < lowerFromParts.length; i++) {
|
||||||
|
outputParts.push('..');
|
||||||
|
}
|
||||||
|
|
||||||
|
outputParts = outputParts.concat(toParts.slice(samePartsLength));
|
||||||
|
|
||||||
|
return outputParts.join('\\');
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
win32._makeLong = function (path) {
|
||||||
|
// Note: this will *probably* throw somewhere.
|
||||||
|
if (!util.isString(path))
|
||||||
|
return path;
|
||||||
|
|
||||||
|
if (!path) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
var resolvedPath = win32.resolve(path);
|
||||||
|
|
||||||
|
if (/^[a-zA-Z]\:\\/.test(resolvedPath)) {
|
||||||
|
// path is local filesystem path, which needs to be converted
|
||||||
|
// to long UNC path.
|
||||||
|
return '\\\\?\\' + resolvedPath;
|
||||||
|
} else if (/^\\\\[^?.]/.test(resolvedPath)) {
|
||||||
|
// path is network UNC path, which needs to be converted
|
||||||
|
// to long UNC path.
|
||||||
|
return '\\\\?\\UNC\\' + resolvedPath.substring(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
return path;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
win32.dirname = function (path) {
|
||||||
|
var result = win32SplitPath(path),
|
||||||
|
root = result[0],
|
||||||
|
dir = result[1];
|
||||||
|
|
||||||
|
if (!root && !dir) {
|
||||||
|
// No dirname whatsoever
|
||||||
|
return '.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dir) {
|
||||||
|
// It has a dirname, strip trailing slash
|
||||||
|
dir = dir.substr(0, dir.length - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return root + dir;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
win32.basename = function (path, ext) {
|
||||||
|
var f = win32SplitPath(path)[2];
|
||||||
|
// TODO: make this comparison case-insensitive on windows?
|
||||||
|
if (ext && f.substr(-1 * ext.length) === ext) {
|
||||||
|
f = f.substr(0, f.length - ext.length);
|
||||||
|
}
|
||||||
|
return f;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
win32.extname = function (path) {
|
||||||
|
return win32SplitPath(path)[3];
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
win32.format = function (pathObject) {
|
||||||
|
if (!util.isObject(pathObject)) {
|
||||||
|
throw new TypeError(
|
||||||
|
"Parameter 'pathObject' must be an object, not " + typeof pathObject
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
var root = pathObject.root || '';
|
||||||
|
|
||||||
|
if (!util.isString(root)) {
|
||||||
|
throw new TypeError(
|
||||||
|
"'pathObject.root' must be a string or undefined, not " +
|
||||||
|
typeof pathObject.root
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
var dir = pathObject.dir;
|
||||||
|
var base = pathObject.base || '';
|
||||||
|
if (!dir) {
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
if (dir[dir.length - 1] === win32.sep) {
|
||||||
|
return dir + base;
|
||||||
|
}
|
||||||
|
return dir + win32.sep + base;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
win32.parse = function (pathString) {
|
||||||
|
if (!util.isString(pathString)) {
|
||||||
|
throw new TypeError(
|
||||||
|
"Parameter 'pathString' must be a string, not " + typeof pathString
|
||||||
|
);
|
||||||
|
}
|
||||||
|
var allParts = win32SplitPath(pathString);
|
||||||
|
if (!allParts || allParts.length !== 4) {
|
||||||
|
throw new TypeError("Invalid path '" + pathString + "'");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
root: allParts[0],
|
||||||
|
dir: allParts[0] + allParts[1].slice(0, -1),
|
||||||
|
base: allParts[2],
|
||||||
|
ext: allParts[3],
|
||||||
|
name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
win32.sep = '\\';
|
||||||
|
win32.delimiter = ';';
|
||||||
|
|
||||||
|
|
||||||
|
// Split a filename into [root, dir, basename, ext], unix version
|
||||||
|
// 'root' is just a slash, or nothing.
|
||||||
|
var splitPathRe =
|
||||||
|
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
|
||||||
|
var posix: any = {};
|
||||||
|
|
||||||
|
function posixSplitPath(filename) {
|
||||||
|
return splitPathRe.exec(filename).slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// path.resolve([from ...], to)
|
||||||
|
// posix version
|
||||||
|
posix.resolve = function () {
|
||||||
|
var resolvedPath = '',
|
||||||
|
resolvedAbsolute = false;
|
||||||
|
|
||||||
|
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
|
||||||
|
var path = (i >= 0) ? arguments[i] : process.cwd();
|
||||||
|
|
||||||
|
// Skip empty and invalid entries
|
||||||
|
if (!util.isString(path)) {
|
||||||
|
throw new TypeError('Arguments to path.resolve must be strings');
|
||||||
|
} else if (!path) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
resolvedPath = path + '/' + resolvedPath;
|
||||||
|
resolvedAbsolute = path[0] === '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
// At this point the path should be resolved to a full absolute path, but
|
||||||
|
// handle relative paths to be safe (might happen when process.cwd() fails)
|
||||||
|
|
||||||
|
// Normalize the path
|
||||||
|
resolvedPath = normalizeArray(resolvedPath.split('/'),
|
||||||
|
!resolvedAbsolute).join('/');
|
||||||
|
|
||||||
|
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
|
||||||
|
};
|
||||||
|
|
||||||
|
// path.normalize(path)
|
||||||
|
// posix version
|
||||||
|
posix.normalize = function (path) {
|
||||||
|
var isAbsolute = posix.isAbsolute(path),
|
||||||
|
trailingSlash = path && path[path.length - 1] === '/';
|
||||||
|
|
||||||
|
// Normalize the path
|
||||||
|
path = normalizeArray(path.split('/'), !isAbsolute).join('/');
|
||||||
|
|
||||||
|
if (!path && !isAbsolute) {
|
||||||
|
path = '.';
|
||||||
|
}
|
||||||
|
if (path && trailingSlash) {
|
||||||
|
path += '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
return (isAbsolute ? '/' : '') + path;
|
||||||
|
};
|
||||||
|
|
||||||
|
// posix version
|
||||||
|
posix.isAbsolute = function (path) {
|
||||||
|
return path.charAt(0) === '/';
|
||||||
|
};
|
||||||
|
|
||||||
|
// posix version
|
||||||
|
posix.join = function () {
|
||||||
|
var path = '';
|
||||||
|
for (var i = 0; i < arguments.length; i++) {
|
||||||
|
var segment = arguments[i];
|
||||||
|
if (!util.isString(segment)) {
|
||||||
|
throw new TypeError('Arguments to path.join must be strings');
|
||||||
|
}
|
||||||
|
if (segment) {
|
||||||
|
if (!path) {
|
||||||
|
path += segment;
|
||||||
|
} else {
|
||||||
|
path += '/' + segment;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return posix.normalize(path);
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
// path.relative(from, to)
|
||||||
|
// posix version
|
||||||
|
posix.relative = function (from, to) {
|
||||||
|
from = posix.resolve(from).substr(1);
|
||||||
|
to = posix.resolve(to).substr(1);
|
||||||
|
|
||||||
|
var fromParts = trimArray(from.split('/'));
|
||||||
|
var toParts = trimArray(to.split('/'));
|
||||||
|
|
||||||
|
var length = Math.min(fromParts.length, toParts.length);
|
||||||
|
var samePartsLength = length;
|
||||||
|
for (var i = 0; i < length; i++) {
|
||||||
|
if (fromParts[i] !== toParts[i]) {
|
||||||
|
samePartsLength = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var outputParts = [];
|
||||||
|
for (var i = samePartsLength; i < fromParts.length; i++) {
|
||||||
|
outputParts.push('..');
|
||||||
|
}
|
||||||
|
|
||||||
|
outputParts = outputParts.concat(toParts.slice(samePartsLength));
|
||||||
|
|
||||||
|
return outputParts.join('/');
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
posix._makeLong = function (path) {
|
||||||
|
return path;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
posix.dirname = function (path) {
|
||||||
|
var result = posixSplitPath(path),
|
||||||
|
root = result[0],
|
||||||
|
dir = result[1];
|
||||||
|
|
||||||
|
if (!root && !dir) {
|
||||||
|
// No dirname whatsoever
|
||||||
|
return '.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dir) {
|
||||||
|
// It has a dirname, strip trailing slash
|
||||||
|
dir = dir.substr(0, dir.length - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return root + dir;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
posix.basename = function (path, ext) {
|
||||||
|
var f = posixSplitPath(path)[2];
|
||||||
|
// TODO: make this comparison case-insensitive on windows?
|
||||||
|
if (ext && f.substr(-1 * ext.length) === ext) {
|
||||||
|
f = f.substr(0, f.length - ext.length);
|
||||||
|
}
|
||||||
|
return f;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
posix.extname = function (path) {
|
||||||
|
return posixSplitPath(path)[3];
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
posix.format = function (pathObject) {
|
||||||
|
if (!util.isObject(pathObject)) {
|
||||||
|
throw new TypeError(
|
||||||
|
"Parameter 'pathObject' must be an object, not " + typeof pathObject
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
var root = pathObject.root || '';
|
||||||
|
|
||||||
|
if (!util.isString(root)) {
|
||||||
|
throw new TypeError(
|
||||||
|
"'pathObject.root' must be a string or undefined, not " +
|
||||||
|
typeof pathObject.root
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
var dir = pathObject.dir ? pathObject.dir + posix.sep : '';
|
||||||
|
var base = pathObject.base || '';
|
||||||
|
return dir + base;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
posix.parse = function (pathString) {
|
||||||
|
if (!util.isString(pathString)) {
|
||||||
|
throw new TypeError(
|
||||||
|
"Parameter 'pathString' must be a string, not " + typeof pathString
|
||||||
|
);
|
||||||
|
}
|
||||||
|
var allParts = posixSplitPath(pathString);
|
||||||
|
if (!allParts || allParts.length !== 4) {
|
||||||
|
throw new TypeError("Invalid path '" + pathString + "'");
|
||||||
|
}
|
||||||
|
allParts[1] = allParts[1] || '';
|
||||||
|
allParts[2] = allParts[2] || '';
|
||||||
|
allParts[3] = allParts[3] || '';
|
||||||
|
|
||||||
|
return {
|
||||||
|
root: allParts[0],
|
||||||
|
dir: allParts[0] + allParts[1].slice(0, -1),
|
||||||
|
base: allParts[2],
|
||||||
|
ext: allParts[3],
|
||||||
|
name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
posix.sep = '/';
|
||||||
|
posix.delimiter = ':';
|
||||||
|
|
||||||
|
|
||||||
|
if (isWindows)
|
||||||
|
module.exports = win32;
|
||||||
|
else /* posix */
|
||||||
|
module.exports = posix;
|
||||||
|
|
||||||
|
module.exports.posix = posix;
|
||||||
|
module.exports.win32 = win32;
|
||||||
442
packages/nodejs/src/punycode/index.ts
Normal file
442
packages/nodejs/src/punycode/index.ts
Normal file
@@ -0,0 +1,442 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/** Highest positive signed 32-bit float value */
|
||||||
|
const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
|
||||||
|
|
||||||
|
/** Bootstring parameters */
|
||||||
|
const base = 36;
|
||||||
|
const tMin = 1;
|
||||||
|
const tMax = 26;
|
||||||
|
const skew = 38;
|
||||||
|
const damp = 700;
|
||||||
|
const initialBias = 72;
|
||||||
|
const initialN = 128; // 0x80
|
||||||
|
const delimiter = '-'; // '\x2D'
|
||||||
|
|
||||||
|
/** Regular expressions */
|
||||||
|
const regexPunycode = /^xn--/;
|
||||||
|
const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
|
||||||
|
const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
|
||||||
|
|
||||||
|
/** Error messages */
|
||||||
|
const errors = {
|
||||||
|
'overflow': 'Overflow: input needs wider integers to process',
|
||||||
|
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
|
||||||
|
'invalid-input': 'Invalid input'
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Convenience shortcuts */
|
||||||
|
const baseMinusTMin = base - tMin;
|
||||||
|
const floor = Math.floor;
|
||||||
|
const stringFromCharCode = String.fromCharCode;
|
||||||
|
|
||||||
|
/*--------------------------------------------------------------------------*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A generic error utility function.
|
||||||
|
* @private
|
||||||
|
* @param {String} type The error type.
|
||||||
|
* @returns {Error} Throws a `RangeError` with the applicable error message.
|
||||||
|
*/
|
||||||
|
function error(type) {
|
||||||
|
throw new RangeError(errors[type]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A generic `Array#map` utility function.
|
||||||
|
* @private
|
||||||
|
* @param {Array} array The array to iterate over.
|
||||||
|
* @param {Function} callback The function that gets called for every array
|
||||||
|
* item.
|
||||||
|
* @returns {Array} A new array of values returned by the callback function.
|
||||||
|
*/
|
||||||
|
function map(array, fn) {
|
||||||
|
const result = [];
|
||||||
|
let length = array.length;
|
||||||
|
while (length--) {
|
||||||
|
result[length] = fn(array[length]);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A simple `Array#map`-like wrapper to work with domain name strings or email
|
||||||
|
* addresses.
|
||||||
|
* @private
|
||||||
|
* @param {String} domain The domain name or email address.
|
||||||
|
* @param {Function} callback The function that gets called for every
|
||||||
|
* character.
|
||||||
|
* @returns {Array} A new string of characters returned by the callback
|
||||||
|
* function.
|
||||||
|
*/
|
||||||
|
function mapDomain(string, fn) {
|
||||||
|
const parts = string.split('@');
|
||||||
|
let result = '';
|
||||||
|
if (parts.length > 1) {
|
||||||
|
// In email addresses, only the domain name should be punycoded. Leave
|
||||||
|
// the local part (i.e. everything up to `@`) intact.
|
||||||
|
result = parts[0] + '@';
|
||||||
|
string = parts[1];
|
||||||
|
}
|
||||||
|
// Avoid `split(regex)` for IE8 compatibility. See #17.
|
||||||
|
string = string.replace(regexSeparators, '\x2E');
|
||||||
|
const labels = string.split('.');
|
||||||
|
const encoded = map(labels, fn).join('.');
|
||||||
|
return result + encoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates an array containing the numeric code points of each Unicode
|
||||||
|
* character in the string. While JavaScript uses UCS-2 internally,
|
||||||
|
* this function will convert a pair of surrogate halves (each of which
|
||||||
|
* UCS-2 exposes as separate characters) into a single code point,
|
||||||
|
* matching UTF-16.
|
||||||
|
* @see `punycode.ucs2.encode`
|
||||||
|
* @see <https://mathiasbynens.be/notes/javascript-encoding>
|
||||||
|
* @memberOf punycode.ucs2
|
||||||
|
* @name decode
|
||||||
|
* @param {String} string The Unicode input string (UCS-2).
|
||||||
|
* @returns {Array} The new array of code points.
|
||||||
|
*/
|
||||||
|
function ucs2decode(string) {
|
||||||
|
const output = [];
|
||||||
|
let counter = 0;
|
||||||
|
const length = string.length;
|
||||||
|
while (counter < length) {
|
||||||
|
const value = string.charCodeAt(counter++);
|
||||||
|
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
|
||||||
|
// It's a high surrogate, and there is a next character.
|
||||||
|
const extra = string.charCodeAt(counter++);
|
||||||
|
if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
|
||||||
|
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
|
||||||
|
} else {
|
||||||
|
// It's an unmatched surrogate; only append this code unit, in case the
|
||||||
|
// next code unit is the high surrogate of a surrogate pair.
|
||||||
|
output.push(value);
|
||||||
|
counter--;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
output.push(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a string based on an array of numeric code points.
|
||||||
|
* @see `punycode.ucs2.decode`
|
||||||
|
* @memberOf punycode.ucs2
|
||||||
|
* @name encode
|
||||||
|
* @param {Array} codePoints The array of numeric code points.
|
||||||
|
* @returns {String} The new Unicode string (UCS-2).
|
||||||
|
*/
|
||||||
|
const ucs2encode = array => String.fromCodePoint(...array);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts a basic code point into a digit/integer.
|
||||||
|
* @see `digitToBasic()`
|
||||||
|
* @private
|
||||||
|
* @param {Number} codePoint The basic numeric code point value.
|
||||||
|
* @returns {Number} The numeric value of a basic code point (for use in
|
||||||
|
* representing integers) in the range `0` to `base - 1`, or `base` if
|
||||||
|
* the code point does not represent a value.
|
||||||
|
*/
|
||||||
|
const basicToDigit = function (codePoint) {
|
||||||
|
if (codePoint - 0x30 < 0x0A) {
|
||||||
|
return codePoint - 0x16;
|
||||||
|
}
|
||||||
|
if (codePoint - 0x41 < 0x1A) {
|
||||||
|
return codePoint - 0x41;
|
||||||
|
}
|
||||||
|
if (codePoint - 0x61 < 0x1A) {
|
||||||
|
return codePoint - 0x61;
|
||||||
|
}
|
||||||
|
return base;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts a digit/integer into a basic code point.
|
||||||
|
* @see `basicToDigit()`
|
||||||
|
* @private
|
||||||
|
* @param {Number} digit The numeric value of a basic code point.
|
||||||
|
* @returns {Number} The basic code point whose value (when used for
|
||||||
|
* representing integers) is `digit`, which needs to be in the range
|
||||||
|
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
|
||||||
|
* used; else, the lowercase form is used. The behavior is undefined
|
||||||
|
* if `flag` is non-zero and `digit` has no uppercase form.
|
||||||
|
*/
|
||||||
|
const digitToBasic = function (digit: number, flag: number) {
|
||||||
|
// 0..25 map to ASCII a..z or A..Z
|
||||||
|
// 26..35 map to ASCII 0..9
|
||||||
|
//@ts-ignore
|
||||||
|
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bias adaptation function as per section 3.4 of RFC 3492.
|
||||||
|
* https://tools.ietf.org/html/rfc3492#section-3.4
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
const adapt = function (delta, numPoints, firstTime) {
|
||||||
|
let k = 0;
|
||||||
|
delta = firstTime ? floor(delta / damp) : delta >> 1;
|
||||||
|
delta += floor(delta / numPoints);
|
||||||
|
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
|
||||||
|
delta = floor(delta / baseMinusTMin);
|
||||||
|
}
|
||||||
|
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
|
||||||
|
* symbols.
|
||||||
|
* @memberOf punycode
|
||||||
|
* @param {String} input The Punycode string of ASCII-only symbols.
|
||||||
|
* @returns {String} The resulting string of Unicode symbols.
|
||||||
|
*/
|
||||||
|
const decode = function (input) {
|
||||||
|
// Don't use UCS-2.
|
||||||
|
const output = [];
|
||||||
|
const inputLength = input.length;
|
||||||
|
let i = 0;
|
||||||
|
let n = initialN;
|
||||||
|
let bias = initialBias;
|
||||||
|
|
||||||
|
// Handle the basic code points: let `basic` be the number of input code
|
||||||
|
// points before the last delimiter, or `0` if there is none, then copy
|
||||||
|
// the first basic code points to the output.
|
||||||
|
|
||||||
|
let basic = input.lastIndexOf(delimiter);
|
||||||
|
if (basic < 0) {
|
||||||
|
basic = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let j = 0; j < basic; ++j) {
|
||||||
|
// if it's not a basic code point
|
||||||
|
if (input.charCodeAt(j) >= 0x80) {
|
||||||
|
error('not-basic');
|
||||||
|
}
|
||||||
|
output.push(input.charCodeAt(j));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main decoding loop: start just after the last delimiter if any basic code
|
||||||
|
// points were copied; start at the beginning otherwise.
|
||||||
|
|
||||||
|
for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
|
||||||
|
|
||||||
|
// `index` is the index of the next character to be consumed.
|
||||||
|
// Decode a generalized variable-length integer into `delta`,
|
||||||
|
// which gets added to `i`. The overflow checking is easier
|
||||||
|
// if we increase `i` as we go, then subtract off its starting
|
||||||
|
// value at the end to obtain `delta`.
|
||||||
|
let oldi = i;
|
||||||
|
for (let w = 1, k = base; /* no condition */; k += base) {
|
||||||
|
|
||||||
|
if (index >= inputLength) {
|
||||||
|
error('invalid-input');
|
||||||
|
}
|
||||||
|
|
||||||
|
const digit = basicToDigit(input.charCodeAt(index++));
|
||||||
|
|
||||||
|
if (digit >= base || digit > floor((maxInt - i) / w)) {
|
||||||
|
error('overflow');
|
||||||
|
}
|
||||||
|
|
||||||
|
i += digit * w;
|
||||||
|
const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
|
||||||
|
|
||||||
|
if (digit < t) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseMinusT = base - t;
|
||||||
|
if (w > floor(maxInt / baseMinusT)) {
|
||||||
|
error('overflow');
|
||||||
|
}
|
||||||
|
|
||||||
|
w *= baseMinusT;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
const out = output.length + 1;
|
||||||
|
bias = adapt(i - oldi, out, oldi == 0);
|
||||||
|
|
||||||
|
// `i` was supposed to wrap around from `out` to `0`,
|
||||||
|
// incrementing `n` each time, so we'll fix that now:
|
||||||
|
if (floor(i / out) > maxInt - n) {
|
||||||
|
error('overflow');
|
||||||
|
}
|
||||||
|
|
||||||
|
n += floor(i / out);
|
||||||
|
i %= out;
|
||||||
|
|
||||||
|
// Insert `n` at position `i` of the output.
|
||||||
|
output.splice(i++, 0, n);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return String.fromCodePoint(...output);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts a string of Unicode symbols (e.g. a domain name label) to a
|
||||||
|
* Punycode string of ASCII-only symbols.
|
||||||
|
* @memberOf punycode
|
||||||
|
* @param {String} input The string of Unicode symbols.
|
||||||
|
* @returns {String} The resulting Punycode string of ASCII-only symbols.
|
||||||
|
*/
|
||||||
|
const encode = function (input) {
|
||||||
|
const output = [];
|
||||||
|
|
||||||
|
// Convert the input in UCS-2 to an array of Unicode code points.
|
||||||
|
input = ucs2decode(input);
|
||||||
|
|
||||||
|
// Cache the length.
|
||||||
|
let inputLength = input.length;
|
||||||
|
|
||||||
|
// Initialize the state.
|
||||||
|
let n = initialN;
|
||||||
|
let delta = 0;
|
||||||
|
let bias = initialBias;
|
||||||
|
|
||||||
|
// Handle the basic code points.
|
||||||
|
for (const currentValue of input) {
|
||||||
|
if (currentValue < 0x80) {
|
||||||
|
output.push(stringFromCharCode(currentValue));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let basicLength = output.length;
|
||||||
|
let handledCPCount = basicLength;
|
||||||
|
|
||||||
|
// `handledCPCount` is the number of code points that have been handled;
|
||||||
|
// `basicLength` is the number of basic code points.
|
||||||
|
|
||||||
|
// Finish the basic string with a delimiter unless it's empty.
|
||||||
|
if (basicLength) {
|
||||||
|
output.push(delimiter);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main encoding loop:
|
||||||
|
while (handledCPCount < inputLength) {
|
||||||
|
|
||||||
|
// All non-basic code points < n have been handled already. Find the next
|
||||||
|
// larger one:
|
||||||
|
let m = maxInt;
|
||||||
|
for (const currentValue of input) {
|
||||||
|
if (currentValue >= n && currentValue < m) {
|
||||||
|
m = currentValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
|
||||||
|
// but guard against overflow.
|
||||||
|
const handledCPCountPlusOne = handledCPCount + 1;
|
||||||
|
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
|
||||||
|
error('overflow');
|
||||||
|
}
|
||||||
|
|
||||||
|
delta += (m - n) * handledCPCountPlusOne;
|
||||||
|
n = m;
|
||||||
|
|
||||||
|
for (const currentValue of input) {
|
||||||
|
if (currentValue < n && ++delta > maxInt) {
|
||||||
|
error('overflow');
|
||||||
|
}
|
||||||
|
if (currentValue == n) {
|
||||||
|
// Represent delta as a generalized variable-length integer.
|
||||||
|
let q = delta;
|
||||||
|
for (let k = base; /* no condition */; k += base) {
|
||||||
|
const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
|
||||||
|
if (q < t) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const qMinusT = q - t;
|
||||||
|
const baseMinusT = base - t;
|
||||||
|
output.push(
|
||||||
|
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
|
||||||
|
);
|
||||||
|
q = floor(qMinusT / baseMinusT);
|
||||||
|
}
|
||||||
|
|
||||||
|
output.push(stringFromCharCode(digitToBasic(q, 0)));
|
||||||
|
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
|
||||||
|
delta = 0;
|
||||||
|
++handledCPCount;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
++delta;
|
||||||
|
++n;
|
||||||
|
|
||||||
|
}
|
||||||
|
return output.join('');
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts a Punycode string representing a domain name or an email address
|
||||||
|
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
|
||||||
|
* it doesn't matter if you call it on a string that has already been
|
||||||
|
* converted to Unicode.
|
||||||
|
* @memberOf punycode
|
||||||
|
* @param {String} input The Punycoded domain name or email address to
|
||||||
|
* convert to Unicode.
|
||||||
|
* @returns {String} The Unicode representation of the given Punycode
|
||||||
|
* string.
|
||||||
|
*/
|
||||||
|
const toUnicode = function (input) {
|
||||||
|
return mapDomain(input, function (string) {
|
||||||
|
return regexPunycode.test(string)
|
||||||
|
? decode(string.slice(4).toLowerCase())
|
||||||
|
: string;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts a Unicode string representing a domain name or an email address to
|
||||||
|
* Punycode. Only the non-ASCII parts of the domain name will be converted,
|
||||||
|
* i.e. it doesn't matter if you call it with a domain that's already in
|
||||||
|
* ASCII.
|
||||||
|
* @memberOf punycode
|
||||||
|
* @param {String} input The domain name or email address to convert, as a
|
||||||
|
* Unicode string.
|
||||||
|
* @returns {String} The Punycode representation of the given domain name or
|
||||||
|
* email address.
|
||||||
|
*/
|
||||||
|
const toASCII = function (input) {
|
||||||
|
return mapDomain(input, function (string) {
|
||||||
|
return regexNonASCII.test(string)
|
||||||
|
? 'xn--' + encode(string)
|
||||||
|
: string;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/*--------------------------------------------------------------------------*/
|
||||||
|
|
||||||
|
/** Define the public API */
|
||||||
|
//@ts-ignore
|
||||||
|
const punycode = {
|
||||||
|
/**
|
||||||
|
* A string representing the current Punycode.js version number.
|
||||||
|
* @memberOf punycode
|
||||||
|
* @type String
|
||||||
|
*/
|
||||||
|
'version': '2.1.0',
|
||||||
|
/**
|
||||||
|
* An object of methods to convert from JavaScript's internal character
|
||||||
|
* representation (UCS-2) to Unicode code points, and back.
|
||||||
|
* @see <https://mathiasbynens.be/notes/javascript-encoding>
|
||||||
|
* @memberOf punycode
|
||||||
|
* @type Object
|
||||||
|
*/
|
||||||
|
'ucs2': {
|
||||||
|
'decode': ucs2decode,
|
||||||
|
'encode': ucs2encode
|
||||||
|
},
|
||||||
|
'decode': decode,
|
||||||
|
'encode': encode,
|
||||||
|
'toASCII': toASCII,
|
||||||
|
'toUnicode': toUnicode
|
||||||
|
};
|
||||||
|
|
||||||
|
export = punycode;
|
||||||
81
packages/nodejs/src/querystring/decode.ts
Normal file
81
packages/nodejs/src/querystring/decode.ts
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
// 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';
|
||||||
|
|
||||||
|
// If obj.hasOwnProperty has been overridden, then calling
|
||||||
|
// obj.hasOwnProperty(prop) will break.
|
||||||
|
// See: https://github.com/joyent/node/issues/1707
|
||||||
|
// @ts-ignore
|
||||||
|
function hasOwnProperty(obj, prop) {
|
||||||
|
return Object.prototype.hasOwnProperty.call(obj, prop);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = function (qs, sep, eq, options) {
|
||||||
|
sep = sep || '&';
|
||||||
|
eq = eq || '=';
|
||||||
|
var obj = {};
|
||||||
|
|
||||||
|
if (typeof qs !== 'string' || qs.length === 0) {
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
var regexp = /\+/g;
|
||||||
|
qs = qs.split(sep);
|
||||||
|
|
||||||
|
var maxKeys = 1000;
|
||||||
|
if (options && typeof options.maxKeys === 'number') {
|
||||||
|
maxKeys = options.maxKeys;
|
||||||
|
}
|
||||||
|
|
||||||
|
var len = qs.length;
|
||||||
|
// maxKeys <= 0 means that we should not limit keys count
|
||||||
|
if (maxKeys > 0 && len > maxKeys) {
|
||||||
|
len = maxKeys;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < len; ++i) {
|
||||||
|
var x = qs[i].replace(regexp, '%20'),
|
||||||
|
idx = x.indexOf(eq),
|
||||||
|
kstr, vstr, k, v;
|
||||||
|
|
||||||
|
if (idx >= 0) {
|
||||||
|
kstr = x.substr(0, idx);
|
||||||
|
vstr = x.substr(idx + 1);
|
||||||
|
} else {
|
||||||
|
kstr = x;
|
||||||
|
vstr = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
k = decodeURIComponent(kstr);
|
||||||
|
v = decodeURIComponent(vstr);
|
||||||
|
|
||||||
|
if (!hasOwnProperty(obj, k)) {
|
||||||
|
obj[k] = v;
|
||||||
|
} else if (Array.isArray(obj[k])) {
|
||||||
|
obj[k].push(v);
|
||||||
|
} else {
|
||||||
|
obj[k] = [obj[k], v];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return obj;
|
||||||
|
};
|
||||||
64
packages/nodejs/src/querystring/encode.ts
Normal file
64
packages/nodejs/src/querystring/encode.ts
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
// 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 stringifyPrimitive = function (v) {
|
||||||
|
switch (typeof v) {
|
||||||
|
case 'string':
|
||||||
|
return v;
|
||||||
|
|
||||||
|
case 'boolean':
|
||||||
|
return v ? 'true' : 'false';
|
||||||
|
|
||||||
|
case 'number':
|
||||||
|
return isFinite(v) ? v : '';
|
||||||
|
|
||||||
|
default:
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = function (obj, sep, eq, name) {
|
||||||
|
sep = sep || '&';
|
||||||
|
eq = eq || '=';
|
||||||
|
if (obj === null) {
|
||||||
|
obj = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof obj === 'object') {
|
||||||
|
return Object.keys(obj).map(function (k) {
|
||||||
|
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
|
||||||
|
if (Array.isArray(obj[k])) {
|
||||||
|
return obj[k].map(function (v) {
|
||||||
|
return ks + encodeURIComponent(stringifyPrimitive(v));
|
||||||
|
}).join(sep);
|
||||||
|
} else {
|
||||||
|
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
|
||||||
|
}
|
||||||
|
}).filter(Boolean).join(sep);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!name) return '';
|
||||||
|
return encodeURIComponent(stringifyPrimitive(name)) + eq +
|
||||||
|
encodeURIComponent(stringifyPrimitive(obj));
|
||||||
|
};
|
||||||
4
packages/nodejs/src/querystring/index.ts
Normal file
4
packages/nodejs/src/querystring/index.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
exports.decode = exports.parse = require('./decode');
|
||||||
|
exports.encode = exports.stringify = require('./encode');
|
||||||
747
packages/nodejs/src/url/index.ts
Normal file
747
packages/nodejs/src/url/index.ts
Normal file
@@ -0,0 +1,747 @@
|
|||||||
|
// 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';
|
||||||
|
|
||||||
|
import * as punycode from 'punycode'
|
||||||
|
|
||||||
|
var util = {
|
||||||
|
isString: function (arg) {
|
||||||
|
return typeof (arg) === 'string';
|
||||||
|
},
|
||||||
|
isObject: function (arg) {
|
||||||
|
return typeof (arg) === 'object' && arg !== null;
|
||||||
|
},
|
||||||
|
isNull: function (arg) {
|
||||||
|
return arg === null;
|
||||||
|
},
|
||||||
|
isNullOrUndefined: function (arg) {
|
||||||
|
return arg == null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.parse = urlParse;
|
||||||
|
exports.resolve = urlResolve;
|
||||||
|
exports.resolveObject = urlResolveObject;
|
||||||
|
exports.format = urlFormat;
|
||||||
|
|
||||||
|
exports.Url = Url;
|
||||||
|
|
||||||
|
function Url(this: any) {
|
||||||
|
this.protocol = null;
|
||||||
|
this.slashes = null;
|
||||||
|
this.auth = null;
|
||||||
|
this.host = null;
|
||||||
|
this.port = null;
|
||||||
|
this.hostname = null;
|
||||||
|
this.hash = null;
|
||||||
|
this.search = null;
|
||||||
|
this.query = null;
|
||||||
|
this.pathname = null;
|
||||||
|
this.path = null;
|
||||||
|
this.href = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reference: RFC 3986, RFC 1808, RFC 2396
|
||||||
|
|
||||||
|
// define these here so at least they only have to be
|
||||||
|
// compiled once on the first module load.
|
||||||
|
var protocolPattern = /^([a-z0-9.+-]+:)/i,
|
||||||
|
portPattern = /:[0-9]*$/,
|
||||||
|
|
||||||
|
// Special case for a simple path URL
|
||||||
|
simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
|
||||||
|
|
||||||
|
// RFC 2396: characters reserved for delimiting URLs.
|
||||||
|
// We actually just auto-escape these.
|
||||||
|
delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
|
||||||
|
|
||||||
|
// RFC 2396: characters not allowed for various reasons.
|
||||||
|
unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
|
||||||
|
|
||||||
|
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
|
||||||
|
autoEscape = ['\''].concat(unwise),
|
||||||
|
// Characters that are never ever allowed in a hostname.
|
||||||
|
// Note that any invalid chars are also handled, but these
|
||||||
|
// are the ones that are *expected* to be seen, so we fast-path
|
||||||
|
// them.
|
||||||
|
nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
|
||||||
|
hostEndingChars = ['/', '?', '#'],
|
||||||
|
hostnameMaxLen = 255,
|
||||||
|
hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
|
||||||
|
hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
|
||||||
|
// protocols that can allow "unsafe" and "unwise" chars.
|
||||||
|
unsafeProtocol = {
|
||||||
|
'javascript': true,
|
||||||
|
'javascript:': true
|
||||||
|
},
|
||||||
|
// protocols that never have a hostname.
|
||||||
|
hostlessProtocol = {
|
||||||
|
'javascript': true,
|
||||||
|
'javascript:': true
|
||||||
|
},
|
||||||
|
// protocols that always contain a // bit.
|
||||||
|
slashedProtocol = {
|
||||||
|
'http': true,
|
||||||
|
'https': true,
|
||||||
|
'ftp': true,
|
||||||
|
'gopher': true,
|
||||||
|
'file': true,
|
||||||
|
'http:': true,
|
||||||
|
'https:': true,
|
||||||
|
'ftp:': true,
|
||||||
|
'gopher:': true,
|
||||||
|
'file:': true
|
||||||
|
},
|
||||||
|
querystring = require('querystring');
|
||||||
|
|
||||||
|
function urlParse(url, parseQueryString?, slashesDenoteHost?) {
|
||||||
|
if (url && util.isObject(url) && url instanceof Url) return url;
|
||||||
|
|
||||||
|
var u = new Url;
|
||||||
|
u.parse(url, parseQueryString, slashesDenoteHost);
|
||||||
|
return u;
|
||||||
|
}
|
||||||
|
|
||||||
|
Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
|
||||||
|
if (!util.isString(url)) {
|
||||||
|
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy chrome, IE, opera backslash-handling behavior.
|
||||||
|
// Back slashes before the query string get converted to forward slashes
|
||||||
|
// See: https://code.google.com/p/chromium/issues/detail?id=25916
|
||||||
|
var queryIndex = url.indexOf('?'),
|
||||||
|
splitter =
|
||||||
|
(queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
|
||||||
|
uSplit = url.split(splitter),
|
||||||
|
slashRegex = /\\/g;
|
||||||
|
uSplit[0] = uSplit[0].replace(slashRegex, '/');
|
||||||
|
url = uSplit.join(splitter);
|
||||||
|
|
||||||
|
var rest = url;
|
||||||
|
|
||||||
|
// trim before proceeding.
|
||||||
|
// This is to support parse stuff like " http://foo.com \n"
|
||||||
|
rest = rest.trim();
|
||||||
|
|
||||||
|
if (!slashesDenoteHost && url.split('#').length === 1) {
|
||||||
|
// Try fast path regexp
|
||||||
|
var simplePath = simplePathPattern.exec(rest);
|
||||||
|
if (simplePath) {
|
||||||
|
this.path = rest;
|
||||||
|
this.href = rest;
|
||||||
|
this.pathname = simplePath[1];
|
||||||
|
if (simplePath[2]) {
|
||||||
|
this.search = simplePath[2];
|
||||||
|
if (parseQueryString) {
|
||||||
|
this.query = querystring.parse(this.search.substr(1));
|
||||||
|
} else {
|
||||||
|
this.query = this.search.substr(1);
|
||||||
|
}
|
||||||
|
} else if (parseQueryString) {
|
||||||
|
this.search = '';
|
||||||
|
this.query = {};
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var proto: any = protocolPattern.exec(rest);
|
||||||
|
if (proto) {
|
||||||
|
proto = proto[0];
|
||||||
|
var lowerProto = proto.toLowerCase();
|
||||||
|
this.protocol = lowerProto;
|
||||||
|
rest = rest.substr(proto.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
// figure out if it's got a host
|
||||||
|
// user@server is *always* interpreted as a hostname, and url
|
||||||
|
// resolution will treat //foo/bar as host=foo,path=bar because that's
|
||||||
|
// how the browser resolves relative URLs.
|
||||||
|
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
|
||||||
|
var slashes = rest.substr(0, 2) === '//';
|
||||||
|
if (slashes && !(proto && hostlessProtocol[proto])) {
|
||||||
|
rest = rest.substr(2);
|
||||||
|
this.slashes = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hostlessProtocol[proto] &&
|
||||||
|
(slashes || (proto && !slashedProtocol[proto]))) {
|
||||||
|
|
||||||
|
// there's a hostname.
|
||||||
|
// the first instance of /, ?, ;, or # ends the host.
|
||||||
|
//
|
||||||
|
// If there is an @ in the hostname, then non-host chars *are* allowed
|
||||||
|
// to the left of the last @ sign, unless some host-ending character
|
||||||
|
// comes *before* the @-sign.
|
||||||
|
// URLs are obnoxious.
|
||||||
|
//
|
||||||
|
// ex:
|
||||||
|
// http://a@b@c/ => user:a@b host:c
|
||||||
|
// http://a@b?@c => user:a host:c path:/?@c
|
||||||
|
|
||||||
|
// v0.12 TODO(isaacs): This is not quite how Chrome does things.
|
||||||
|
// Review our test case against browsers more comprehensively.
|
||||||
|
|
||||||
|
// find the first instance of any hostEndingChars
|
||||||
|
var hostEnd = -1;
|
||||||
|
for (var i = 0; i < hostEndingChars.length; i++) {
|
||||||
|
var hec = rest.indexOf(hostEndingChars[i]);
|
||||||
|
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
|
||||||
|
hostEnd = hec;
|
||||||
|
}
|
||||||
|
|
||||||
|
// at this point, either we have an explicit point where the
|
||||||
|
// auth portion cannot go past, or the last @ char is the decider.
|
||||||
|
var auth, atSign;
|
||||||
|
if (hostEnd === -1) {
|
||||||
|
// atSign can be anywhere.
|
||||||
|
atSign = rest.lastIndexOf('@');
|
||||||
|
} else {
|
||||||
|
// atSign must be in auth portion.
|
||||||
|
// http://a@b/c@d => host:b auth:a path:/c@d
|
||||||
|
atSign = rest.lastIndexOf('@', hostEnd);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now we have a portion which is definitely the auth.
|
||||||
|
// Pull that off.
|
||||||
|
if (atSign !== -1) {
|
||||||
|
auth = rest.slice(0, atSign);
|
||||||
|
rest = rest.slice(atSign + 1);
|
||||||
|
this.auth = decodeURIComponent(auth);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the host is the remaining to the left of the first non-host char
|
||||||
|
hostEnd = -1;
|
||||||
|
for (var i = 0; i < nonHostChars.length; i++) {
|
||||||
|
var hec = rest.indexOf(nonHostChars[i]);
|
||||||
|
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
|
||||||
|
hostEnd = hec;
|
||||||
|
}
|
||||||
|
// if we still have not hit it, then the entire thing is a host.
|
||||||
|
if (hostEnd === -1)
|
||||||
|
hostEnd = rest.length;
|
||||||
|
|
||||||
|
this.host = rest.slice(0, hostEnd);
|
||||||
|
rest = rest.slice(hostEnd);
|
||||||
|
|
||||||
|
// pull out port.
|
||||||
|
this.parseHost();
|
||||||
|
|
||||||
|
// we've indicated that there is a hostname,
|
||||||
|
// so even if it's empty, it has to be present.
|
||||||
|
this.hostname = this.hostname || '';
|
||||||
|
|
||||||
|
// if hostname begins with [ and ends with ]
|
||||||
|
// assume that it's an IPv6 address.
|
||||||
|
var ipv6Hostname = this.hostname[0] === '[' &&
|
||||||
|
this.hostname[this.hostname.length - 1] === ']';
|
||||||
|
|
||||||
|
// validate a little.
|
||||||
|
if (!ipv6Hostname) {
|
||||||
|
var hostparts = this.hostname.split(/\./);
|
||||||
|
for (var i = 0, l = hostparts.length; i < l; i++) {
|
||||||
|
var part = hostparts[i];
|
||||||
|
if (!part) continue;
|
||||||
|
if (!part.match(hostnamePartPattern)) {
|
||||||
|
var newpart = '';
|
||||||
|
for (var j = 0, k = part.length; j < k; j++) {
|
||||||
|
if (part.charCodeAt(j) > 127) {
|
||||||
|
// we replace non-ASCII char with a temporary placeholder
|
||||||
|
// we need this to make sure size of hostname is not
|
||||||
|
// broken by replacing non-ASCII by nothing
|
||||||
|
newpart += 'x';
|
||||||
|
} else {
|
||||||
|
newpart += part[j];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// we test again with ASCII char only
|
||||||
|
if (!newpart.match(hostnamePartPattern)) {
|
||||||
|
var validParts = hostparts.slice(0, i);
|
||||||
|
var notHost = hostparts.slice(i + 1);
|
||||||
|
var bit = part.match(hostnamePartStart);
|
||||||
|
if (bit) {
|
||||||
|
validParts.push(bit[1]);
|
||||||
|
notHost.unshift(bit[2]);
|
||||||
|
}
|
||||||
|
if (notHost.length) {
|
||||||
|
rest = '/' + notHost.join('.') + rest;
|
||||||
|
}
|
||||||
|
this.hostname = validParts.join('.');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.hostname.length > hostnameMaxLen) {
|
||||||
|
this.hostname = '';
|
||||||
|
} else {
|
||||||
|
// hostnames are always lower case.
|
||||||
|
this.hostname = this.hostname.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ipv6Hostname) {
|
||||||
|
// IDNA Support: Returns a punycoded representation of "domain".
|
||||||
|
// It only converts parts of the domain name that
|
||||||
|
// have non-ASCII characters, i.e. it doesn't matter if
|
||||||
|
// you call it with a domain that already is ASCII-only.
|
||||||
|
this.hostname = punycode.toASCII(this.hostname);
|
||||||
|
}
|
||||||
|
|
||||||
|
var p = this.port ? ':' + this.port : '';
|
||||||
|
var h = this.hostname || '';
|
||||||
|
this.host = h + p;
|
||||||
|
this.href += this.host;
|
||||||
|
|
||||||
|
// strip [ and ] from the hostname
|
||||||
|
// the host field still retains them, though
|
||||||
|
if (ipv6Hostname) {
|
||||||
|
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
|
||||||
|
if (rest[0] !== '/') {
|
||||||
|
rest = '/' + rest;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// now rest is set to the post-host stuff.
|
||||||
|
// chop off any delim chars.
|
||||||
|
if (!unsafeProtocol[lowerProto]) {
|
||||||
|
|
||||||
|
// First, make 100% sure that any "autoEscape" chars get
|
||||||
|
// escaped, even if encodeURIComponent doesn't think they
|
||||||
|
// need to be.
|
||||||
|
for (var i = 0, m = autoEscape.length; i < m; i++) {
|
||||||
|
var ae = autoEscape[i];
|
||||||
|
if (rest.indexOf(ae) === -1)
|
||||||
|
continue;
|
||||||
|
var esc = encodeURIComponent(ae);
|
||||||
|
if (esc === ae) {
|
||||||
|
esc = escape(ae);
|
||||||
|
}
|
||||||
|
rest = rest.split(ae).join(esc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// chop off from the tail first.
|
||||||
|
var hash = rest.indexOf('#');
|
||||||
|
if (hash !== -1) {
|
||||||
|
// got a fragment string.
|
||||||
|
this.hash = rest.substr(hash);
|
||||||
|
rest = rest.slice(0, hash);
|
||||||
|
}
|
||||||
|
var qm = rest.indexOf('?');
|
||||||
|
if (qm !== -1) {
|
||||||
|
this.search = rest.substr(qm);
|
||||||
|
this.query = rest.substr(qm + 1);
|
||||||
|
if (parseQueryString) {
|
||||||
|
this.query = querystring.parse(this.query);
|
||||||
|
}
|
||||||
|
rest = rest.slice(0, qm);
|
||||||
|
} else if (parseQueryString) {
|
||||||
|
// no query string, but parseQueryString still requested
|
||||||
|
this.search = '';
|
||||||
|
this.query = {};
|
||||||
|
}
|
||||||
|
if (rest) this.pathname = rest;
|
||||||
|
if (slashedProtocol[lowerProto] &&
|
||||||
|
this.hostname && !this.pathname) {
|
||||||
|
this.pathname = '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
//to support http.request
|
||||||
|
if (this.pathname || this.search) {
|
||||||
|
var q = this.pathname || '';
|
||||||
|
var s = this.search || '';
|
||||||
|
this.path = q + s;
|
||||||
|
}
|
||||||
|
|
||||||
|
// finally, reconstruct the href based on what has been validated.
|
||||||
|
this.href = this.format();
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
|
// format a parsed object into a url string
|
||||||
|
function urlFormat(obj) {
|
||||||
|
// ensure it's an object, and not a string url.
|
||||||
|
// If it's an obj, this is a no-op.
|
||||||
|
// this way, you can call url_format() on strings
|
||||||
|
// to clean up potentially wonky urls.
|
||||||
|
if (util.isString(obj)) obj = urlParse(obj);
|
||||||
|
if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
|
||||||
|
// @ts-ignore
|
||||||
|
return obj.format();
|
||||||
|
}
|
||||||
|
|
||||||
|
Url.prototype.format = function () {
|
||||||
|
var auth = this.auth || '';
|
||||||
|
if (auth) {
|
||||||
|
auth = encodeURIComponent(auth);
|
||||||
|
auth = auth.replace(/%3A/i, ':');
|
||||||
|
auth += '@';
|
||||||
|
}
|
||||||
|
|
||||||
|
var protocol = this.protocol || '',
|
||||||
|
pathname = this.pathname || '',
|
||||||
|
hash = this.hash || '',
|
||||||
|
host: any = false,
|
||||||
|
query = '';
|
||||||
|
|
||||||
|
if (this.host) {
|
||||||
|
host = auth + this.host;
|
||||||
|
} else if (this.hostname) {
|
||||||
|
host = auth + (this.hostname.indexOf(':') === -1 ?
|
||||||
|
this.hostname :
|
||||||
|
'[' + this.hostname + ']');
|
||||||
|
if (this.port) {
|
||||||
|
host += ':' + this.port;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.query &&
|
||||||
|
util.isObject(this.query) &&
|
||||||
|
Object.keys(this.query).length) {
|
||||||
|
query = querystring.stringify(this.query);
|
||||||
|
}
|
||||||
|
|
||||||
|
var search = this.search || (query && ('?' + query)) || '';
|
||||||
|
|
||||||
|
if (protocol && protocol.substr(-1) !== ':') protocol += ':';
|
||||||
|
|
||||||
|
// only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
|
||||||
|
// unless they had them to begin with.
|
||||||
|
if (this.slashes ||
|
||||||
|
(!protocol || slashedProtocol[protocol]) && host !== false) {
|
||||||
|
host = '//' + (host || '');
|
||||||
|
if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
|
||||||
|
} else if (!host) {
|
||||||
|
host = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
|
||||||
|
if (search && search.charAt(0) !== '?') search = '?' + search;
|
||||||
|
|
||||||
|
pathname = pathname.replace(/[?#]/g, function (match) {
|
||||||
|
return encodeURIComponent(match);
|
||||||
|
});
|
||||||
|
search = search.replace('#', '%23');
|
||||||
|
|
||||||
|
return protocol + host + pathname + search + hash;
|
||||||
|
};
|
||||||
|
|
||||||
|
function urlResolve(source, relative) {
|
||||||
|
return urlParse(source, false, true).resolve(relative);
|
||||||
|
}
|
||||||
|
|
||||||
|
Url.prototype.resolve = function (relative) {
|
||||||
|
return this.resolveObject(urlParse(relative, false, true)).format();
|
||||||
|
};
|
||||||
|
|
||||||
|
function urlResolveObject(source, relative) {
|
||||||
|
if (!source) return relative;
|
||||||
|
return urlParse(source, false, true).resolveObject(relative);
|
||||||
|
}
|
||||||
|
|
||||||
|
Url.prototype.resolveObject = function (relative) {
|
||||||
|
if (util.isString(relative)) {
|
||||||
|
var rel = new Url();
|
||||||
|
rel.parse(relative, false, true);
|
||||||
|
relative = rel;
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = new Url();
|
||||||
|
var tkeys = Object.keys(this);
|
||||||
|
for (var tk = 0; tk < tkeys.length; tk++) {
|
||||||
|
var tkey = tkeys[tk];
|
||||||
|
result[tkey] = this[tkey];
|
||||||
|
}
|
||||||
|
|
||||||
|
// hash is always overridden, no matter what.
|
||||||
|
// even href="" will remove it.
|
||||||
|
result.hash = relative.hash;
|
||||||
|
|
||||||
|
// if the relative url is empty, then there's nothing left to do here.
|
||||||
|
if (relative.href === '') {
|
||||||
|
result.href = result.format();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// hrefs like //foo/bar always cut to the protocol.
|
||||||
|
if (relative.slashes && !relative.protocol) {
|
||||||
|
// take everything except the protocol from relative
|
||||||
|
var rkeys = Object.keys(relative);
|
||||||
|
for (var rk = 0; rk < rkeys.length; rk++) {
|
||||||
|
var rkey = rkeys[rk];
|
||||||
|
if (rkey !== 'protocol')
|
||||||
|
result[rkey] = relative[rkey];
|
||||||
|
}
|
||||||
|
|
||||||
|
//urlParse appends trailing / to urls like http://www.example.com
|
||||||
|
if (slashedProtocol[result.protocol] &&
|
||||||
|
result.hostname && !result.pathname) {
|
||||||
|
result.path = result.pathname = '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
result.href = result.format();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (relative.protocol && relative.protocol !== result.protocol) {
|
||||||
|
// if it's a known url protocol, then changing
|
||||||
|
// the protocol does weird things
|
||||||
|
// first, if it's not file:, then we MUST have a host,
|
||||||
|
// and if there was a path
|
||||||
|
// to begin with, then we MUST have a path.
|
||||||
|
// if it is file:, then the host is dropped,
|
||||||
|
// because that's known to be hostless.
|
||||||
|
// anything else is assumed to be absolute.
|
||||||
|
if (!slashedProtocol[relative.protocol]) {
|
||||||
|
var keys = Object.keys(relative);
|
||||||
|
for (var v = 0; v < keys.length; v++) {
|
||||||
|
var k = keys[v];
|
||||||
|
result[k] = relative[k];
|
||||||
|
}
|
||||||
|
result.href = result.format();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
result.protocol = relative.protocol;
|
||||||
|
if (!relative.host && !hostlessProtocol[relative.protocol]) {
|
||||||
|
var relPath = (relative.pathname || '').split('/');
|
||||||
|
while (relPath.length && !(relative.host = relPath.shift()));
|
||||||
|
if (!relative.host) relative.host = '';
|
||||||
|
if (!relative.hostname) relative.hostname = '';
|
||||||
|
if (relPath[0] !== '') relPath.unshift('');
|
||||||
|
if (relPath.length < 2) relPath.unshift('');
|
||||||
|
result.pathname = relPath.join('/');
|
||||||
|
} else {
|
||||||
|
result.pathname = relative.pathname;
|
||||||
|
}
|
||||||
|
result.search = relative.search;
|
||||||
|
result.query = relative.query;
|
||||||
|
result.host = relative.host || '';
|
||||||
|
result.auth = relative.auth;
|
||||||
|
result.hostname = relative.hostname || relative.host;
|
||||||
|
result.port = relative.port;
|
||||||
|
// to support http.request
|
||||||
|
if (result.pathname || result.search) {
|
||||||
|
var p = result.pathname || '';
|
||||||
|
var s = result.search || '';
|
||||||
|
result.path = p + s;
|
||||||
|
}
|
||||||
|
result.slashes = result.slashes || relative.slashes;
|
||||||
|
result.href = result.format();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
|
||||||
|
isRelAbs = (
|
||||||
|
relative.host ||
|
||||||
|
relative.pathname && relative.pathname.charAt(0) === '/'
|
||||||
|
),
|
||||||
|
mustEndAbs = (isRelAbs || isSourceAbs ||
|
||||||
|
(result.host && relative.pathname)),
|
||||||
|
removeAllDots = mustEndAbs,
|
||||||
|
srcPath = result.pathname && result.pathname.split('/') || [],
|
||||||
|
relPath = relative.pathname && relative.pathname.split('/') || [],
|
||||||
|
psychotic = result.protocol && !slashedProtocol[result.protocol];
|
||||||
|
|
||||||
|
// if the url is a non-slashed url, then relative
|
||||||
|
// links like ../.. should be able
|
||||||
|
// to crawl up to the hostname, as well. This is strange.
|
||||||
|
// result.protocol has already been set by now.
|
||||||
|
// Later on, put the first path part into the host field.
|
||||||
|
if (psychotic) {
|
||||||
|
result.hostname = '';
|
||||||
|
result.port = null;
|
||||||
|
if (result.host) {
|
||||||
|
if (srcPath[0] === '') srcPath[0] = result.host;
|
||||||
|
else srcPath.unshift(result.host);
|
||||||
|
}
|
||||||
|
result.host = '';
|
||||||
|
if (relative.protocol) {
|
||||||
|
relative.hostname = null;
|
||||||
|
relative.port = null;
|
||||||
|
if (relative.host) {
|
||||||
|
if (relPath[0] === '') relPath[0] = relative.host;
|
||||||
|
else relPath.unshift(relative.host);
|
||||||
|
}
|
||||||
|
relative.host = null;
|
||||||
|
}
|
||||||
|
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isRelAbs) {
|
||||||
|
// it's absolute.
|
||||||
|
result.host = (relative.host || relative.host === '') ?
|
||||||
|
relative.host : result.host;
|
||||||
|
result.hostname = (relative.hostname || relative.hostname === '') ?
|
||||||
|
relative.hostname : result.hostname;
|
||||||
|
result.search = relative.search;
|
||||||
|
result.query = relative.query;
|
||||||
|
srcPath = relPath;
|
||||||
|
// fall through to the dot-handling below.
|
||||||
|
} else if (relPath.length) {
|
||||||
|
// it's relative
|
||||||
|
// throw away the existing file, and take the new path instead.
|
||||||
|
if (!srcPath) srcPath = [];
|
||||||
|
srcPath.pop();
|
||||||
|
srcPath = srcPath.concat(relPath);
|
||||||
|
result.search = relative.search;
|
||||||
|
result.query = relative.query;
|
||||||
|
} else if (!util.isNullOrUndefined(relative.search)) {
|
||||||
|
// just pull out the search.
|
||||||
|
// like href='?foo'.
|
||||||
|
// Put this after the other two cases because it simplifies the booleans
|
||||||
|
if (psychotic) {
|
||||||
|
result.hostname = result.host = srcPath.shift();
|
||||||
|
//occationaly the auth can get stuck only in host
|
||||||
|
//this especially happens in cases like
|
||||||
|
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
|
||||||
|
var authInHost = result.host && result.host.indexOf('@') > 0 ?
|
||||||
|
result.host.split('@') : false;
|
||||||
|
if (authInHost) {
|
||||||
|
result.auth = authInHost.shift();
|
||||||
|
result.host = result.hostname = authInHost.shift();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.search = relative.search;
|
||||||
|
result.query = relative.query;
|
||||||
|
//to support http.request
|
||||||
|
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
|
||||||
|
result.path = (result.pathname ? result.pathname : '') +
|
||||||
|
(result.search ? result.search : '');
|
||||||
|
}
|
||||||
|
result.href = result.format();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!srcPath.length) {
|
||||||
|
// no path at all. easy.
|
||||||
|
// we've already handled the other stuff above.
|
||||||
|
result.pathname = null;
|
||||||
|
//to support http.request
|
||||||
|
if (result.search) {
|
||||||
|
result.path = '/' + result.search;
|
||||||
|
} else {
|
||||||
|
result.path = null;
|
||||||
|
}
|
||||||
|
result.href = result.format();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// if a url ENDs in . or .., then it must get a trailing slash.
|
||||||
|
// however, if it ends in anything else non-slashy,
|
||||||
|
// then it must NOT get a trailing slash.
|
||||||
|
var last = srcPath.slice(-1)[0];
|
||||||
|
var hasTrailingSlash = (
|
||||||
|
(result.host || relative.host || srcPath.length > 1) &&
|
||||||
|
(last === '.' || last === '..') || last === '');
|
||||||
|
|
||||||
|
// strip single dots, resolve double dots to parent dir
|
||||||
|
// if the path tries to go above the root, `up` ends up > 0
|
||||||
|
var up = 0;
|
||||||
|
for (var i = srcPath.length; i >= 0; i--) {
|
||||||
|
last = srcPath[i];
|
||||||
|
if (last === '.') {
|
||||||
|
srcPath.splice(i, 1);
|
||||||
|
} else if (last === '..') {
|
||||||
|
srcPath.splice(i, 1);
|
||||||
|
up++;
|
||||||
|
} else if (up) {
|
||||||
|
srcPath.splice(i, 1);
|
||||||
|
up--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// if the path is allowed to go above the root, restore leading ..s
|
||||||
|
if (!mustEndAbs && !removeAllDots) {
|
||||||
|
for (; up--; up) {
|
||||||
|
srcPath.unshift('..');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mustEndAbs && srcPath[0] !== '' &&
|
||||||
|
(!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
|
||||||
|
srcPath.unshift('');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
|
||||||
|
srcPath.push('');
|
||||||
|
}
|
||||||
|
|
||||||
|
var isAbsolute = srcPath[0] === '' ||
|
||||||
|
(srcPath[0] && srcPath[0].charAt(0) === '/');
|
||||||
|
|
||||||
|
// put the host back
|
||||||
|
if (psychotic) {
|
||||||
|
result.hostname = result.host = isAbsolute ? '' :
|
||||||
|
srcPath.length ? srcPath.shift() : '';
|
||||||
|
//occationaly the auth can get stuck only in host
|
||||||
|
//this especially happens in cases like
|
||||||
|
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
|
||||||
|
var authInHost = result.host && result.host.indexOf('@') > 0 ?
|
||||||
|
result.host.split('@') : false;
|
||||||
|
if (authInHost) {
|
||||||
|
result.auth = authInHost.shift();
|
||||||
|
result.host = result.hostname = authInHost.shift();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mustEndAbs = mustEndAbs || (result.host && srcPath.length);
|
||||||
|
|
||||||
|
if (mustEndAbs && !isAbsolute) {
|
||||||
|
srcPath.unshift('');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!srcPath.length) {
|
||||||
|
result.pathname = null;
|
||||||
|
result.path = null;
|
||||||
|
} else {
|
||||||
|
result.pathname = srcPath.join('/');
|
||||||
|
}
|
||||||
|
|
||||||
|
//to support request.http
|
||||||
|
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
|
||||||
|
result.path = (result.pathname ? result.pathname : '') +
|
||||||
|
(result.search ? result.search : '');
|
||||||
|
}
|
||||||
|
result.auth = relative.auth || result.auth;
|
||||||
|
result.slashes = result.slashes || relative.slashes;
|
||||||
|
result.href = result.format();
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
Url.prototype.parseHost = function () {
|
||||||
|
var host = this.host;
|
||||||
|
var port: any = portPattern.exec(host);
|
||||||
|
if (port) {
|
||||||
|
port = port[0];
|
||||||
|
if (port !== ':') {
|
||||||
|
this.port = port.substr(1);
|
||||||
|
}
|
||||||
|
host = host.substr(0, host.length - port.length);
|
||||||
|
}
|
||||||
|
if (host) this.hostname = host;
|
||||||
|
};
|
||||||
727
packages/nodejs/src/util/index.ts
Normal file
727
packages/nodejs/src/util/index.ts
Normal file
@@ -0,0 +1,727 @@
|
|||||||
|
// 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.
|
||||||
|
|
||||||
|
var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
|
||||||
|
function getOwnPropertyDescriptors(obj) {
|
||||||
|
var keys = Object.keys(obj);
|
||||||
|
var descriptors = {};
|
||||||
|
for (var i = 0; i < keys.length; i++) {
|
||||||
|
descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
|
||||||
|
}
|
||||||
|
return descriptors;
|
||||||
|
};
|
||||||
|
|
||||||
|
var formatRegExp = /%[sdj%]/g;
|
||||||
|
exports.format = function (f) {
|
||||||
|
if (!isString(f)) {
|
||||||
|
var objects = [];
|
||||||
|
for (var i = 0; i < arguments.length; i++) {
|
||||||
|
objects.push(inspect(arguments[i]));
|
||||||
|
}
|
||||||
|
return objects.join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
var i = 1;
|
||||||
|
var args = arguments;
|
||||||
|
var len = args.length;
|
||||||
|
// @ts-ignore
|
||||||
|
var str = String(f).replace(formatRegExp, function (x) {
|
||||||
|
if (x === '%%') return '%';
|
||||||
|
if (i >= len) return x;
|
||||||
|
switch (x) {
|
||||||
|
case '%s': return String(args[i++]);
|
||||||
|
case '%d': return Number(args[i++]);
|
||||||
|
case '%j':
|
||||||
|
try {
|
||||||
|
return JSON.stringify(args[i++]);
|
||||||
|
} catch (_) {
|
||||||
|
return '[Circular]';
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
for (var x = args[i]; i < len; x = args[++i]) {
|
||||||
|
if (isNull(x) || !isObject(x)) {
|
||||||
|
str += ' ' + x;
|
||||||
|
} else {
|
||||||
|
str += ' ' + inspect(x);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return str;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
// Mark that a method should not be used.
|
||||||
|
// Returns a modified function which warns once by default.
|
||||||
|
// If --no-deprecation is set, then it is a no-op.
|
||||||
|
exports.deprecate = function (fn, msg) {
|
||||||
|
// @ts-ignore
|
||||||
|
if (typeof process !== 'undefined' && process.noDeprecation === true) {
|
||||||
|
return fn;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow for deprecating things in the process of starting up.
|
||||||
|
if (typeof process === 'undefined') {
|
||||||
|
return function () {
|
||||||
|
// @ts-ignore
|
||||||
|
return exports.deprecate(fn, msg).apply(this, arguments);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
var warned = false;
|
||||||
|
function deprecated() {
|
||||||
|
if (!warned) {
|
||||||
|
// @ts-ignore
|
||||||
|
if (process.throwDeprecation) {
|
||||||
|
throw new Error(msg);
|
||||||
|
// @ts-ignore
|
||||||
|
} else if (process.traceDeprecation) {
|
||||||
|
console.trace(msg);
|
||||||
|
} else {
|
||||||
|
console.error(msg);
|
||||||
|
}
|
||||||
|
warned = true;
|
||||||
|
}
|
||||||
|
// @ts-ignore
|
||||||
|
return fn.apply(this, arguments);
|
||||||
|
}
|
||||||
|
|
||||||
|
return deprecated;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
var debugs = {};
|
||||||
|
var debugEnvRegex = /^$/;
|
||||||
|
|
||||||
|
if (process.env.NODE_DEBUG) {
|
||||||
|
var debugEnv = process.env.NODE_DEBUG;
|
||||||
|
debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
|
||||||
|
.replace(/\*/g, '.*')
|
||||||
|
.replace(/,/g, '$|^')
|
||||||
|
.toUpperCase();
|
||||||
|
debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');
|
||||||
|
}
|
||||||
|
exports.debuglog = function (set) {
|
||||||
|
set = set.toUpperCase();
|
||||||
|
if (!debugs[set]) {
|
||||||
|
if (debugEnvRegex.test(set)) {
|
||||||
|
var pid = process.pid;
|
||||||
|
debugs[set] = function () {
|
||||||
|
var msg = exports.format.apply(exports, arguments);
|
||||||
|
console.error('%s %d: %s', set, pid, msg);
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
debugs[set] = function () { };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return debugs[set];
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Echos the value of a value. Trys to print the value out
|
||||||
|
* in the best way possible given the different types.
|
||||||
|
*
|
||||||
|
* @param {Object} obj The object to print out.
|
||||||
|
* @param {Object} opts Optional options object that alters the output.
|
||||||
|
*/
|
||||||
|
/* legacy: obj, showHidden, depth, colors*/
|
||||||
|
function inspect(obj, opts?) {
|
||||||
|
// default options
|
||||||
|
var ctx: any = {
|
||||||
|
seen: [],
|
||||||
|
stylize: stylizeNoColor
|
||||||
|
};
|
||||||
|
// legacy...
|
||||||
|
if (arguments.length >= 3) ctx.depth = arguments[2];
|
||||||
|
if (arguments.length >= 4) ctx.colors = arguments[3];
|
||||||
|
if (isBoolean(opts)) {
|
||||||
|
// legacy...
|
||||||
|
ctx.showHidden = opts;
|
||||||
|
} else if (opts) {
|
||||||
|
// got an "options" object
|
||||||
|
exports._extend(ctx, opts);
|
||||||
|
}
|
||||||
|
// set default options
|
||||||
|
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
|
||||||
|
if (isUndefined(ctx.depth)) ctx.depth = 2;
|
||||||
|
if (isUndefined(ctx.colors)) ctx.colors = false;
|
||||||
|
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
|
||||||
|
if (ctx.colors) ctx.stylize = stylizeWithColor;
|
||||||
|
return formatValue(ctx, obj, ctx.depth);
|
||||||
|
}
|
||||||
|
exports.inspect = inspect;
|
||||||
|
|
||||||
|
|
||||||
|
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
|
||||||
|
inspect.colors = {
|
||||||
|
'bold': [1, 22],
|
||||||
|
'italic': [3, 23],
|
||||||
|
'underline': [4, 24],
|
||||||
|
'inverse': [7, 27],
|
||||||
|
'white': [37, 39],
|
||||||
|
'grey': [90, 39],
|
||||||
|
'black': [30, 39],
|
||||||
|
'blue': [34, 39],
|
||||||
|
'cyan': [36, 39],
|
||||||
|
'green': [32, 39],
|
||||||
|
'magenta': [35, 39],
|
||||||
|
'red': [31, 39],
|
||||||
|
'yellow': [33, 39]
|
||||||
|
};
|
||||||
|
|
||||||
|
// Don't use 'blue' not visible on cmd.exe
|
||||||
|
inspect.styles = {
|
||||||
|
'special': 'cyan',
|
||||||
|
'number': 'yellow',
|
||||||
|
'boolean': 'yellow',
|
||||||
|
'undefined': 'grey',
|
||||||
|
'null': 'bold',
|
||||||
|
'string': 'green',
|
||||||
|
'date': 'magenta',
|
||||||
|
// "name": intentionally not styling
|
||||||
|
'regexp': 'red'
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
function stylizeWithColor(str, styleType) {
|
||||||
|
var style = inspect.styles[styleType];
|
||||||
|
|
||||||
|
if (style) {
|
||||||
|
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
|
||||||
|
'\u001b[' + inspect.colors[style][1] + 'm';
|
||||||
|
} else {
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function stylizeNoColor(str, styleType) {
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function arrayToHash(array) {
|
||||||
|
var hash = {};
|
||||||
|
|
||||||
|
array.forEach(function (val, idx) {
|
||||||
|
hash[val] = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
return hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function formatValue(ctx, value, recurseTimes) {
|
||||||
|
// Provide a hook for user-specified inspect functions.
|
||||||
|
// Check that value is an object with an inspect function on it
|
||||||
|
if (ctx.customInspect &&
|
||||||
|
value &&
|
||||||
|
isFunction(value.inspect) &&
|
||||||
|
// Filter out the util module, it's inspect function is special
|
||||||
|
value.inspect !== exports.inspect &&
|
||||||
|
// Also filter out any prototype objects using the circular check.
|
||||||
|
!(value.constructor && value.constructor.prototype === value)) {
|
||||||
|
var ret = value.inspect(recurseTimes, ctx);
|
||||||
|
if (!isString(ret)) {
|
||||||
|
ret = formatValue(ctx, ret, recurseTimes);
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Primitive types cannot have properties
|
||||||
|
var primitive = formatPrimitive(ctx, value);
|
||||||
|
if (primitive) {
|
||||||
|
return primitive;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Look up the keys of the object.
|
||||||
|
var keys = Object.keys(value);
|
||||||
|
var visibleKeys = arrayToHash(keys);
|
||||||
|
|
||||||
|
if (ctx.showHidden) {
|
||||||
|
keys = Object.getOwnPropertyNames(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// IE doesn't make error fields non-enumerable
|
||||||
|
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
|
||||||
|
if (isError(value)
|
||||||
|
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
|
||||||
|
return formatError(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Some type of object without properties can be shortcutted.
|
||||||
|
if (keys.length === 0) {
|
||||||
|
if (isFunction(value)) {
|
||||||
|
var name = value.name ? ': ' + value.name : '';
|
||||||
|
return ctx.stylize('[Function' + name + ']', 'special');
|
||||||
|
}
|
||||||
|
if (isRegExp(value)) {
|
||||||
|
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
|
||||||
|
}
|
||||||
|
if (isDate(value)) {
|
||||||
|
return ctx.stylize(Date.prototype.toString.call(value), 'date');
|
||||||
|
}
|
||||||
|
if (isError(value)) {
|
||||||
|
return formatError(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var base = '', array = false, braces = ['{', '}'];
|
||||||
|
|
||||||
|
// Make Array say that they are Array
|
||||||
|
if (isArray(value)) {
|
||||||
|
array = true;
|
||||||
|
braces = ['[', ']'];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make functions say that they are functions
|
||||||
|
if (isFunction(value)) {
|
||||||
|
var n = value.name ? ': ' + value.name : '';
|
||||||
|
base = ' [Function' + n + ']';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make RegExps say that they are RegExps
|
||||||
|
if (isRegExp(value)) {
|
||||||
|
base = ' ' + RegExp.prototype.toString.call(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make dates with properties first say the date
|
||||||
|
if (isDate(value)) {
|
||||||
|
base = ' ' + Date.prototype.toUTCString.call(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make error with message first say the error
|
||||||
|
if (isError(value)) {
|
||||||
|
base = ' ' + formatError(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (keys.length === 0 && (!array || value.length == 0)) {
|
||||||
|
return braces[0] + base + braces[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (recurseTimes < 0) {
|
||||||
|
if (isRegExp(value)) {
|
||||||
|
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
|
||||||
|
} else {
|
||||||
|
return ctx.stylize('[Object]', 'special');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.seen.push(value);
|
||||||
|
|
||||||
|
var output;
|
||||||
|
if (array) {
|
||||||
|
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
|
||||||
|
} else {
|
||||||
|
output = keys.map(function (key) {
|
||||||
|
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.seen.pop();
|
||||||
|
|
||||||
|
return reduceToSingleString(output, base, braces);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function formatPrimitive(ctx, value) {
|
||||||
|
if (isUndefined(value))
|
||||||
|
return ctx.stylize('undefined', 'undefined');
|
||||||
|
if (isString(value)) {
|
||||||
|
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
|
||||||
|
.replace(/'/g, "\\'")
|
||||||
|
.replace(/\\"/g, '"') + '\'';
|
||||||
|
return ctx.stylize(simple, 'string');
|
||||||
|
}
|
||||||
|
if (isNumber(value))
|
||||||
|
return ctx.stylize('' + value, 'number');
|
||||||
|
if (isBoolean(value))
|
||||||
|
return ctx.stylize('' + value, 'boolean');
|
||||||
|
// For some reason typeof null is "object", so special case here.
|
||||||
|
if (isNull(value))
|
||||||
|
return ctx.stylize('null', 'null');
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function formatError(value) {
|
||||||
|
return '[' + Error.prototype.toString.call(value) + ']';
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
|
||||||
|
var output = [];
|
||||||
|
for (var i = 0, l = value.length; i < l; ++i) {
|
||||||
|
if (hasOwnProperty(value, String(i))) {
|
||||||
|
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
|
||||||
|
String(i), true));
|
||||||
|
} else {
|
||||||
|
output.push('');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keys.forEach(function (key) {
|
||||||
|
if (!key.match(/^\d+$/)) {
|
||||||
|
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
|
||||||
|
key, true));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
|
||||||
|
var name, str, desc;
|
||||||
|
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
|
||||||
|
if (desc.get) {
|
||||||
|
if (desc.set) {
|
||||||
|
str = ctx.stylize('[Getter/Setter]', 'special');
|
||||||
|
} else {
|
||||||
|
str = ctx.stylize('[Getter]', 'special');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (desc.set) {
|
||||||
|
str = ctx.stylize('[Setter]', 'special');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasOwnProperty(visibleKeys, key)) {
|
||||||
|
name = '[' + key + ']';
|
||||||
|
}
|
||||||
|
if (!str) {
|
||||||
|
if (ctx.seen.indexOf(desc.value) < 0) {
|
||||||
|
if (isNull(recurseTimes)) {
|
||||||
|
str = formatValue(ctx, desc.value, null);
|
||||||
|
} else {
|
||||||
|
str = formatValue(ctx, desc.value, recurseTimes - 1);
|
||||||
|
}
|
||||||
|
if (str.indexOf('\n') > -1) {
|
||||||
|
if (array) {
|
||||||
|
str = str.split('\n').map(function (line) {
|
||||||
|
return ' ' + line;
|
||||||
|
}).join('\n').substr(2);
|
||||||
|
} else {
|
||||||
|
str = '\n' + str.split('\n').map(function (line) {
|
||||||
|
return ' ' + line;
|
||||||
|
}).join('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
str = ctx.stylize('[Circular]', 'special');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (isUndefined(name)) {
|
||||||
|
if (array && key.match(/^\d+$/)) {
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
name = JSON.stringify('' + key);
|
||||||
|
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
|
||||||
|
name = name.substr(1, name.length - 2);
|
||||||
|
name = ctx.stylize(name, 'name');
|
||||||
|
} else {
|
||||||
|
name = name.replace(/'/g, "\\'")
|
||||||
|
.replace(/\\"/g, '"')
|
||||||
|
.replace(/(^"|"$)/g, "'");
|
||||||
|
name = ctx.stylize(name, 'string');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return name + ': ' + str;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function reduceToSingleString(output, base, braces) {
|
||||||
|
var numLinesEst = 0;
|
||||||
|
var length = output.reduce(function (prev, cur) {
|
||||||
|
numLinesEst++;
|
||||||
|
if (cur.indexOf('\n') >= 0) numLinesEst++;
|
||||||
|
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
if (length > 60) {
|
||||||
|
return braces[0] +
|
||||||
|
(base === '' ? '' : base + '\n ') +
|
||||||
|
' ' +
|
||||||
|
output.join(',\n ') +
|
||||||
|
' ' +
|
||||||
|
braces[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// NOTE: These type checking functions intentionally don't use `instanceof`
|
||||||
|
// because it is fragile and can be easily faked with `Object.create()`.
|
||||||
|
exports.types = require('./support/types');
|
||||||
|
|
||||||
|
function isArray(ar) {
|
||||||
|
return Array.isArray(ar);
|
||||||
|
}
|
||||||
|
exports.isArray = isArray;
|
||||||
|
|
||||||
|
function isBoolean(arg) {
|
||||||
|
return typeof arg === 'boolean';
|
||||||
|
}
|
||||||
|
exports.isBoolean = isBoolean;
|
||||||
|
|
||||||
|
function isNull(arg) {
|
||||||
|
return arg === null;
|
||||||
|
}
|
||||||
|
exports.isNull = isNull;
|
||||||
|
|
||||||
|
function isNullOrUndefined(arg) {
|
||||||
|
return arg == null;
|
||||||
|
}
|
||||||
|
exports.isNullOrUndefined = isNullOrUndefined;
|
||||||
|
|
||||||
|
function isNumber(arg) {
|
||||||
|
return typeof arg === 'number';
|
||||||
|
}
|
||||||
|
exports.isNumber = isNumber;
|
||||||
|
|
||||||
|
function isString(arg) {
|
||||||
|
return typeof arg === 'string';
|
||||||
|
}
|
||||||
|
exports.isString = isString;
|
||||||
|
|
||||||
|
function isSymbol(arg) {
|
||||||
|
return typeof arg === 'symbol';
|
||||||
|
}
|
||||||
|
exports.isSymbol = isSymbol;
|
||||||
|
|
||||||
|
function isUndefined(arg) {
|
||||||
|
return arg === void 0;
|
||||||
|
}
|
||||||
|
exports.isUndefined = isUndefined;
|
||||||
|
|
||||||
|
function isRegExp(re) {
|
||||||
|
return isObject(re) && objectToString(re) === '[object RegExp]';
|
||||||
|
}
|
||||||
|
exports.isRegExp = isRegExp;
|
||||||
|
exports.types.isRegExp = isRegExp;
|
||||||
|
|
||||||
|
function isObject(arg) {
|
||||||
|
return typeof arg === 'object' && arg !== null;
|
||||||
|
}
|
||||||
|
exports.isObject = isObject;
|
||||||
|
|
||||||
|
function isDate(d) {
|
||||||
|
return isObject(d) && objectToString(d) === '[object Date]';
|
||||||
|
}
|
||||||
|
exports.isDate = isDate;
|
||||||
|
exports.types.isDate = isDate;
|
||||||
|
|
||||||
|
function isError(e) {
|
||||||
|
return isObject(e) &&
|
||||||
|
(objectToString(e) === '[object Error]' || e instanceof Error);
|
||||||
|
}
|
||||||
|
exports.isError = isError;
|
||||||
|
exports.types.isNativeError = isError;
|
||||||
|
|
||||||
|
function isFunction(arg) {
|
||||||
|
return typeof arg === 'function';
|
||||||
|
}
|
||||||
|
exports.isFunction = isFunction;
|
||||||
|
|
||||||
|
function isPrimitive(arg) {
|
||||||
|
return arg === null ||
|
||||||
|
typeof arg === 'boolean' ||
|
||||||
|
typeof arg === 'number' ||
|
||||||
|
typeof arg === 'string' ||
|
||||||
|
typeof arg === 'symbol' || // ES6 symbol
|
||||||
|
typeof arg === 'undefined';
|
||||||
|
}
|
||||||
|
exports.isPrimitive = isPrimitive;
|
||||||
|
|
||||||
|
exports.isBuffer = require('./support/isBuffer');
|
||||||
|
|
||||||
|
function objectToString(o) {
|
||||||
|
return Object.prototype.toString.call(o);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function pad(n) {
|
||||||
|
return n < 10 ? '0' + n.toString(10) : n.toString(10);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
|
||||||
|
'Oct', 'Nov', 'Dec'];
|
||||||
|
|
||||||
|
// 26 Feb 16:19:34
|
||||||
|
function timestamp() {
|
||||||
|
var d = new Date();
|
||||||
|
var time = [pad(d.getHours()),
|
||||||
|
pad(d.getMinutes()),
|
||||||
|
pad(d.getSeconds())].join(':');
|
||||||
|
return [d.getDate(), months[d.getMonth()], time].join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// log is just a thin wrapper to console.log that prepends a timestamp
|
||||||
|
exports.log = function () {
|
||||||
|
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inherit the prototype methods from one constructor into another.
|
||||||
|
*
|
||||||
|
* The Function.prototype.inherits from lang.js rewritten as a standalone
|
||||||
|
* function (not on Function.prototype). NOTE: If this file is to be loaded
|
||||||
|
* during bootstrapping this function needs to be rewritten using some native
|
||||||
|
* functions as prototype setup using normal JavaScript does not work as
|
||||||
|
* expected during bootstrapping (see mirror.js in r114903).
|
||||||
|
*
|
||||||
|
* @param {function} ctor Constructor function which needs to inherit the
|
||||||
|
* prototype.
|
||||||
|
* @param {function} superCtor Constructor function to inherit prototype from.
|
||||||
|
*/
|
||||||
|
exports.inherits = require('inherits');
|
||||||
|
|
||||||
|
exports._extend = function (origin, add) {
|
||||||
|
// Don't do anything if add isn't an object
|
||||||
|
if (!add || !isObject(add)) return origin;
|
||||||
|
|
||||||
|
var keys = Object.keys(add);
|
||||||
|
var i = keys.length;
|
||||||
|
while (i--) {
|
||||||
|
origin[keys[i]] = add[keys[i]];
|
||||||
|
}
|
||||||
|
return origin;
|
||||||
|
};
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
function hasOwnProperty(obj, prop) {
|
||||||
|
return Object.prototype.hasOwnProperty.call(obj, prop);
|
||||||
|
}
|
||||||
|
|
||||||
|
var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;
|
||||||
|
|
||||||
|
exports.promisify = function promisify(original) {
|
||||||
|
if (typeof original !== 'function')
|
||||||
|
throw new TypeError('The "original" argument must be of type Function');
|
||||||
|
|
||||||
|
if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
|
||||||
|
// @ts-ignore
|
||||||
|
var fn = original[kCustomPromisifiedSymbol];
|
||||||
|
if (typeof fn !== 'function') {
|
||||||
|
throw new TypeError('The "util.promisify.custom" argument must be of type Function');
|
||||||
|
}
|
||||||
|
Object.defineProperty(fn, kCustomPromisifiedSymbol, {
|
||||||
|
value: fn, enumerable: false, writable: false, configurable: true
|
||||||
|
});
|
||||||
|
return fn;
|
||||||
|
}
|
||||||
|
// @ts-ignore
|
||||||
|
function fn() {
|
||||||
|
var promiseResolve, promiseReject;
|
||||||
|
var promise = new Promise(function (resolve, reject) {
|
||||||
|
promiseResolve = resolve;
|
||||||
|
promiseReject = reject;
|
||||||
|
});
|
||||||
|
|
||||||
|
var args = [];
|
||||||
|
for (var i = 0; i < arguments.length; i++) {
|
||||||
|
args.push(arguments[i]);
|
||||||
|
}
|
||||||
|
args.push(function (err, value) {
|
||||||
|
if (err) {
|
||||||
|
promiseReject(err);
|
||||||
|
} else {
|
||||||
|
promiseResolve(value);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
// @ts-ignore
|
||||||
|
original.apply(this, args);
|
||||||
|
} catch (err) {
|
||||||
|
promiseReject(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
|
||||||
|
|
||||||
|
if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
|
||||||
|
value: fn, enumerable: false, writable: false, configurable: true
|
||||||
|
});
|
||||||
|
return Object.defineProperties(
|
||||||
|
fn,
|
||||||
|
getOwnPropertyDescriptors(original)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.promisify.custom = kCustomPromisifiedSymbol
|
||||||
|
|
||||||
|
function callbackifyOnRejected(reason, cb) {
|
||||||
|
// `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
|
||||||
|
// Because `null` is a special error value in callbacks which means "no error
|
||||||
|
// occurred", we error-wrap so the callback consumer can distinguish between
|
||||||
|
// "the promise rejected with null" or "the promise fulfilled with undefined".
|
||||||
|
if (!reason) {
|
||||||
|
var newReason = new Error('Promise was rejected with a falsy value');
|
||||||
|
// @ts-ignore
|
||||||
|
newReason.reason = reason;
|
||||||
|
reason = newReason;
|
||||||
|
}
|
||||||
|
return cb(reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
function callbackify(original) {
|
||||||
|
if (typeof original !== 'function') {
|
||||||
|
throw new TypeError('The "original" argument must be of type Function');
|
||||||
|
}
|
||||||
|
|
||||||
|
// We DO NOT return the promise as it gives the user a false sense that
|
||||||
|
// the promise is actually somehow related to the callback's execution
|
||||||
|
// and that the callback throwing will reject the promise.
|
||||||
|
function callbackified() {
|
||||||
|
var args = [];
|
||||||
|
for (var i = 0; i < arguments.length; i++) {
|
||||||
|
args.push(arguments[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
var maybeCb = args.pop();
|
||||||
|
if (typeof maybeCb !== 'function') {
|
||||||
|
throw new TypeError('The last argument must be of type Function');
|
||||||
|
}
|
||||||
|
// @ts-ignore
|
||||||
|
var self = this;
|
||||||
|
var cb = function () {
|
||||||
|
return maybeCb.apply(self, arguments);
|
||||||
|
};
|
||||||
|
// In true node style we process the callback on `nextTick` with all the
|
||||||
|
// implications (stack, `uncaughtException`, `async_hooks`)
|
||||||
|
// @ts-ignore
|
||||||
|
original.apply(this, args)
|
||||||
|
.then(function (ret) { process.nextTick(cb.bind(null, null, ret)) },
|
||||||
|
function (rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) });
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
|
||||||
|
Object.defineProperties(callbackified,
|
||||||
|
getOwnPropertyDescriptors(original));
|
||||||
|
return callbackified;
|
||||||
|
}
|
||||||
|
exports.callbackify = callbackify;
|
||||||
3
packages/nodejs/src/util/support/isBuffer.ts
Normal file
3
packages/nodejs/src/util/support/isBuffer.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module.exports = function isBuffer(arg) {
|
||||||
|
return arg instanceof Buffer;
|
||||||
|
}
|
||||||
6
packages/nodejs/src/util/support/isBufferBrowser.ts
Normal file
6
packages/nodejs/src/util/support/isBufferBrowser.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
module.exports = function isBuffer(arg) {
|
||||||
|
return arg && typeof arg === 'object'
|
||||||
|
&& typeof arg.copy === 'function'
|
||||||
|
&& typeof arg.fill === 'function'
|
||||||
|
&& typeof arg.readUInt8 === 'function';
|
||||||
|
}
|
||||||
424
packages/nodejs/src/util/support/types.ts
Normal file
424
packages/nodejs/src/util/support/types.ts
Normal file
@@ -0,0 +1,424 @@
|
|||||||
|
// Currently in sync with Node.js lib/internal/util/types.js
|
||||||
|
// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9
|
||||||
|
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
var isBuffer = require('./isBuffer');
|
||||||
|
|
||||||
|
var isArgumentsObject = require('is-arguments');
|
||||||
|
var isGeneratorFunction = require('is-generator-function');
|
||||||
|
|
||||||
|
function uncurryThis(f) {
|
||||||
|
return f.call.bind(f);
|
||||||
|
}
|
||||||
|
|
||||||
|
var BigIntSupported = typeof BigInt !== 'undefined';
|
||||||
|
var SymbolSupported = typeof Symbol !== 'undefined';
|
||||||
|
var SymbolToStringTagSupported = SymbolSupported && typeof Symbol.toStringTag !== 'undefined';
|
||||||
|
var Uint8ArraySupported = typeof Uint8Array !== 'undefined';
|
||||||
|
var ArrayBufferSupported = typeof ArrayBuffer !== 'undefined';
|
||||||
|
|
||||||
|
if (Uint8ArraySupported && SymbolToStringTagSupported) {
|
||||||
|
var TypedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
||||||
|
|
||||||
|
var TypedArrayProto_toStringTag =
|
||||||
|
uncurryThis(
|
||||||
|
Object.getOwnPropertyDescriptor(TypedArrayPrototype,
|
||||||
|
Symbol.toStringTag).get);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
var ObjectToString = uncurryThis(Object.prototype.toString);
|
||||||
|
|
||||||
|
var numberValue = uncurryThis(Number.prototype.valueOf);
|
||||||
|
var stringValue = uncurryThis(String.prototype.valueOf);
|
||||||
|
var booleanValue = uncurryThis(Boolean.prototype.valueOf);
|
||||||
|
|
||||||
|
if (BigIntSupported) {
|
||||||
|
var bigIntValue = uncurryThis(BigInt.prototype.valueOf);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (SymbolSupported) {
|
||||||
|
var symbolValue = uncurryThis(Symbol.prototype.valueOf);
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkBoxedPrimitive(value, prototypeValueOf) {
|
||||||
|
if (typeof value !== 'object') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
prototypeValueOf(value);
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.isArgumentsObject = isArgumentsObject;
|
||||||
|
|
||||||
|
exports.isGeneratorFunction = isGeneratorFunction;
|
||||||
|
|
||||||
|
// Taken from here and modified for better browser support
|
||||||
|
// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js
|
||||||
|
function isPromise(input) {
|
||||||
|
return (
|
||||||
|
(
|
||||||
|
typeof Promise !== 'undefined' &&
|
||||||
|
input instanceof Promise
|
||||||
|
) ||
|
||||||
|
(
|
||||||
|
input !== null &&
|
||||||
|
typeof input === 'object' &&
|
||||||
|
typeof input.then === 'function' &&
|
||||||
|
typeof input.catch === 'function'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
exports.isPromise = isPromise;
|
||||||
|
|
||||||
|
function isArrayBufferView(value) {
|
||||||
|
if (ArrayBufferSupported && ArrayBuffer.isView) {
|
||||||
|
return ArrayBuffer.isView(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
isTypedArray(value) ||
|
||||||
|
isDataView(value)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
exports.isArrayBufferView = isArrayBufferView;
|
||||||
|
|
||||||
|
function isTypedArray(value) {
|
||||||
|
if (Uint8ArraySupported && SymbolToStringTagSupported) {
|
||||||
|
return TypedArrayProto_toStringTag(value) !== undefined;
|
||||||
|
} else {
|
||||||
|
return (
|
||||||
|
isUint8Array(value) ||
|
||||||
|
isUint8ClampedArray(value) ||
|
||||||
|
isUint16Array(value) ||
|
||||||
|
isUint32Array(value) ||
|
||||||
|
isInt8Array(value) ||
|
||||||
|
isInt16Array(value) ||
|
||||||
|
isInt32Array(value) ||
|
||||||
|
isFloat32Array(value) ||
|
||||||
|
isFloat64Array(value) ||
|
||||||
|
isBigInt64Array(value) ||
|
||||||
|
isBigUint64Array(value)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.isTypedArray = isTypedArray;
|
||||||
|
|
||||||
|
function isUint8Array(value) {
|
||||||
|
if (Uint8ArraySupported && SymbolToStringTagSupported) {
|
||||||
|
return TypedArrayProto_toStringTag(value) === 'Uint8Array';
|
||||||
|
} else {
|
||||||
|
return (
|
||||||
|
ObjectToString(value) === '[object Uint8Array]' ||
|
||||||
|
// If it's a Buffer instance _and_ has a `.buffer` property,
|
||||||
|
// this is an ArrayBuffer based buffer; thus it's an Uint8Array
|
||||||
|
// (Old Node.js had a custom non-Uint8Array implementation)
|
||||||
|
isBuffer(value) && value.buffer !== undefined
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.isUint8Array = isUint8Array;
|
||||||
|
|
||||||
|
function isUint8ClampedArray(value) {
|
||||||
|
if (Uint8ArraySupported && SymbolToStringTagSupported) {
|
||||||
|
return TypedArrayProto_toStringTag(value) === 'Uint8ClampedArray';
|
||||||
|
} else {
|
||||||
|
return ObjectToString(value) === '[object Uint8ClampedArray]';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.isUint8ClampedArray = isUint8ClampedArray;
|
||||||
|
|
||||||
|
function isUint16Array(value) {
|
||||||
|
if (Uint8ArraySupported && SymbolToStringTagSupported) {
|
||||||
|
return TypedArrayProto_toStringTag(value) === 'Uint16Array';
|
||||||
|
} else {
|
||||||
|
return ObjectToString(value) === '[object Uint16Array]';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.isUint16Array = isUint16Array;
|
||||||
|
|
||||||
|
function isUint32Array(value) {
|
||||||
|
if (Uint8ArraySupported && SymbolToStringTagSupported) {
|
||||||
|
return TypedArrayProto_toStringTag(value) === 'Uint32Array';
|
||||||
|
} else {
|
||||||
|
return ObjectToString(value) === '[object Uint32Array]';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.isUint32Array = isUint32Array;
|
||||||
|
|
||||||
|
function isInt8Array(value) {
|
||||||
|
if (Uint8ArraySupported && SymbolToStringTagSupported) {
|
||||||
|
return TypedArrayProto_toStringTag(value) === 'Int8Array';
|
||||||
|
} else {
|
||||||
|
return ObjectToString(value) === '[object Int8Array]';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.isInt8Array = isInt8Array;
|
||||||
|
|
||||||
|
function isInt16Array(value) {
|
||||||
|
if (Uint8ArraySupported && SymbolToStringTagSupported) {
|
||||||
|
return TypedArrayProto_toStringTag(value) === 'Int16Array';
|
||||||
|
} else {
|
||||||
|
return ObjectToString(value) === '[object Int16Array]';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.isInt16Array = isInt16Array;
|
||||||
|
|
||||||
|
function isInt32Array(value) {
|
||||||
|
if (Uint8ArraySupported && SymbolToStringTagSupported) {
|
||||||
|
return TypedArrayProto_toStringTag(value) === 'Int32Array';
|
||||||
|
} else {
|
||||||
|
return ObjectToString(value) === '[object Int32Array]';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.isInt32Array = isInt32Array;
|
||||||
|
|
||||||
|
function isFloat32Array(value) {
|
||||||
|
if (Uint8ArraySupported && SymbolToStringTagSupported) {
|
||||||
|
return TypedArrayProto_toStringTag(value) === 'Float32Array';
|
||||||
|
} else {
|
||||||
|
return ObjectToString(value) === '[object Float32Array]';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.isFloat32Array = isFloat32Array;
|
||||||
|
|
||||||
|
function isFloat64Array(value) {
|
||||||
|
if (Uint8ArraySupported && SymbolToStringTagSupported) {
|
||||||
|
return TypedArrayProto_toStringTag(value) === 'Float64Array';
|
||||||
|
} else {
|
||||||
|
return ObjectToString(value) === '[object Float64Array]';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.isFloat64Array = isFloat64Array;
|
||||||
|
|
||||||
|
function isBigInt64Array(value) {
|
||||||
|
if (Uint8ArraySupported && SymbolToStringTagSupported) {
|
||||||
|
return TypedArrayProto_toStringTag(value) === 'BigInt64Array';
|
||||||
|
} else {
|
||||||
|
return ObjectToString(value) === '[object BigInt64Array]';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.isBigInt64Array = isBigInt64Array;
|
||||||
|
|
||||||
|
function isBigUint64Array(value) {
|
||||||
|
if (Uint8ArraySupported && SymbolToStringTagSupported) {
|
||||||
|
return TypedArrayProto_toStringTag(value) === 'BigUint64Array';
|
||||||
|
} else {
|
||||||
|
return ObjectToString(value) === '[object BigUint64Array]';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.isBigUint64Array = isBigUint64Array;
|
||||||
|
|
||||||
|
function isMapToString(value) {
|
||||||
|
return ObjectToString(value) === '[object Map]';
|
||||||
|
}
|
||||||
|
isMapToString.working = (
|
||||||
|
typeof Map !== 'undefined' &&
|
||||||
|
isMapToString(new Map())
|
||||||
|
);
|
||||||
|
|
||||||
|
function isMap(value) {
|
||||||
|
if (typeof Map === 'undefined') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return isMapToString.working
|
||||||
|
? isMapToString(value)
|
||||||
|
: value instanceof Map;
|
||||||
|
}
|
||||||
|
exports.isMap = isMap;
|
||||||
|
|
||||||
|
function isSetToString(value) {
|
||||||
|
return ObjectToString(value) === '[object Set]';
|
||||||
|
}
|
||||||
|
isSetToString.working = (
|
||||||
|
typeof Set !== 'undefined' &&
|
||||||
|
isSetToString(new Set())
|
||||||
|
);
|
||||||
|
function isSet(value) {
|
||||||
|
if (typeof Set === 'undefined') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return isSetToString.working
|
||||||
|
? isSetToString(value)
|
||||||
|
: value instanceof Set;
|
||||||
|
}
|
||||||
|
exports.isSet = isSet;
|
||||||
|
|
||||||
|
function isWeakMapToString(value) {
|
||||||
|
return ObjectToString(value) === '[object WeakMap]';
|
||||||
|
}
|
||||||
|
isWeakMapToString.working = (
|
||||||
|
typeof WeakMap !== 'undefined' &&
|
||||||
|
isWeakMapToString(new WeakMap())
|
||||||
|
);
|
||||||
|
function isWeakMap(value) {
|
||||||
|
if (typeof WeakMap === 'undefined') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return isWeakMapToString.working
|
||||||
|
? isWeakMapToString(value)
|
||||||
|
: value instanceof WeakMap;
|
||||||
|
}
|
||||||
|
exports.isWeakMap = isWeakMap;
|
||||||
|
|
||||||
|
function isWeakSetToString(value) {
|
||||||
|
return ObjectToString(value) === '[object WeakSet]';
|
||||||
|
}
|
||||||
|
isWeakSetToString.working = (
|
||||||
|
typeof WeakSet !== 'undefined' &&
|
||||||
|
isWeakSetToString(new WeakSet())
|
||||||
|
);
|
||||||
|
function isWeakSet(value) {
|
||||||
|
return isWeakSetToString(value);
|
||||||
|
if (typeof WeakSet === 'undefined') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return isWeakSetToString.working
|
||||||
|
? isWeakSetToString(value)
|
||||||
|
: value instanceof WeakSet;
|
||||||
|
}
|
||||||
|
exports.isWeakSet = isWeakSet;
|
||||||
|
|
||||||
|
function isArrayBufferToString(value) {
|
||||||
|
return ObjectToString(value) === '[object ArrayBuffer]';
|
||||||
|
}
|
||||||
|
isArrayBufferToString.working = (
|
||||||
|
typeof ArrayBuffer !== 'undefined' &&
|
||||||
|
// @ts-ignore
|
||||||
|
isArrayBufferToString(new ArrayBuffer())
|
||||||
|
);
|
||||||
|
function isArrayBuffer(value) {
|
||||||
|
if (typeof ArrayBuffer === 'undefined') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return isArrayBufferToString.working
|
||||||
|
? isArrayBufferToString(value)
|
||||||
|
: value instanceof ArrayBuffer;
|
||||||
|
}
|
||||||
|
exports.isArrayBuffer = isArrayBuffer;
|
||||||
|
|
||||||
|
function isDataViewToString(value) {
|
||||||
|
return ObjectToString(value) === '[object DataView]';
|
||||||
|
}
|
||||||
|
isDataViewToString.working = (
|
||||||
|
typeof ArrayBuffer !== 'undefined' &&
|
||||||
|
typeof DataView !== 'undefined' &&
|
||||||
|
isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1))
|
||||||
|
);
|
||||||
|
function isDataView(value) {
|
||||||
|
if (typeof DataView === 'undefined') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return isDataViewToString.working
|
||||||
|
? isDataViewToString(value)
|
||||||
|
: value instanceof DataView;
|
||||||
|
}
|
||||||
|
exports.isDataView = isDataView;
|
||||||
|
|
||||||
|
function isSharedArrayBufferToString(value) {
|
||||||
|
return ObjectToString(value) === '[object SharedArrayBuffer]';
|
||||||
|
}
|
||||||
|
isSharedArrayBufferToString.working = (
|
||||||
|
typeof SharedArrayBuffer !== 'undefined' &&
|
||||||
|
// @ts-ignore
|
||||||
|
isSharedArrayBufferToString(new SharedArrayBuffer())
|
||||||
|
);
|
||||||
|
function isSharedArrayBuffer(value) {
|
||||||
|
if (typeof SharedArrayBuffer === 'undefined') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return isSharedArrayBufferToString.working
|
||||||
|
? isSharedArrayBufferToString(value)
|
||||||
|
: value instanceof SharedArrayBuffer;
|
||||||
|
}
|
||||||
|
exports.isSharedArrayBuffer = isSharedArrayBuffer;
|
||||||
|
|
||||||
|
function isAsyncFunction(value) {
|
||||||
|
return ObjectToString(value) === '[object AsyncFunction]';
|
||||||
|
}
|
||||||
|
exports.isAsyncFunction = isAsyncFunction;
|
||||||
|
|
||||||
|
function isMapIterator(value) {
|
||||||
|
return ObjectToString(value) === '[object Map Iterator]';
|
||||||
|
}
|
||||||
|
exports.isMapIterator = isMapIterator;
|
||||||
|
|
||||||
|
function isSetIterator(value) {
|
||||||
|
return ObjectToString(value) === '[object Set Iterator]';
|
||||||
|
}
|
||||||
|
exports.isSetIterator = isSetIterator;
|
||||||
|
|
||||||
|
function isGeneratorObject(value) {
|
||||||
|
return ObjectToString(value) === '[object Generator]';
|
||||||
|
}
|
||||||
|
exports.isGeneratorObject = isGeneratorObject;
|
||||||
|
|
||||||
|
function isWebAssemblyCompiledModule(value) {
|
||||||
|
return ObjectToString(value) === '[object WebAssembly.Module]';
|
||||||
|
}
|
||||||
|
exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;
|
||||||
|
|
||||||
|
function isNumberObject(value) {
|
||||||
|
return checkBoxedPrimitive(value, numberValue);
|
||||||
|
}
|
||||||
|
exports.isNumberObject = isNumberObject;
|
||||||
|
|
||||||
|
function isStringObject(value) {
|
||||||
|
return checkBoxedPrimitive(value, stringValue);
|
||||||
|
}
|
||||||
|
exports.isStringObject = isStringObject;
|
||||||
|
|
||||||
|
function isBooleanObject(value) {
|
||||||
|
return checkBoxedPrimitive(value, booleanValue);
|
||||||
|
}
|
||||||
|
exports.isBooleanObject = isBooleanObject;
|
||||||
|
|
||||||
|
function isBigIntObject(value) {
|
||||||
|
return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);
|
||||||
|
}
|
||||||
|
exports.isBigIntObject = isBigIntObject;
|
||||||
|
|
||||||
|
function isSymbolObject(value) {
|
||||||
|
return SymbolSupported && checkBoxedPrimitive(value, symbolValue);
|
||||||
|
}
|
||||||
|
exports.isSymbolObject = isSymbolObject;
|
||||||
|
|
||||||
|
function isBoxedPrimitive(value) {
|
||||||
|
return (
|
||||||
|
isNumberObject(value) ||
|
||||||
|
isStringObject(value) ||
|
||||||
|
isBooleanObject(value) ||
|
||||||
|
isBigIntObject(value) ||
|
||||||
|
isSymbolObject(value)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
exports.isBoxedPrimitive = isBoxedPrimitive;
|
||||||
|
|
||||||
|
function isAnyArrayBuffer(value) {
|
||||||
|
return Uint8ArraySupported && (
|
||||||
|
isArrayBuffer(value) ||
|
||||||
|
isSharedArrayBuffer(value)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
exports.isAnyArrayBuffer = isAnyArrayBuffer;
|
||||||
|
|
||||||
|
['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function (method) {
|
||||||
|
Object.defineProperty(exports, method, {
|
||||||
|
enumerable: false,
|
||||||
|
value: function () {
|
||||||
|
throw new Error(method + ' is not supported in userland');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/nukkit",
|
"name": "@ms/nukkit",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript nukkit package",
|
"description": "MiaoScript nukkit package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -24,12 +24,11 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/api": "^0.3.0",
|
"@ms/api": "^0.5.0",
|
||||||
"@ms/common": "^0.3.0",
|
"@ms/common": "^0.5.0",
|
||||||
"@ms/container": "^0.3.0",
|
"@ms/container": "^0.5.0"
|
||||||
"@ms/types": "^0.3.0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,16 @@ import { server } from '@ms/api'
|
|||||||
import { provideSingleton } from '@ms/container';
|
import { provideSingleton } from '@ms/container';
|
||||||
|
|
||||||
let Nukkit: cn.nukkit.Server = base.getInstance().getServer();
|
let Nukkit: cn.nukkit.Server = base.getInstance().getServer();
|
||||||
|
const File = Java.type("java.io.File");
|
||||||
|
|
||||||
@provideSingleton(server.Server)
|
@provideSingleton(server.Server)
|
||||||
export class NukkitServer implements 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) {
|
getPlayer(name: string) {
|
||||||
return Nukkit.getPlayer(name)
|
return Nukkit.getPlayer(name)
|
||||||
}
|
}
|
||||||
@@ -29,6 +36,15 @@ export class NukkitServer implements server.Server {
|
|||||||
dispatchConsoleCommand(command: string): boolean {
|
dispatchConsoleCommand(command: string): boolean {
|
||||||
return Nukkit.dispatchCommand(Nukkit.getConsoleSender(), command)
|
return Nukkit.dispatchCommand(Nukkit.getConsoleSender(), command)
|
||||||
}
|
}
|
||||||
|
getPluginsFolder(): string {
|
||||||
|
return this.pluginsFolder;
|
||||||
|
}
|
||||||
|
getNativePluginManager() {
|
||||||
|
return Nukkit.getPluginManager() as any;
|
||||||
|
}
|
||||||
|
getNettyPipeline() {
|
||||||
|
throw new Error("Method not implemented.");
|
||||||
|
}
|
||||||
sendJson(sender: string | any, json: object | string): void {
|
sendJson(sender: string | any, json: object | string): void {
|
||||||
throw new Error("Method not implemented.");
|
throw new Error("Method not implemented.");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ export class NukkitTaskManager implements task.TaskManager {
|
|||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return func()
|
return func()
|
||||||
}
|
}
|
||||||
|
disable() {
|
||||||
|
base.getInstance().getServer().getScheduler().cancelTask(this.pluginInstance)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class NukkitTask extends task.Task {
|
export class NukkitTask extends task.Task {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/ployfill",
|
"name": "@ms/ployfill",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript ployfill package",
|
"description": "MiaoScript ployfill package",
|
||||||
"author": "MiaoWoo <admin@yumc.pw>",
|
"author": "MiaoWoo <admin@yumc.pw>",
|
||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
@@ -17,12 +17,13 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/nashorn": "^0.3.0",
|
"@ms/i18n": "^0.5.0",
|
||||||
|
"@ms/nashorn": "^0.5.0",
|
||||||
"core-js": "^3.6.4"
|
"core-js": "^3.6.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +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;
|
|
||||||
i18n(name: string, ...params: any[]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export { }
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
/// <reference path="./global.ts" />
|
/// <reference types="@ms/nashorn" />
|
||||||
/// <reference types='@ms/nashorn' />
|
|
||||||
import i18n from '@ms/i18n'
|
import i18n from '@ms/i18n'
|
||||||
let ployfillStartTime = new Date().getTime();
|
let ployfillStartTime = new Date().getTime();
|
||||||
i18n.initialize();
|
i18n.initialize();
|
||||||
|
|||||||
141
packages/ployfill/src/task.ts
Normal file
141
packages/ployfill/src/task.ts
Normal 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);
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/plugin",
|
"name": "@ms/plugin",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -22,16 +22,16 @@
|
|||||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/js-yaml": "^3.12.2",
|
"@types/js-yaml": "^3.12.3",
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/api": "^0.3.0",
|
"@ms/api": "^0.5.0",
|
||||||
"@ms/common": "^0.3.0",
|
"@ms/common": "^0.5.0",
|
||||||
"@ms/container": "^0.3.0",
|
"@ms/container": "^0.5.0",
|
||||||
"@ms/i18n": "^0.3.0",
|
"@ms/i18n": "^0.5.0",
|
||||||
"js-yaml": "^3.13.1"
|
"js-yaml": "^3.13.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,4 +4,9 @@ export const METADATA_KEY = {
|
|||||||
tab: "@ms/plugin:tab",
|
tab: "@ms/plugin:tab",
|
||||||
listener: "@ms/plugin:listener",
|
listener: "@ms/plugin:listener",
|
||||||
config: "@ms/plugin:config",
|
config: "@ms/plugin:config",
|
||||||
|
stage: {
|
||||||
|
load: "@ms/plugin:stage:load",
|
||||||
|
enable: "@ms/plugin:stage:enable",
|
||||||
|
disable: "@ms/plugin:stage:disable"
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import { injectable, decorate } from "@ms/container";
|
import { injectable, decorate } from "@ms/container";
|
||||||
import { interfaces } from './interfaces'
|
import { interfaces } from './interfaces'
|
||||||
import { METADATA_KEY } from './constants'
|
import { METADATA_KEY } from './constants'
|
||||||
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata, getPluginConfigMetadata } from './utils'
|
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPluginTabCompleterMetadata, getPluginConfigMetadata, getPluginStageMetadata } from './utils'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* MiaoScript plugin
|
* MiaoScript plugin
|
||||||
* @param metadata PluginMetadata
|
* @param metadata PluginMetadata
|
||||||
*/
|
*/
|
||||||
export function plugin(metadata: interfaces.PluginMetadata) {
|
export function plugin(metadata: interfaces.PluginMetadata) {
|
||||||
return function(target: any) {
|
return function (target: any) {
|
||||||
metadata.target = target;
|
metadata.target = target;
|
||||||
decorate(injectable(), target);
|
decorate(injectable(), target);
|
||||||
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target);
|
Reflect.defineMetadata(METADATA_KEY.plugin, metadata, target);
|
||||||
@@ -23,7 +23,7 @@ export function plugin(metadata: interfaces.PluginMetadata) {
|
|||||||
* @param metadata CommandMetadata
|
* @param metadata CommandMetadata
|
||||||
*/
|
*/
|
||||||
export function cmd(metadata: interfaces.CommandMetadata = {}) {
|
export function cmd(metadata: interfaces.CommandMetadata = {}) {
|
||||||
return function(target: any, key: string, value: any) {
|
return function (target: any, key: string, value: any) {
|
||||||
metadata.name = metadata.name || key;
|
metadata.name = metadata.name || key;
|
||||||
metadata.executor = key;
|
metadata.executor = key;
|
||||||
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
||||||
@@ -37,13 +37,13 @@ export function cmd(metadata: interfaces.CommandMetadata = {}) {
|
|||||||
* MiaoScript TabComplete
|
* MiaoScript TabComplete
|
||||||
* @param metadata TabCompleterMetadata
|
* @param metadata TabCompleterMetadata
|
||||||
*/
|
*/
|
||||||
export function tab(metadata: interfaces.TabCompleterMetadata = {}) {
|
export function tab(metadata: interfaces.CommandMetadata = {}) {
|
||||||
return function(target: any, key: string, value: any) {
|
return function (target: any, key: string, value: any) {
|
||||||
metadata.name = metadata.name || (key.startsWith('tab') ? key.split('tab', 2)[1] : key);
|
metadata.name = metadata.name || (key.startsWith('tab') ? key.split('tab', 2)[1] : key);
|
||||||
if (!metadata.name) { return; }
|
if (!metadata.name) { return; }
|
||||||
metadata.executor = key;
|
metadata.executor = key;
|
||||||
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
metadata.paramtypes = Reflect.getMetadata("design:paramtypes", target, key)
|
||||||
const previousMetadata: Map<string, interfaces.TabCompleterMetadata> = getPluginTabCompleterMetadata(target)
|
const previousMetadata: Map<string, interfaces.CommandMetadata> = getPluginTabCompleterMetadata(target)
|
||||||
previousMetadata.set(metadata.name, metadata)
|
previousMetadata.set(metadata.name, metadata)
|
||||||
Reflect.defineMetadata(METADATA_KEY.tab, previousMetadata, target.constructor);
|
Reflect.defineMetadata(METADATA_KEY.tab, previousMetadata, target.constructor);
|
||||||
};
|
};
|
||||||
@@ -54,7 +54,7 @@ export function tab(metadata: interfaces.TabCompleterMetadata = {}) {
|
|||||||
* @param metadata ListenerMetadata
|
* @param metadata ListenerMetadata
|
||||||
*/
|
*/
|
||||||
export function listener(metadata: interfaces.ListenerMetadata = {}) {
|
export function listener(metadata: interfaces.ListenerMetadata = {}) {
|
||||||
return function(target: any, key: string, value: any) {
|
return function (target: any, key: string, value: any) {
|
||||||
metadata.name = metadata.name || key;
|
metadata.name = metadata.name || key;
|
||||||
metadata.executor = key;
|
metadata.executor = key;
|
||||||
const previousMetadata: interfaces.ListenerMetadata[] = getPluginListenerMetadata(target)
|
const previousMetadata: interfaces.ListenerMetadata[] = getPluginListenerMetadata(target)
|
||||||
@@ -63,7 +63,7 @@ export function listener(metadata: interfaces.ListenerMetadata = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function config(metadata: interfaces.ConfigMetadata = { version: 1, format: 'yml' }) {
|
export function config(metadata: interfaces.ConfigMetadata = { version: 1, format: 'yml' }) {
|
||||||
return function(target: any, key: string) {
|
return function (target: any, key: string) {
|
||||||
metadata.name = metadata.name || key;
|
metadata.name = metadata.name || key;
|
||||||
metadata.variable = key;
|
metadata.variable = key;
|
||||||
const previousMetadata: Map<string, interfaces.ConfigMetadata> = getPluginConfigMetadata(target)
|
const previousMetadata: Map<string, interfaces.ConfigMetadata> = getPluginConfigMetadata(target)
|
||||||
@@ -71,3 +71,24 @@ export function config(metadata: interfaces.ConfigMetadata = { version: 1, forma
|
|||||||
Reflect.defineMetadata(METADATA_KEY.config, previousMetadata, target.constructor);
|
Reflect.defineMetadata(METADATA_KEY.config, previousMetadata, target.constructor);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function stage(metadata: interfaces.ExecMetadata = {}, stage: string) {
|
||||||
|
return function (target: any, key: string, value: any) {
|
||||||
|
metadata.name = metadata.name || key;
|
||||||
|
metadata.executor = key;
|
||||||
|
const previousMetadata: interfaces.ExecMetadata[] = getPluginStageMetadata(target, stage)
|
||||||
|
Reflect.defineMetadata(METADATA_KEY.stage[stage], [metadata, ...previousMetadata], target.constructor);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function load(metadata: interfaces.ExecMetadata = {}) {
|
||||||
|
return stage(metadata, 'load')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function enable(metadata: interfaces.ExecMetadata = {}) {
|
||||||
|
return stage(metadata, 'enable')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function disable(metadata: interfaces.ExecMetadata = {}) {
|
||||||
|
return stage(metadata, 'disable')
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { server, MiaoScriptConsole } from "@ms/api";
|
import { server, MiaoScriptConsole, event } from "@ms/api";
|
||||||
import { METADATA_KEY } from './constants'
|
import { METADATA_KEY } from './constants'
|
||||||
import { injectable, inject, postConstruct } from "@ms/container";
|
import { injectable, inject, postConstruct } from "@ms/container";
|
||||||
import { getPluginMetadata } from "./utils";
|
import { getPluginMetadata } from "./utils";
|
||||||
@@ -55,7 +55,7 @@ export namespace interfaces {
|
|||||||
*/
|
*/
|
||||||
target?: any;
|
target?: any;
|
||||||
}
|
}
|
||||||
interface ExecMetadata extends BaseMetadata {
|
export interface ExecMetadata extends BaseMetadata {
|
||||||
/**
|
/**
|
||||||
* 执行器
|
* 执行器
|
||||||
*/
|
*/
|
||||||
@@ -67,13 +67,16 @@ export namespace interfaces {
|
|||||||
*/
|
*/
|
||||||
paramtypes?: string[];
|
paramtypes?: string[];
|
||||||
}
|
}
|
||||||
export interface TabCompleterMetadata extends ExecMetadata {
|
|
||||||
/**
|
|
||||||
* 参数列表
|
|
||||||
*/
|
|
||||||
paramtypes?: string[];
|
|
||||||
}
|
|
||||||
export interface ListenerMetadata extends ExecMetadata {
|
export interface ListenerMetadata extends ExecMetadata {
|
||||||
|
/**
|
||||||
|
* 监听优先级
|
||||||
|
*/
|
||||||
|
priority?: event.EventPriority;
|
||||||
|
/**
|
||||||
|
* 是否忽略已取消的事件
|
||||||
|
*/
|
||||||
|
ignoreCancel?: boolean;
|
||||||
|
|
||||||
}
|
}
|
||||||
export interface ConfigMetadata extends BaseMetadata {
|
export interface ConfigMetadata extends BaseMetadata {
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
import i18n from '@ms/i18n'
|
import i18n from '@ms/i18n'
|
||||||
import { plugin, server, command, event } from '@ms/api'
|
import { plugin, server, command, event } from '@ms/api'
|
||||||
import { inject, provideSingleton, postConstruct, Container, ContainerInstance } from '@ms/container'
|
import { inject, provideSingleton, Container, ContainerInstance } from '@ms/container'
|
||||||
import * as fs from '@ms/common/dist/fs'
|
import * as fs from '@ms/common/dist/fs'
|
||||||
|
|
||||||
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPlugin, getPluginTabCompleterMetadata, getPluginConfigMetadata } from './utils'
|
import { getPluginMetadatas, getPluginCommandMetadata, getPluginListenerMetadata, getPlugin, getPluginTabCompleterMetadata, getPluginConfigMetadata, getPluginStageMetadata } from './utils'
|
||||||
import { interfaces } from './interfaces'
|
import { interfaces } from './interfaces'
|
||||||
import { getConfigLoader } from './config'
|
import { getConfigLoader } from './config'
|
||||||
|
|
||||||
|
const Thread = Java.type('java.lang.Thread')
|
||||||
|
|
||||||
@provideSingleton(plugin.PluginManager)
|
@provideSingleton(plugin.PluginManager)
|
||||||
export class PluginManagerImpl implements plugin.PluginManager {
|
export class PluginManagerImpl implements plugin.PluginManager {
|
||||||
@inject(ContainerInstance)
|
@inject(ContainerInstance)
|
||||||
@@ -22,25 +24,23 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
@inject(event.Event)
|
@inject(event.Event)
|
||||||
private EventManager: event.Event
|
private EventManager: event.Event
|
||||||
|
|
||||||
|
private initialized: boolean = false
|
||||||
private pluginMap: Map<string, interfaces.Plugin>
|
private pluginMap: Map<string, interfaces.Plugin>
|
||||||
|
|
||||||
@postConstruct()
|
|
||||||
initialize() {
|
initialize() {
|
||||||
if (this.pluginInstance !== null) {
|
if (this.pluginInstance !== null && this.initialized !== true) {
|
||||||
// 如果plugin不等于null 则代表是正式环境
|
// 如果plugin不等于null 则代表是正式环境
|
||||||
console.i18n('ms.plugin.initialize', { plugin: this.pluginInstance })
|
console.i18n('ms.plugin.initialize', { plugin: this.pluginInstance, loader: Thread.currentThread().contextClassLoader })
|
||||||
this.pluginMap = new Map()
|
this.pluginMap = new Map()
|
||||||
console.i18n('ms.plugin.event.map', { count: this.EventManager.mapEventName().toFixed(0), type: this.serverType });
|
console.i18n('ms.plugin.event.map', { count: this.EventManager.mapEventName().toFixed(0), type: this.serverType });
|
||||||
|
this.initialized = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
scan(folder: string): void {
|
scan(folder: string): void {
|
||||||
|
this.initialize()
|
||||||
var plugin = fs.file(root, folder)
|
var plugin = fs.file(root, folder)
|
||||||
var files = []
|
var files = this.scanFolder(plugin)
|
||||||
// load common plugin
|
|
||||||
.concat(this.scanFolder(plugin))
|
|
||||||
// load space plugin
|
|
||||||
.concat(this.scanFolder(fs.file(plugin, this.serverType)))
|
|
||||||
this.loadPlugins(files)
|
this.loadPlugins(files)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,33 +52,37 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
console.i18n("ms.plugin.manager.stage", { stage, plugin: plugin.description.name, version: plugin.description.version, author: plugin.description.author })
|
console.i18n("ms.plugin.manager.stage", { stage, plugin: plugin.description.name, version: plugin.description.version, author: plugin.description.author })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private runPluginStage(plugin: interfaces.Plugin, stage: string, ext: Function) {
|
||||||
|
this.logStage(plugin, i18n.translate(`ms.plugin.manager.stage.${stage}`))
|
||||||
|
this.runCatch(plugin, stage)
|
||||||
|
this.runCatch(plugin, `${this.serverType}${stage}`)
|
||||||
|
this.execPluginStage(plugin, stage)
|
||||||
|
}
|
||||||
|
|
||||||
load(...args: any[]): void {
|
load(...args: any[]): void {
|
||||||
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||||
this.logStage(plugin, i18n.translate("ms.plugin.manager.stage.load"))
|
this.runPluginStage(plugin, 'load', () => {
|
||||||
this.loadConfig(plugin)
|
this.loadConfig(plugin)
|
||||||
this.runCatch(plugin, 'load')
|
})
|
||||||
this.runCatch(plugin, `${this.serverType}load`)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
enable(...args: any[]): void {
|
enable(...args: any[]): void {
|
||||||
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||||
this.logStage(plugin, i18n.translate("ms.plugin.manager.stage.enable"))
|
this.runPluginStage(plugin, 'enable', () => {
|
||||||
this.runCatch(plugin, 'enable')
|
|
||||||
this.runCatch(plugin, `${this.serverType}enable`)
|
|
||||||
this.registryCommand(plugin)
|
this.registryCommand(plugin)
|
||||||
this.registryListener(plugin)
|
this.registryListener(plugin)
|
||||||
})
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
disable(...args: any[]): void {
|
disable(...args: any[]): void {
|
||||||
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
this.checkAndGet(args[0]).forEach((plugin: interfaces.Plugin) => {
|
||||||
this.logStage(plugin, i18n.translate("ms.plugin.manager.stage.disable"))
|
this.runPluginStage(plugin, 'disable', () => {
|
||||||
this.runCatch(plugin, 'disable')
|
|
||||||
this.runCatch(plugin, `${this.serverType}disable`)
|
|
||||||
this.unregistryCommand(plugin)
|
this.unregistryCommand(plugin)
|
||||||
this.unregistryListener(plugin)
|
this.unregistryListener(plugin)
|
||||||
})
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
reload(...args: any[]): void {
|
reload(...args: any[]): void {
|
||||||
@@ -99,7 +103,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
try {
|
try {
|
||||||
if (pl[func]) pl[func].call(pl)
|
if (pl[func]) pl[func].call(pl)
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.console(`§6Plugin §b${pl.description.name} §6exec §d${func} §6function error §4${ex}`)
|
console.i18n("ms.plugin.manager.stage.exec.error", { plugin: pl.description.name, executor: func, error: ex })
|
||||||
console.ex(ex)
|
console.ex(ex)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -160,10 +164,16 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private checkServers(servers: string[]) {
|
private allowProcess(servers: string[]) {
|
||||||
if (!servers) { return true }
|
// Not set servers allow
|
||||||
if (servers.indexOf(`!${this.serverType}`) != -1) { return false }
|
if (!servers || !servers.length) return true
|
||||||
return servers?.indexOf(this.serverType) != -1
|
// 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) {
|
private createPlugin(file: string) {
|
||||||
@@ -174,12 +184,13 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
private buildPlugins() {
|
private buildPlugins() {
|
||||||
let pluginMetadatas = getPluginMetadatas()
|
let pluginMetadatas = getPluginMetadatas()
|
||||||
for (const [_, metadata] of pluginMetadatas) {
|
for (const [_, metadata] of pluginMetadatas) {
|
||||||
if (!this.checkServers(metadata.servers)) { continue }
|
if (!this.allowProcess(metadata.servers)) { continue }
|
||||||
this.buildPlugin(metadata)
|
this.buildPlugin(metadata)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private buildPlugin(metadata: interfaces.PluginMetadata) {
|
private buildPlugin(metadata: interfaces.PluginMetadata) {
|
||||||
|
try {
|
||||||
this.bindPlugin(metadata)
|
this.bindPlugin(metadata)
|
||||||
let pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
|
let pluginInstance = this.container.getNamed<interfaces.Plugin>(plugin.Plugin, metadata.name)
|
||||||
if (!(pluginInstance instanceof interfaces.Plugin)) {
|
if (!(pluginInstance instanceof interfaces.Plugin)) {
|
||||||
@@ -187,7 +198,11 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
this.pluginMap.set(metadata.name, pluginInstance)
|
this.pluginMap.set(metadata.name, pluginInstance)
|
||||||
return pluginInstance
|
return pluginInstance;
|
||||||
|
} catch (ex) {
|
||||||
|
console.i18n("ms.plugin.manager.initialize.error", { name: metadata.name, ex })
|
||||||
|
console.ex(ex)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private bindPlugin(metadata: interfaces.PluginMetadata) {
|
private bindPlugin(metadata: interfaces.PluginMetadata) {
|
||||||
@@ -221,7 +236,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
let tabs = getPluginTabCompleterMetadata(pluginInstance)
|
let tabs = getPluginTabCompleterMetadata(pluginInstance)
|
||||||
for (const [_, cmd] of cmds) {
|
for (const [_, cmd] of cmds) {
|
||||||
let tab = tabs.get(cmd.name)
|
let tab = tabs.get(cmd.name)
|
||||||
if (!this.checkServers(cmd.servers)) { continue }
|
if (!this.allowProcess(cmd.servers)) { continue }
|
||||||
this.CommandManager.on(pluginInstance, cmd.name, {
|
this.CommandManager.on(pluginInstance, cmd.name, {
|
||||||
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
|
cmd: pluginInstance[cmd.executor].bind(pluginInstance),
|
||||||
tab: tab ? pluginInstance[tab.executor].bind(pluginInstance) : undefined
|
tab: tab ? pluginInstance[tab.executor].bind(pluginInstance) : undefined
|
||||||
@@ -233,7 +248,7 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
let events = getPluginListenerMetadata(pluginInstance)
|
let events = getPluginListenerMetadata(pluginInstance)
|
||||||
for (const event of events) {
|
for (const event of events) {
|
||||||
// ignore space listener
|
// ignore space listener
|
||||||
if (!this.checkServers(event.servers)) { continue }
|
if (!this.allowProcess(event.servers)) { continue }
|
||||||
// here must bind this to pluginInstance
|
// here must bind this to pluginInstance
|
||||||
this.EventManager.listen(pluginInstance, event.name, pluginInstance[event.executor].bind(pluginInstance))
|
this.EventManager.listen(pluginInstance, event.name, pluginInstance[event.executor].bind(pluginInstance))
|
||||||
}
|
}
|
||||||
@@ -249,4 +264,18 @@ export class PluginManagerImpl implements plugin.PluginManager {
|
|||||||
private unregistryListener(pluginInstance: interfaces.Plugin) {
|
private unregistryListener(pluginInstance: interfaces.Plugin) {
|
||||||
this.EventManager.disable(pluginInstance)
|
this.EventManager.disable(pluginInstance)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private execPluginStage(pluginInstance: interfaces.Plugin, stageName: string) {
|
||||||
|
let stages = getPluginStageMetadata(pluginInstance, stageName);
|
||||||
|
for (const stage of stages) {
|
||||||
|
if (!this.allowProcess(stage.servers)) { continue }
|
||||||
|
console.i18n("ms.plugin.manager.stage.exec", { plugin: pluginInstance.description.name, name: stage.executor, stage: stageName, servers: stage.servers })
|
||||||
|
try {
|
||||||
|
pluginInstance[stage.executor].apply(pluginInstance)
|
||||||
|
} catch (error) {
|
||||||
|
console.i18n("ms.plugin.manager.stage.exec.error", { plugin: pluginInstance.description.name, executor: stage.executor, error })
|
||||||
|
console.ex(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,10 +34,10 @@ function getPluginCommandMetadata(target: any) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function getPluginTabCompleterMetadata(target: any) {
|
function getPluginTabCompleterMetadata(target: any) {
|
||||||
let tabcompleterMetadata: Map<string, interfaces.TabCompleterMetadata> = Reflect.getMetadata(
|
let tabcompleterMetadata: Map<string, interfaces.CommandMetadata> = Reflect.getMetadata(
|
||||||
METADATA_KEY.tab,
|
METADATA_KEY.tab,
|
||||||
target.constructor
|
target.constructor
|
||||||
) || new Map<string, interfaces.TabCompleterMetadata>();
|
) || new Map<string, interfaces.CommandMetadata>();
|
||||||
return tabcompleterMetadata;
|
return tabcompleterMetadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,6 +57,14 @@ function getPluginConfigMetadata(target: any) {
|
|||||||
return configMetadata;
|
return configMetadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getPluginStageMetadata(target: any, stage: string) {
|
||||||
|
let stageMetadata: interfaces.ExecMetadata[] = Reflect.getMetadata(
|
||||||
|
METADATA_KEY.stage[stage],
|
||||||
|
target.constructor
|
||||||
|
) || [];
|
||||||
|
return stageMetadata;
|
||||||
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
getPlugin,
|
getPlugin,
|
||||||
getPlugins,
|
getPlugins,
|
||||||
@@ -65,5 +73,6 @@ export {
|
|||||||
getPluginCommandMetadata,
|
getPluginCommandMetadata,
|
||||||
getPluginTabCompleterMetadata,
|
getPluginTabCompleterMetadata,
|
||||||
getPluginListenerMetadata,
|
getPluginListenerMetadata,
|
||||||
getPluginConfigMetadata
|
getPluginConfigMetadata,
|
||||||
|
getPluginStageMetadata
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
"private": true,
|
||||||
"name": "@ms/plugins",
|
"name": "@ms/plugins",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript plugins package",
|
"description": "MiaoScript plugins package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -25,12 +25,11 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/plugin": "^0.3.0",
|
"@ms/api": "^0.5.0",
|
||||||
"axios": "^0.19.2",
|
"@ms/container": "^0.5.0",
|
||||||
"es6-map": "^0.1.5",
|
"@ms/plugin": "^0.5.0"
|
||||||
"inversify": "^5.0.1"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,33 +23,43 @@ export class HelloWorld extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bukkitload() {
|
bukkitload() {
|
||||||
this.logger.log('Load When ServerType is Bukkit!')
|
this.logger.log('Plugin Load When ServerType is Bukkit!')
|
||||||
}
|
}
|
||||||
bukkitenable() {
|
bukkitenable() {
|
||||||
this.logger.log('Enable When ServerType is Bukkit!')
|
this.logger.log('Plugin Enable When ServerType is Bukkit!')
|
||||||
}
|
}
|
||||||
bukkitdisable() {
|
bukkitdisable() {
|
||||||
this.logger.log('Disable When ServerType is Bukkit!')
|
this.logger.log('Plugin Disable When ServerType is Bukkit!')
|
||||||
}
|
}
|
||||||
|
|
||||||
spongeload() {
|
spongeload() {
|
||||||
this.logger.log('Load When ServerType is Sponge!')
|
this.logger.log('Plugin Load When ServerType is Sponge!')
|
||||||
}
|
}
|
||||||
spongeenable() {
|
spongeenable() {
|
||||||
this.logger.log('Enable When ServerType is Sponge!')
|
this.logger.log('Plugin Enable When ServerType is Sponge!')
|
||||||
}
|
}
|
||||||
spongedisable() {
|
spongedisable() {
|
||||||
this.logger.log('Disable When ServerType is Sponge!')
|
this.logger.log('Plugin Disable When ServerType is Sponge!')
|
||||||
}
|
}
|
||||||
|
|
||||||
bungeeload() {
|
bungeeload() {
|
||||||
this.logger.log('Load When ServerType is BungeeCord!')
|
this.logger.log('Plugin Load When ServerType is BungeeCord!')
|
||||||
}
|
}
|
||||||
bungeeenable() {
|
bungeeenable() {
|
||||||
this.logger.log('Enable When ServerType is BungeeCord!')
|
this.logger.log('Plugin Enable When ServerType is BungeeCord!')
|
||||||
}
|
}
|
||||||
bungeedisable() {
|
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()
|
@cmd()
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
/// <reference types="@ms/types/dist/typings/sponge" />
|
/// <reference types="@ms/types/dist/typings/sponge" />
|
||||||
/// <reference types="@ms/types/dist/typings/bungee" />
|
/// <reference types="@ms/types/dist/typings/bungee" />
|
||||||
|
|
||||||
import { server, plugin as pluginApi, channel } from '@ms/api'
|
import { server, plugin as pluginApi, channel, constants } from '@ms/api'
|
||||||
import { inject } from '@ms/container';
|
import { inject, optional } from '@ms/container';
|
||||||
import { plugin, interfaces, cmd, listener, tab, config } from '@ms/plugin'
|
import { plugin, interfaces, cmd, listener, tab, config, enable } from '@ms/plugin'
|
||||||
import Tellraw from '@ms/common/dist/tellraw'
|
import Tellraw from '@ms/common/dist/tellraw'
|
||||||
|
|
||||||
const ByteArrayInputStream = Java.type("java.io.ByteArrayInputStream");
|
const ByteArrayInputStream = Java.type("java.io.ByteArrayInputStream");
|
||||||
@@ -12,10 +12,8 @@ const ByteArrayOutputStream = Java.type("java.io.ByteArrayOutputStream");
|
|||||||
const StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
|
const StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
|
||||||
const GZIPInputStream = Java.type("java.util.zip.GZIPInputStream");
|
const GZIPInputStream = Java.type("java.util.zip.GZIPInputStream");
|
||||||
const GZIPOutputStream = Java.type("java.util.zip.GZIPOutputStream");
|
const GZIPOutputStream = Java.type("java.util.zip.GZIPOutputStream");
|
||||||
const Consumer = Java.type("java.util.function.Consumer");
|
|
||||||
const ByteArray = Java.type("byte[]")
|
|
||||||
|
|
||||||
const BiConsumer = Java.type('java.util.function.BiConsumer')
|
const BiConsumer = Java.type('java.util.function.BiConsumer')
|
||||||
|
const ByteArray = Java.type("byte[]")
|
||||||
|
|
||||||
class MiaoMessage {
|
class MiaoMessage {
|
||||||
// public static final String CHANNEL = "MiaoChat:Default".toLowerCase();
|
// public static final String CHANNEL = "MiaoChat:Default".toLowerCase();
|
||||||
@@ -56,10 +54,10 @@ class MiaoMessage {
|
|||||||
export class MiaoChat extends interfaces.Plugin {
|
export class MiaoChat extends interfaces.Plugin {
|
||||||
@inject(server.Server)
|
@inject(server.Server)
|
||||||
private Server: server.Server
|
private Server: server.Server
|
||||||
@inject(server.ServerType)
|
|
||||||
private ServerType: string
|
|
||||||
@inject(channel.Channel)
|
@inject(channel.Channel)
|
||||||
private Channel: channel.Channel
|
@optional() private Channel: channel.Channel
|
||||||
|
|
||||||
|
private channelOff: { off: () => void };
|
||||||
|
|
||||||
@config()
|
@config()
|
||||||
private config = {
|
private config = {
|
||||||
@@ -146,7 +144,7 @@ export class MiaoChat extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private compare(prop: string) {
|
private compare(prop: string) {
|
||||||
return function(obj1: { [x: string]: any; }, obj2: { [x: string]: any; }) {
|
return function (obj1: { [x: string]: any; }, obj2: { [x: string]: any; }) {
|
||||||
var val1 = obj1[prop];
|
var val1 = obj1[prop];
|
||||||
var val2 = obj2[prop];
|
var val2 = obj2[prop];
|
||||||
if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
|
if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
|
||||||
@@ -169,12 +167,10 @@ export class MiaoChat extends interfaces.Plugin {
|
|||||||
return string;
|
return string;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.Channel.listen(this, MiaoMessage.CHANNEL, (data) => {
|
|
||||||
this.sendChatAll(MiaoMessage.decode(data).json)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
disable() {
|
disable() {
|
||||||
|
this.channelOff?.off()
|
||||||
}
|
}
|
||||||
|
|
||||||
bukkitenable() {
|
bukkitenable() {
|
||||||
@@ -188,9 +184,6 @@ export class MiaoChat extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bukkitdisable() {
|
|
||||||
}
|
|
||||||
|
|
||||||
spongeenable() {
|
spongeenable() {
|
||||||
// 尝试加载 Sponge 的 PlaceholderAPI
|
// 尝试加载 Sponge 的 PlaceholderAPI
|
||||||
try {
|
try {
|
||||||
@@ -209,13 +202,27 @@ export class MiaoChat extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
spongedisable() {
|
@enable({ servers: [constants.ServerType.Bukkit, constants.ServerType.Sponge] })
|
||||||
|
serverEnbale() {
|
||||||
|
this.channelOff = this.Channel?.listen(this, MiaoMessage.CHANNEL, (data) => {
|
||||||
|
this.sendChatAll(MiaoMessage.decode(data).json)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
bungeeenable() {
|
bungeeenable() {
|
||||||
|
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())
|
||||||
}
|
}
|
||||||
|
}
|
||||||
bungeedisable() {
|
}))
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@cmd({ servers: ["bungee"] })
|
@cmd({ servers: ["bungee"] })
|
||||||
@@ -236,7 +243,7 @@ export class MiaoChat extends interfaces.Plugin {
|
|||||||
|
|
||||||
@listener({ servers: ['bukkit'] })
|
@listener({ servers: ['bukkit'] })
|
||||||
AsyncPlayerChatEvent(event: org.bukkit.event.player.AsyncPlayerChatEvent) {
|
AsyncPlayerChatEvent(event: org.bukkit.event.player.AsyncPlayerChatEvent) {
|
||||||
this.sendChat(event.getPlayer(), event.getMessage(), function() {
|
this.sendChat(event.getPlayer(), event.getMessage(), function () {
|
||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -252,27 +259,11 @@ export class MiaoChat extends interfaces.Plugin {
|
|||||||
if (plain.startsWith(Tellraw.duplicateChar)) {
|
if (plain.startsWith(Tellraw.duplicateChar)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.sendChat(player, plain, function() {
|
this.sendChat(player, plain, function () {
|
||||||
event.setMessageCancelled(true)
|
event.setMessageCancelled(true)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@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) {
|
|
||||||
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[]) {
|
initFormat(chatFormats: any[]) {
|
||||||
chatFormats.forEach(chatFormat => {
|
chatFormats.forEach(chatFormat => {
|
||||||
var chat_format_str = chatFormat.format;
|
var chat_format_str = chatFormat.format;
|
||||||
@@ -308,7 +299,7 @@ export class MiaoChat extends interfaces.Plugin {
|
|||||||
chat_format.format_list.forEach((format) => {
|
chat_format.format_list.forEach((format) => {
|
||||||
var style = this.styleFormats[format];
|
var style = this.styleFormats[format];
|
||||||
if (style) {
|
if (style) {
|
||||||
tr.then(this.replace(player, style.text));
|
tr.then(this.replace(player, style.text.replace(/&(\w)/g, '§$1')));
|
||||||
if (style.hover) {
|
if (style.hover) {
|
||||||
tr.tip(this.replace(player, style.hover.join('\n')));
|
tr.tip(this.replace(player, style.hover.join('\n')));
|
||||||
}
|
}
|
||||||
@@ -333,7 +324,7 @@ export class MiaoChat extends interfaces.Plugin {
|
|||||||
});
|
});
|
||||||
let json = tr.then(this.replace(player, plain)).json()
|
let json = tr.then(this.replace(player, plain)).json()
|
||||||
this.sendChatAll(json)
|
this.sendChatAll(json)
|
||||||
this.Channel.send(player, MiaoMessage.CHANNEL, MiaoMessage.encode(json))
|
this.Channel?.send(player, MiaoMessage.CHANNEL, MiaoMessage.encode(json))
|
||||||
}
|
}
|
||||||
|
|
||||||
sendChatAll(json: string) {
|
sendChatAll(json: string) {
|
||||||
|
|||||||
@@ -4,239 +4,111 @@
|
|||||||
|
|
||||||
import { plugin as pluginApi, server, task } from '@ms/api'
|
import { plugin as pluginApi, server, task } from '@ms/api'
|
||||||
import { plugin, interfaces, cmd } from '@ms/plugin'
|
import { plugin, interfaces, cmd } from '@ms/plugin'
|
||||||
import { inject, Container, ContainerInstance, postConstruct } from '@ms/container'
|
import { inject, ContainerInstance, Container } from '@ms/container'
|
||||||
import * as reflect from '@ms/common/dist/reflect'
|
import io, { Server as SocketIOServer, Socket as SocketIOSocket } from '@ms/websocket'
|
||||||
|
|
||||||
let clients: any[] = []
|
const suffixMap = {
|
||||||
let SPLIT_LINE = '\\M\\W\\S|T|S|S/L/T/'
|
ts: 'typescript',
|
||||||
let MessageHandle = Symbol.for('MiaoConsole:MessageHandle')
|
js: 'javascript',
|
||||||
const refList: Array<{ server: string, future: string }> = [
|
yml: 'yaml'
|
||||||
{ server: 'an', future: 'g' },//spigot 1.12.2
|
}
|
||||||
{ server: 'getServerConnection', future: 'f' },//after spigot 1.14.4
|
|
||||||
{ 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 {
|
export class MiaoConsole extends interfaces.Plugin {
|
||||||
public static GlobalContainer: Container
|
|
||||||
public static GlobalLogger: Console
|
|
||||||
|
|
||||||
@inject(ContainerInstance)
|
@inject(ContainerInstance)
|
||||||
private container: Container
|
private container: Container
|
||||||
@inject(pluginApi.PluginManager)
|
|
||||||
private PluginManager: pluginApi.PluginManager
|
|
||||||
@inject(server.ServerType)
|
@inject(server.ServerType)
|
||||||
private ServerType: string
|
private serverType: string
|
||||||
@inject(server.Server)
|
@inject(server.Server)
|
||||||
private Server: server.Server
|
private server: server.Server
|
||||||
@inject(task.TaskManager)
|
@inject(task.TaskManager)
|
||||||
private Task: task.TaskManager
|
private task: task.TaskManager
|
||||||
|
@inject(pluginApi.PluginManager)
|
||||||
|
private pluginManager: pluginApi.PluginManager
|
||||||
|
|
||||||
private pipeline: any
|
private pipeline: any;
|
||||||
|
private socketIOServer: SocketIOServer;
|
||||||
|
|
||||||
@cmd()
|
@cmd()
|
||||||
mconsole(sender: any, command: string, args: string[]) {
|
mconsole(sender: any, command: string, args: string[]) {
|
||||||
switch (args[0]) {
|
if (args[0] == 'reload') {
|
||||||
case "reload":
|
// @ts-ignore
|
||||||
this.PluginManager.reload(this)
|
require.clear('websocket');
|
||||||
break
|
this.pluginManager.reload(this);
|
||||||
default:
|
return
|
||||||
}
|
}
|
||||||
|
let tfunc = new Function('pipeline', args.join(' '))
|
||||||
|
tfunc.apply(this, [this.pipeline])
|
||||||
}
|
}
|
||||||
|
|
||||||
enable() {
|
enable() {
|
||||||
MiaoConsole.GlobalLogger = this.logger
|
let count = 0;
|
||||||
MiaoConsole.GlobalContainer = this.container
|
let wait = this.task.create(() => {
|
||||||
|
this.pipeline = this.server.getNettyPipeline()
|
||||||
|
if (this.pipeline) {
|
||||||
|
wait.cancel()
|
||||||
|
this.createSocketIOServer()
|
||||||
|
this.startSocketIOServer()
|
||||||
|
}
|
||||||
|
if (count > 30) { wait.cancel() }
|
||||||
|
count++
|
||||||
|
}).later(20).timer(40).submit()
|
||||||
}
|
}
|
||||||
|
|
||||||
disable() {
|
disable() {
|
||||||
if (this.pipeline) {
|
this.socketIOServer?.close()
|
||||||
if (this.pipeline.names().contains('miao_detect')) {
|
if (this.container.isBound(io.Instance)) {
|
||||||
this.pipeline.remove('miao_detect')
|
this.container.unbind(io.Instance)
|
||||||
}
|
|
||||||
clients.forEach(c => c.close())
|
|
||||||
this.container.unbind(MessageHandle)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bukkitenable() {
|
createSocketIOServer() {
|
||||||
let Bukkit = Java.type('org.bukkit.Bukkit')
|
this.socketIOServer = io(this.pipeline, {
|
||||||
let consoleServer = reflect.on(Bukkit.getServer()).get('console').get()
|
path: '/ws',
|
||||||
this.reflectChannel(this.reflectPromise(consoleServer))
|
root: '/home/project/TSWorkSpace/ms/packages/plugins/public'
|
||||||
this.injectMiaoDetect()
|
});
|
||||||
|
this.container.bind(io.Instance).toConstantValue(this.socketIOServer)
|
||||||
}
|
}
|
||||||
|
|
||||||
spongeenable() {
|
startSocketIOServer() {
|
||||||
let Sponge = Java.type('org.spongepowered.api.Sponge')
|
let namespace = this.socketIOServer.of('/MiaoConsole')
|
||||||
let consoleServer = reflect.on(Sponge.getServer()).get()
|
namespace.on('connect', (client: SocketIOSocket) => {
|
||||||
this.reflectChannel(this.reflectPromise(consoleServer))
|
this.logger.console(`§6客户端 §b${client.id} §a新建连接...`)
|
||||||
this.injectMiaoDetect()
|
client.on('type', (fn) => {
|
||||||
}
|
fn && fn(this.serverType)
|
||||||
|
client.emit('log', `Currect Server Version is ${this.server.getVersion()}`)
|
||||||
bungeeenable() {
|
})
|
||||||
let wait = this.Task.create(() => {
|
client.on('command', (cmd) => {
|
||||||
|
setTimeout(() => this.server.dispatchConsoleCommand(cmd), 0)
|
||||||
|
client.emit('log', `§6命令: §b${cmd} §a执行成功!`)
|
||||||
|
})
|
||||||
|
client.on('exec', (code) => {
|
||||||
try {
|
try {
|
||||||
// @ts-ignore
|
client.emit('log', this.runCode(code, namespace, client))
|
||||||
this.pipeline = reflect.on(base.getInstance().getProxy()).get('listeners').get().toArray()[0].pipeline()
|
|
||||||
this.injectMiaoDetect()
|
|
||||||
wait.cancel();
|
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
this.logger.warn('Wait BungeeCord start ready to get netty channel pipeline. Err: ' + ex)
|
client.emit('log', '§4代码执行异常\n' + console.stack(ex).join('\n'))
|
||||||
}
|
}
|
||||||
}).later(300).timer(500).submit()
|
})
|
||||||
}
|
client.on('edit', (file: string, fn) => {
|
||||||
|
fn && fn(base.read(file), suffixMap[file.split('.', 2)[1]])
|
||||||
reflectPromise(consoleServer) {
|
})
|
||||||
for (const ref of refList) {
|
client.on('disconnect', () => {
|
||||||
try { return reflect.on(consoleServer).call(ref.server).get(ref.future).get().get(0) } catch (error) { }
|
this.logger.console(`§6客户端 §b${client.id} §c断开连接...`)
|
||||||
}
|
})
|
||||||
}
|
})
|
||||||
|
|
||||||
reflectChannel(promise) {
|
|
||||||
if (!promise) { throw Error(`Can't found ServerConnection or ChannelFuture !`) }
|
|
||||||
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
|
||||||
}
|
|
||||||
|
|
||||||
injectMiaoDetect() {
|
|
||||||
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!')
|
this.logger.info('Netty Channel Pipeline Inject MiaoDetectHandler Successful!')
|
||||||
}
|
}
|
||||||
|
|
||||||
onmessage(ctx: any, msg: any) {
|
private runCode(code: string, namespace: any, client: any) {
|
||||||
let text: string = msg.text()
|
let tfunc = new Function('namespace', 'client', `
|
||||||
const [type, content] = text.split(SPLIT_LINE)
|
var reflect = require('@ms/common/dist/reflect');
|
||||||
try {
|
var tempconcent = '';
|
||||||
var result = this[type](ctx, content)
|
function print(text) {
|
||||||
} catch (ex) {
|
tempconcent += text + "\\n"
|
||||||
var result = '§4代码执行异常\n' + console.stack(ex).join('\n')
|
|
||||||
}
|
}
|
||||||
result && this.sendResult(ctx, "log", result)
|
var result = eval(${JSON.stringify(code)});
|
||||||
}
|
return tempconcent + result
|
||||||
|
`)
|
||||||
execCommand(ctx: any, cmd: string) {
|
return this.task.callSyncMethod(() => tfunc.apply(this, [namespace, client])) + ''
|
||||||
setTimeout(() => this.Server.dispatchConsoleCommand(cmd), 0)
|
|
||||||
return `§6命令: §b${cmd} §a执行成功!`
|
|
||||||
}
|
|
||||||
|
|
||||||
execCode(ctx: any, code: string) {
|
|
||||||
return this.Task.callSyncMethod(() => eval(code)) + '';
|
|
||||||
}
|
|
||||||
|
|
||||||
execDetect(ctx: any, cmd: string) {
|
|
||||||
switch (cmd) {
|
|
||||||
case "type":
|
|
||||||
this.sendResult(ctx, "type", this.ServerType)
|
|
||||||
return `Currect Server Version is ${this.Server.getVersion()}`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
sendResult(ctx: any, type: string, msg: string) {
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -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 { plugin, interfaces, cmd } from "@ms/plugin";
|
||||||
|
|
||||||
import http from '@ms/common/dist/http'
|
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 })
|
@plugin({ name: 'MiaoPluginManager', prefix: 'MPM', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
export class MiaoPluginManager extends interfaces.Plugin {
|
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()
|
@cmd()
|
||||||
mpman(sender: any, command: string, args: string[]) {
|
mpman(sender: any, command: string, args: string[]) {
|
||||||
|
|
||||||
}
|
}
|
||||||
@cmd()
|
@cmd()
|
||||||
bktman(sender: any, command: string, args: string[]) {
|
bktman(sender: any, command: string, args: string[]) {
|
||||||
switch (args[0]) {
|
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 "s":
|
||||||
case "search":
|
case "search":
|
||||||
if (args[1]) {
|
this.logger.sender(sender, `§6正在从 §a${api.name()} §6搜索插件 §b${args[0]} §6请稍候...`)
|
||||||
let result = http.get('https://servermods.forgesvc.net/servermods/projects?search=' + args[1])
|
let result = api.search(args[0])
|
||||||
for (let item of result) {
|
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;
|
break;
|
||||||
|
case "d":
|
||||||
|
case "download":
|
||||||
|
http.download(api.download(Number(args[0])), fs.concat(this.server.getPluginsFolder(), args[1] + '.jar'))
|
||||||
|
break;
|
||||||
default:
|
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`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import { plugin as pluginApi, task, server } from '@ms/api'
|
import { plugin as pluginApi, task, server } from '@ms/api'
|
||||||
|
|
||||||
import * as fs from '@ms/common/dist/fs'
|
import { Translate } from '@ms/i18n'
|
||||||
import { inject } from '@ms/container';
|
import { inject } from '@ms/container';
|
||||||
import { interfaces, plugin, cmd, tab } from '@ms/plugin'
|
import { interfaces, plugin, cmd, tab } from '@ms/plugin'
|
||||||
|
|
||||||
|
import * as fs from '@ms/common/dist/fs'
|
||||||
|
import http from '@ms/common/dist/http'
|
||||||
|
|
||||||
let help = [
|
let help = [
|
||||||
'§6========= §6[§aMiaoScriptPackageManager§6] 帮助 §aBy §b喵♂呜 §6=========',
|
'§6========= §6[§aMiaoScriptPackageManager§6] 帮助 §aBy §b喵♂呜 §6=========',
|
||||||
'§6/mpm §ainstall §e<插件名称> §6- §3安装插件',
|
'§6/mpm §ainstall §e<插件名称> §6- §3安装插件',
|
||||||
@@ -17,6 +20,20 @@ let help = [
|
|||||||
'§6/mpm §crestart §6- §4重启MiaoScript脚本引擎'
|
'§6/mpm §crestart §6- §4重启MiaoScript脚本引擎'
|
||||||
];
|
];
|
||||||
|
|
||||||
|
let langMap = {
|
||||||
|
'list.header.install': '§6当前 §bMiaoScript §6已安装下列插件:',
|
||||||
|
'list.header': '§6当前 §bMiaoScriptPackageCenter §6中存在下列插件:',
|
||||||
|
'list.body': '§6插件名称: §b{name} §6版本: §a{version} §6作者: §3{author}',
|
||||||
|
'plugin.not.exists': '§6插件 §b{name} §c不存在!',
|
||||||
|
'plugin.unload.finish': '§6插件 §b{name} §a已卸载!',
|
||||||
|
'plugin.reload.finish': '§6插件 §b{name} §a重载完成!',
|
||||||
|
'plugin.name.empty': '§c请输入插件名称!',
|
||||||
|
'cloud.update.finish': '§6成功从 §aMiaoScriptPackageCenter §6获取到 §a{length} §6个插件!',
|
||||||
|
'cloud.not.exists': '§6当前 §aMiaoScriptPackageCenter §c不存在 §a{name} §c插件!'
|
||||||
|
}
|
||||||
|
|
||||||
|
let fallbackMap = langMap
|
||||||
|
|
||||||
@plugin({ name: 'MiaoScriptPackageManager', prefix: 'PM', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
@plugin({ name: 'MiaoScriptPackageManager', prefix: 'PM', version: '1.0.0', author: 'MiaoWoo', source: __filename })
|
||||||
export class MiaoScriptPackageManager extends interfaces.Plugin {
|
export class MiaoScriptPackageManager extends interfaces.Plugin {
|
||||||
@inject(pluginApi.PluginManager)
|
@inject(pluginApi.PluginManager)
|
||||||
@@ -29,11 +46,16 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
private server: server.Server
|
private server: server.Server
|
||||||
|
|
||||||
private packageCache: any[] = [];
|
private packageCache: any[] = [];
|
||||||
private packageNameCache: any[] = [];
|
private packageNameCache: string[] = [];
|
||||||
|
|
||||||
|
private translate: Translate;
|
||||||
|
|
||||||
load() {
|
load() {
|
||||||
this.taskManager.create(() => {
|
this.translate = new Translate({
|
||||||
}).async().submit();
|
langMap,
|
||||||
|
fallbackMap
|
||||||
|
})
|
||||||
|
this.updateRepo(this.server.getConsoleSender())
|
||||||
}
|
}
|
||||||
|
|
||||||
@cmd()
|
@cmd()
|
||||||
@@ -41,91 +63,68 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
this.taskManager.create(() => this.main(sender, command, args)).async().submit();
|
this.taskManager.create(() => this.main(sender, command, args)).async().submit();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
i18n(sender: any, name: string, params?: any) {
|
||||||
|
this.logger.sender(sender, this.translate.translate(name, params))
|
||||||
|
}
|
||||||
|
|
||||||
main(sender: any, command: string, args: string[]) {
|
main(sender: any, command: string, args: string[]) {
|
||||||
if (!args[0] || args[1] === 'help') {
|
let cmdKey = 'cmd' + args[0]
|
||||||
|
if (!this[cmdKey] || args[0] === 'help') {
|
||||||
this.logger.sender(sender, help);
|
this.logger.sender(sender, help);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
switch (args[0]) {
|
args.shift()
|
||||||
case "list":
|
this[cmdKey](sender, ...args);
|
||||||
if (args[1]) {
|
}
|
||||||
this.logger.sender(sender, '§6当前 §bMiaoScript §6已安装下列插件:');
|
|
||||||
|
cmdlist(sender, type: string = 'cloud') {
|
||||||
|
if (type == "install") {
|
||||||
|
this.i18n(sender, 'list.header.install')
|
||||||
this.pluginManager.getPlugins().forEach((plugin) => {
|
this.pluginManager.getPlugins().forEach((plugin) => {
|
||||||
var desc = plugin.description;
|
this.i18n(sender, 'list.body', plugin.description);
|
||||||
this.logger.sender(sender, `§6插件名称: §b${desc.name} §6版本: §a${desc.version || '1.0'} §6作者: §3${desc.author || '未知'}`)
|
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
this.logger.sender(sender, '§6当前 §bMiaoScriptPackageCenter §6中存在下列插件:');
|
this.i18n(sender, 'list.header')
|
||||||
for (var pkgName in this.packageCache) {
|
for (var pkgName in this.packageCache) {
|
||||||
var pkg = this.packageCache[pkgName];
|
this.i18n(sender, 'list.body', this.packageCache[pkgName]);
|
||||||
// console.sender(sender, '§6插件名称: §b%s §6版本: §a%s §6作者: §3%s'.format(pkg.name, pkg.version || '1.0', pkg.author || '未知'))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
|
||||||
case "install":
|
|
||||||
// if (args.length > 1) {
|
|
||||||
// download(sender, args[1]);
|
|
||||||
// } else {
|
|
||||||
// console.sender(sender, '§c请输入插件名称!')
|
|
||||||
// }
|
|
||||||
break;
|
|
||||||
case "uninstall":
|
|
||||||
break;
|
|
||||||
case "update":
|
|
||||||
// if (args.length > 1) {
|
|
||||||
// update(sender, args[1]);
|
|
||||||
// } else {
|
|
||||||
// load();
|
|
||||||
// console.sender(sender, "§a仓库缓存刷新成功 共存在 §b" + Object.keys(packageCache).length + " §a个插件!")
|
|
||||||
// }
|
|
||||||
break;
|
|
||||||
case "upgrade":
|
|
||||||
if (args[3] === "engine") {
|
|
||||||
fs.del(fs.concat(root, '', ''))
|
|
||||||
}
|
}
|
||||||
break;
|
|
||||||
case "delete":
|
cmdinstall(sender: any, name: string) {
|
||||||
// if (args.length > 1) {
|
if (!name) { return this.i18n(sender, 'plugin.name.empty') }
|
||||||
// del(sender, args[1]);
|
this.download(sender, name);
|
||||||
// } else {
|
|
||||||
// console.sender(sender, '§c请输入插件名称!')
|
|
||||||
// }
|
|
||||||
break;
|
|
||||||
case "load":
|
|
||||||
if (args.length > 1) {
|
|
||||||
var pname = args[1];
|
|
||||||
if (!this.pluginManager.getPlugins().has(pname)) {
|
|
||||||
this.logger.sender(sender, `§6插件 §b${pname} §c不存在!`)
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
this.pluginManager.load(pname)
|
|
||||||
this.pluginManager.enable(pname)
|
cmdupdate(sender: any, name: string) {
|
||||||
this.logger.sender(sender, `§6插件 §b${pname} §a已加载!`)
|
if (name) {
|
||||||
|
this.update(sender, name);
|
||||||
|
} else {
|
||||||
|
this.updateRepo(sender)
|
||||||
}
|
}
|
||||||
break;
|
|
||||||
case "unload":
|
|
||||||
if (args.length > 1) {
|
|
||||||
var pname = args[1];
|
|
||||||
if (!this.pluginManager.getPlugins().has(pname)) {
|
|
||||||
this.logger.sender(sender, `§6插件 §b${pname} §c不存在!`)
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
this.pluginManager.disable(pname)
|
|
||||||
this.logger.sender(sender, `§6插件 §b${pname} §a已卸载!`)
|
cmdunload(sender: any, name: string) {
|
||||||
|
if (this.checkPlugin(sender, name)) {
|
||||||
|
this.pluginManager.disable(name)
|
||||||
|
this.i18n(sender, 'plugin.unload.finish', { name })
|
||||||
}
|
}
|
||||||
break;
|
|
||||||
case "reload":
|
|
||||||
if (args.length > 1) {
|
|
||||||
var pname = args[1];
|
|
||||||
if (!this.pluginManager.getPlugins().has(pname)) {
|
|
||||||
this.logger.sender(sender, `§6插件 §b${pname} §c不存在!`)
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
this.pluginManager.reload(pname);
|
|
||||||
this.logger.sender(sender, `§6插件 §b${pname} §a重载完成!`)
|
cmdreload(sender: any, name: string) {
|
||||||
|
if (this.checkPlugin(sender, name)) {
|
||||||
|
this.pluginManager.reload(name);
|
||||||
|
this.i18n(sender, 'plugin.reload.finish', { name })
|
||||||
}
|
}
|
||||||
break;
|
}
|
||||||
case "restart":
|
|
||||||
|
checkPlugin(sender: any, name: string) {
|
||||||
|
if (name && this.pluginManager.getPlugins().has(name)) { return true }
|
||||||
|
this.i18n(sender, 'plugin.not.exists', { name })
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
cmdrestart(sender: any) {
|
||||||
if (this.serverType === "sponge") {
|
if (this.serverType === "sponge") {
|
||||||
setTimeout(() => this.server.dispatchConsoleCommand('sponge plugins reload'), 0)
|
setTimeout(() => this.server.dispatchConsoleCommand('sponge plugins reload'), 0)
|
||||||
return
|
return
|
||||||
@@ -139,9 +138,9 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
this.logger.sender(sender, "§3MiaoScript Engine §6Reload §cError! ERR: " + ex);
|
this.logger.sender(sender, "§3MiaoScript Engine §6Reload §cError! ERR: " + ex);
|
||||||
this.logger.sender(sender, this.logger.stack(ex));
|
this.logger.sender(sender, this.logger.stack(ex));
|
||||||
}
|
}
|
||||||
break;
|
}
|
||||||
case "run":
|
|
||||||
args.shift();
|
cmdrun(sender, ...args: any[]) {
|
||||||
try {
|
try {
|
||||||
var script = args.join(' ');
|
var script = args.join(' ');
|
||||||
this.logger.sender(sender, '§b运行脚本:§r', script);
|
this.logger.sender(sender, '§b运行脚本:§r', script);
|
||||||
@@ -149,26 +148,11 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
this.logger.sender(sender, this.logger.stack(ex));
|
this.logger.sender(sender, this.logger.stack(ex));
|
||||||
}
|
}
|
||||||
break;
|
}
|
||||||
case "create":
|
|
||||||
this.logger.sender(sender, `§4当前暂不支持生成插件模板!`);
|
update(sender: any, name: string) {
|
||||||
// var name = args[1];
|
if (!this.packageNameCache.includes(name)) {
|
||||||
// if (!name) {
|
this.i18n(sender, 'cloud.not.exists', { name })
|
||||||
// this.logger.sender(sender, '§4参数错误 /mpm create <插件名称> [作者] [版本] [主命令]');
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
// // var result = template.create(http.get(self.config.template)).render({
|
|
||||||
// // name: name,
|
|
||||||
// // author: args[2] || 'MiaoWoo',
|
|
||||||
// // version: args[3] || '1.0',
|
|
||||||
// // command: args[4] || name.toLowerCase(),
|
|
||||||
// // });
|
|
||||||
// // fs.save(fs.file(__dirname, name + '.js'), result);
|
|
||||||
// this.logger.sender(sender, '§6插件 §a' + name + ' §6已生成到插件目录...');
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
this.logger.sender(sender, help);
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,6 +161,8 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
if (args.length === 1) return ['list', 'install', 'update', 'upgrade', 'reload', 'restart', 'run', 'help', 'create'];
|
if (args.length === 1) return ['list', 'install', 'update', 'upgrade', 'reload', 'restart', 'run', 'help', 'create'];
|
||||||
if (args.length > 1) {
|
if (args.length > 1) {
|
||||||
switch (args[0]) {
|
switch (args[0]) {
|
||||||
|
case "list":
|
||||||
|
return ["install", "cloud"]
|
||||||
case "install":
|
case "install":
|
||||||
return this.packageNameCache;
|
return this.packageNameCache;
|
||||||
case "update":
|
case "update":
|
||||||
@@ -188,4 +174,19 @@ export class MiaoScriptPackageManager extends interfaces.Plugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
updateRepo(sender: any) {
|
||||||
|
this.taskManager.create(() => {
|
||||||
|
let result = http.get('http://ms.yumc.pw/api/plugin');
|
||||||
|
for (const pl of result.data) {
|
||||||
|
this.packageCache[pl.name] = pl;
|
||||||
|
}
|
||||||
|
this.packageNameCache = Object.keys(this.packageCache);
|
||||||
|
this.i18n(sender, 'cloud.update.finish', { length: this.packageNameCache.length })
|
||||||
|
}).async().submit();
|
||||||
|
}
|
||||||
|
|
||||||
|
download(sender, name) {
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,9 @@
|
|||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"baseUrl": "src",
|
"baseUrl": "src",
|
||||||
"outDir": "dist",
|
"outDir": "dist",
|
||||||
"skipLibCheck": true
|
"skipLibCheck": true,
|
||||||
|
"sourceMap": false,
|
||||||
|
"inlineSourceMap": true
|
||||||
},
|
},
|
||||||
"exclude": [
|
"exclude": [
|
||||||
"dist",
|
"dist",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/sponge",
|
"name": "@ms/sponge",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript api package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -24,12 +24,11 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/api": "^0.3.0",
|
"@ms/api": "^0.5.0",
|
||||||
"@ms/common": "^0.3.0",
|
"@ms/common": "^0.5.0",
|
||||||
"@ms/container": "^0.3.0",
|
"@ms/container": "^0.5.0"
|
||||||
"@ms/types": "^0.3.0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ export class SpongeChannel extends channel.Channel {
|
|||||||
}
|
}
|
||||||
let innerListener = new RawDataListener({
|
let innerListener = new RawDataListener({
|
||||||
handlePayload: (/* ChannelBuf */ data: any, /**RemoteConnection */ connection: any, /**Platform.Type */ side: any) => {
|
handlePayload: (/* ChannelBuf */ data: any, /**RemoteConnection */ connection: any, /**Platform.Type */ side: any) => {
|
||||||
listener(data.readBytes(data.available()))
|
listener(data.readBytes(data.available()), { data, connection, side })
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
this.channelMap.get(channel).addListener(innerListener);
|
this.channelMap.get(channel).addListener(innerListener);
|
||||||
|
|||||||
@@ -1,11 +1,22 @@
|
|||||||
import { server } from '@ms/api'
|
import { server, constants } from '@ms/api'
|
||||||
import { provideSingleton } from '@ms/container';
|
import { provideSingleton } from '@ms/container';
|
||||||
|
|
||||||
let Sponge = org.spongepowered.api.Sponge;
|
import * as reflect from '@ms/common/dist/reflect'
|
||||||
let TextSerializers = org.spongepowered.api.text.serializer.TextSerializers;
|
|
||||||
|
const Sponge = org.spongepowered.api.Sponge;
|
||||||
|
const TextSerializers = org.spongepowered.api.text.serializer.TextSerializers;
|
||||||
|
const File = Java.type("java.io.File");
|
||||||
|
|
||||||
@provideSingleton(server.Server)
|
@provideSingleton(server.Server)
|
||||||
export class SpongeServer implements server.Server {
|
export class SpongeServer implements server.Server {
|
||||||
|
private pluginsFolder: string;
|
||||||
|
private pipeline: any;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.pluginsFolder = new File(base.getInstance().getClass().getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile().getCanonicalPath()
|
||||||
|
this.reflectPipeline()
|
||||||
|
}
|
||||||
|
|
||||||
getPlayer(name: string) {
|
getPlayer(name: string) {
|
||||||
return Sponge.getServer().getPlayer(name).orElse(null)
|
return Sponge.getServer().getPlayer(name).orElse(null)
|
||||||
}
|
}
|
||||||
@@ -30,10 +41,41 @@ export class SpongeServer implements server.Server {
|
|||||||
dispatchConsoleCommand(command: string): boolean {
|
dispatchConsoleCommand(command: string): boolean {
|
||||||
return Sponge.getCommandManager().process(Sponge.getServer().getConsole(), command).getQueryResult()
|
return Sponge.getCommandManager().process(Sponge.getServer().getConsole(), command).getQueryResult()
|
||||||
}
|
}
|
||||||
|
getPluginsFolder(): string {
|
||||||
|
return this.pluginsFolder;
|
||||||
|
}
|
||||||
|
getNativePluginManager() {
|
||||||
|
return Sponge.getPluginManager() as any;
|
||||||
|
}
|
||||||
|
getNettyPipeline() {
|
||||||
|
return this.pipeline;
|
||||||
|
}
|
||||||
sendJson(sender: string | any, json: string): void {
|
sendJson(sender: string | any, json: string): void {
|
||||||
if (typeof sender === "string") {
|
if (typeof sender === "string") {
|
||||||
sender = this.getPlayer(sender)
|
sender = this.getPlayer(sender)
|
||||||
}
|
}
|
||||||
sender.sendMessage(TextSerializers.JSON.deserialize(json))
|
sender.sendMessage(TextSerializers.JSON.deserialize(json))
|
||||||
}
|
}
|
||||||
|
private reflectPipeline() {
|
||||||
|
let consoleServer = reflect.on(Sponge.getServer()).get()
|
||||||
|
let connection: any;
|
||||||
|
let promise: any;
|
||||||
|
for (const method of constants.Reflect.Method.getServerConnection) {
|
||||||
|
try {
|
||||||
|
connection = reflect.on(consoleServer).call(method).get()
|
||||||
|
if (connection.class.name.indexOf('ServerConnection') !== -1) { break; }
|
||||||
|
connection = undefined;
|
||||||
|
} catch (error) { }
|
||||||
|
}
|
||||||
|
if (!connection) { console.error("Can't found ServerConnection!"); return }
|
||||||
|
for (const field of constants.Reflect.Field.listeningChannels) {
|
||||||
|
try {
|
||||||
|
promise = reflect.on(connection).get(field).get().get(0);
|
||||||
|
if (promise.class.name.indexOf('Promise') !== -1) { break; }
|
||||||
|
promise = undefined;
|
||||||
|
} catch (error) { }
|
||||||
|
}
|
||||||
|
if (!promise) { console.error("Can't found listeningChannels!"); return }
|
||||||
|
this.pipeline = reflect.on(promise).get('channel').get().pipeline()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { task, plugin } from '@ms/api'
|
import { task, plugin } from '@ms/api'
|
||||||
import { inject, provideSingleton } from '@ms/container';
|
import { inject, provideSingleton, postConstruct } from '@ms/container';
|
||||||
|
|
||||||
const Sponge = Java.type("org.spongepowered.api.Sponge");
|
const Sponge = Java.type("org.spongepowered.api.Sponge");
|
||||||
const Task = Java.type("org.spongepowered.api.scheduler.Task");
|
const Task = Java.type("org.spongepowered.api.scheduler.Task");
|
||||||
@@ -11,16 +11,23 @@ const TimeUnit = Java.type('java.util.concurrent.TimeUnit');
|
|||||||
export class SpongeTaskManager implements task.TaskManager {
|
export class SpongeTaskManager implements task.TaskManager {
|
||||||
@inject(plugin.PluginInstance)
|
@inject(plugin.PluginInstance)
|
||||||
private pluginInstance: any;
|
private pluginInstance: any;
|
||||||
|
private syncExecutor: any;
|
||||||
|
|
||||||
|
@postConstruct()
|
||||||
|
initialize() {
|
||||||
|
this.syncExecutor = Sponge.getScheduler().createSyncExecutor(this.pluginInstance)
|
||||||
|
}
|
||||||
|
|
||||||
create(func: Function): task.Task {
|
create(func: Function): task.Task {
|
||||||
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
if (Object.prototype.toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
|
||||||
return new SpongeTask(this.pluginInstance, func);
|
return new SpongeTask(this.pluginInstance, func);
|
||||||
}
|
}
|
||||||
callSyncMethod(func: Function): any {
|
callSyncMethod(func: Function): any {
|
||||||
return Sponge.getScheduler()
|
|
||||||
.createSyncExecutor(this.pluginInstance)
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
.schedule(new Callable({ call: () => func() }), java.lang.Long.valueOf(0), TimeUnit.NANOSECONDS).get()
|
return this.syncExecutor.schedule(new Callable({ call: () => func() }), java.lang.Long.valueOf(0), TimeUnit.NANOSECONDS).get()
|
||||||
|
}
|
||||||
|
disable() {
|
||||||
|
Sponge.getScheduler().getScheduledTasks(this.pluginInstance).forEach((task: task.Cancelable) => task.cancel())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
4
packages/types/dist/index.d.ts
vendored
Normal file
4
packages/types/dist/index.d.ts
vendored
Normal 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" />
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
|
||||||
"name": "@ms/types",
|
"name": "@ms/types",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript types package",
|
"description": "MiaoScript types package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
@@ -13,6 +12,7 @@
|
|||||||
"homepage": "https://github.com/circlecloud/ms.git",
|
"homepage": "https://github.com/circlecloud/ms.git",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
|
"types": "dist/index.d.ts",
|
||||||
"publishConfig": {
|
"publishConfig": {
|
||||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@ms/websocket",
|
"name": "@ms/websocket",
|
||||||
"version": "0.3.0",
|
"version": "0.5.0",
|
||||||
"description": "MiaoScript api package",
|
"description": "MiaoScript websocket package",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"miaoscript",
|
"miaoscript",
|
||||||
"minecraft",
|
"minecraft",
|
||||||
@@ -24,11 +24,9 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"reflect-metadata": "^0.1.13",
|
"reflect-metadata": "^0.1.13",
|
||||||
"rimraf": "^3.0.2",
|
"rimraf": "^3.0.2",
|
||||||
"typescript": "^3.8.2"
|
"typescript": "^3.8.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ms/api": "^0.3.0",
|
"@ms/nashorn": "^0.5.0"
|
||||||
"@ms/common": "^0.3.0"
|
}
|
||||||
},
|
|
||||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +1,46 @@
|
|||||||
import '@ms/nashorn'
|
/// <reference types="@ms/nashorn" />
|
||||||
|
|
||||||
|
import { Server, ServerOptions } from './socket-io'
|
||||||
|
|
||||||
|
interface SocketIOStatic {
|
||||||
|
/**
|
||||||
|
* Default Server constructor
|
||||||
|
*/
|
||||||
|
(): Server;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new Server
|
||||||
|
* @param srv The HTTP server that we're going to bind to
|
||||||
|
* @param opts An optional parameters object
|
||||||
|
*/
|
||||||
|
(srv: any, opts?: ServerOptions): Server;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new Server
|
||||||
|
* @param port A port to bind to, as a number, or a string
|
||||||
|
* @param An optional parameters object
|
||||||
|
*/
|
||||||
|
(port: string | number, opts?: ServerOptions): Server;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new Server
|
||||||
|
* @param A parameters object
|
||||||
|
*/
|
||||||
|
(opts: ServerOptions): Server;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Backwards compatibility
|
||||||
|
* @see io().listen()
|
||||||
|
*/
|
||||||
|
listen?: SocketIOStatic;
|
||||||
|
}
|
||||||
|
|
||||||
|
type SocketStatic = SocketIOStatic & { Instance?: symbol }
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
let io: SocketStatic = function (pipeline: any, options: ServerOptions) {
|
||||||
|
return new Server(pipeline, options)
|
||||||
|
}
|
||||||
|
io.Instance = Symbol("@ms/websocket")
|
||||||
|
export default io
|
||||||
|
export * from './socket-io'
|
||||||
|
|||||||
@@ -1,20 +1,19 @@
|
|||||||
/// <reference types="@ms/ployfill" />
|
|
||||||
|
|
||||||
const TypeParameterMatcher = Java.type('io.netty.util.internal.TypeParameterMatcher')
|
const TypeParameterMatcher = Java.type('io.netty.util.internal.TypeParameterMatcher')
|
||||||
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
|
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
|
||||||
const FullHttpRequestMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.FullHttpRequest'))
|
const FullHttpRequestMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.FullHttpRequest'))
|
||||||
|
|
||||||
export default abstract class HttpRequestHandlerAdapter {
|
export abstract class HttpRequestHandlerAdapter {
|
||||||
private _Handler;
|
private _Handler;
|
||||||
constructor() {
|
constructor() {
|
||||||
this._Handler == Java.extend(SimpleChannelInboundHandler, {
|
let HttpRequestHandlerAdapterImpl = Java.extend(SimpleChannelInboundHandler, {
|
||||||
acceptInboundMessage: (msg: any) => {
|
acceptInboundMessage: (msg: any) => {
|
||||||
return FullHttpRequestMatcher.match(msg)
|
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() {
|
getHandler() {
|
||||||
return this._Handler;
|
return this._Handler;
|
||||||
}
|
}
|
||||||
|
|||||||
3
packages/websocket/src/netty/index.ts
Normal file
3
packages/websocket/src/netty/index.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export * from './text_websocket_frame'
|
||||||
|
export * from './websocket'
|
||||||
|
export * from './httprequest'
|
||||||
@@ -1,22 +1,23 @@
|
|||||||
/// <reference types="@ms/ployfill" />
|
|
||||||
|
|
||||||
const TypeParameterMatcher = Java.type('io.netty.util.internal.TypeParameterMatcher')
|
const TypeParameterMatcher = Java.type('io.netty.util.internal.TypeParameterMatcher')
|
||||||
const TextWebSocketFrameMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.websocketx.TextWebSocketFrame'))
|
const TextWebSocketFrameMatcher = TypeParameterMatcher.get(base.getClass('io.netty.handler.codec.http.websocketx.TextWebSocketFrame'))
|
||||||
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
|
const SimpleChannelInboundHandler = Java.type('io.netty.channel.SimpleChannelInboundHandler')
|
||||||
|
|
||||||
export default abstract class TextWebSocketFrameHandlerAdapter {
|
export abstract class TextWebSocketFrameHandlerAdapter {
|
||||||
private _Handler;
|
private _Handler;
|
||||||
constructor() {
|
constructor() {
|
||||||
this._Handler == Java.extend(SimpleChannelInboundHandler, {
|
let TextWebSocketFrameHandlerAdapterImpl = Java.extend(SimpleChannelInboundHandler, {
|
||||||
userEventTriggered: this.userEventTriggered,
|
userEventTriggered: this.userEventTriggered.bind(this),
|
||||||
acceptInboundMessage: (msg: any) => {
|
acceptInboundMessage: (msg: any) => {
|
||||||
return TextWebSocketFrameMatcher.match(msg)
|
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 userEventTriggered(ctx: any, evt: any);
|
||||||
abstract channelRead0(ctx: any, msg: any);
|
abstract channelRead0(ctx: any, msg: any);
|
||||||
|
abstract exceptionCaught(ctx: any, cause: Error);
|
||||||
getHandler() {
|
getHandler() {
|
||||||
return this._Handler;
|
return this._Handler;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,16 @@
|
|||||||
import '@ms/api'
|
|
||||||
|
|
||||||
const MiaoWebSocket = 'miaowebsocket'
|
|
||||||
const CharsetUtil = Java.type('io.netty.util.CharsetUtil')
|
|
||||||
const ChannelInboundHandlerAdapter = Java.type('io.netty.channel.ChannelInboundHandlerAdapter')
|
const ChannelInboundHandlerAdapter = Java.type('io.netty.channel.ChannelInboundHandlerAdapter')
|
||||||
|
|
||||||
export default abstract class WebSocketHandlerAdapter {
|
export abstract class WebSocketHandlerAdapter {
|
||||||
private _Handler;
|
private _Handler;
|
||||||
constructor() {
|
constructor() {
|
||||||
this._Handler = Java.extend(ChannelInboundHandlerAdapter, {
|
let ChannelInboundHandlerAdapterImpl = Java.extend(ChannelInboundHandlerAdapter, {
|
||||||
channelRead: this.channelRead
|
channelRead: this.channelRead.bind(this),
|
||||||
|
exceptionCaught: this.exceptionCaught.bind(this)
|
||||||
})
|
})
|
||||||
|
this._Handler = new ChannelInboundHandlerAdapterImpl()
|
||||||
}
|
}
|
||||||
abstract channelRead(ctx: any, msg: any);
|
abstract channelRead(ctx: any, channel: any);
|
||||||
|
abstract exceptionCaught(ctx: any, cause: Error);
|
||||||
getHandler() {
|
getHandler() {
|
||||||
return this._Handler;
|
return this._Handler;
|
||||||
}
|
}
|
||||||
|
|||||||
40
packages/websocket/src/server/client.ts
Normal file
40
packages/websocket/src/server/client.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { EventEmitter } from 'events'
|
||||||
|
import { SocketIO } from 'socket-io/interfaces';
|
||||||
|
import { 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
22
packages/websocket/src/server/constants.ts
Normal file
22
packages/websocket/src/server/constants.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
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"
|
||||||
|
}
|
||||||
|
|
||||||
|
let RequestAttributeKey: any
|
||||||
|
try { RequestAttributeKey = AttributeKey.valueOf('request') } catch (error) { }
|
||||||
|
export enum AttributeKeys {
|
||||||
|
Request = RequestAttributeKey
|
||||||
|
}
|
||||||
61
packages/websocket/src/server/httprequest.ts
Normal file
61
packages/websocket/src/server/httprequest.ts
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
48
packages/websocket/src/server/index.ts
Normal file
48
packages/websocket/src/server/index.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { EventEmitter } from 'events'
|
||||||
|
|
||||||
|
import { NettyClient } from './client'
|
||||||
|
import { ServerOptions } from '../socket-io'
|
||||||
|
import { ServerEvent, Keys } from './constants'
|
||||||
|
import { WebSocketDetect } from './websocket_detect'
|
||||||
|
import { WebSocketHandler } from './websocket_handler'
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
23
packages/websocket/src/server/text_websocket_frame.ts
Normal file
23
packages/websocket/src/server/text_websocket_frame.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { EventEmitter } from 'events'
|
||||||
|
import { ServerEvent } from './constants'
|
||||||
|
import { ServerOptions } from '../socket-io';
|
||||||
|
import { TextWebSocketFrameHandlerAdapter } from '../netty'
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
17
packages/websocket/src/server/websocket_detect.ts
Normal file
17
packages/websocket/src/server/websocket_detect.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
exceptionCaught(ctx: any, cause: Error) {
|
||||||
|
this.event.emit(ServerEvent.error, ctx, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
46
packages/websocket/src/server/websocket_handler.ts
Normal file
46
packages/websocket/src/server/websocket_handler.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { EventEmitter } from 'events'
|
||||||
|
|
||||||
|
import { Keys, ServerEvent } 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)
|
||||||
|
}
|
||||||
|
exceptionCaught(ctx: any, cause: Error) {
|
||||||
|
this.options.event.emit(ServerEvent.error, ctx, cause)
|
||||||
|
}
|
||||||
|
}
|
||||||
127
packages/websocket/src/socket-io/adapter.ts
Normal file
127
packages/websocket/src/socket-io/adapter.ts
Normal 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--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
103
packages/websocket/src/socket-io/client.ts
Normal file
103
packages/websocket/src/socket-io/client.ts
Normal 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);
|
||||||
|
};
|
||||||
|
}
|
||||||
208
packages/websocket/src/socket-io/index.ts
Normal file
208
packages/websocket/src/socket-io/index.ts
Normal file
@@ -0,0 +1,208 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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({
|
||||||
|
event: new EventEmitter(),
|
||||||
|
path: '/socket.io',
|
||||||
|
root: root + '/wwwroot'
|
||||||
|
}, 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
|
||||||
|
}
|
||||||
824
packages/websocket/src/socket-io/interfaces.ts
Normal file
824
packages/websocket/src/socket-io/interfaces.ts
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user