Compare commits
68 Commits
Author | SHA1 | Date |
---|---|---|
MiaoWoo | 8e807fc2e0 | |
MiaoWoo | 1aa042bef0 | |
MiaoWoo | d702d9e40d | |
MiaoWoo | 507431232b | |
MiaoWoo | 3e8d1f7029 | |
MiaoWoo | 9fac585e5e | |
MiaoWoo | 1d26a1e318 | |
MiaoWoo | 5f5df3452d | |
MiaoWoo | fce3c1a284 | |
MiaoWoo | 21b35b0036 | |
MiaoWoo | 2b7588cf04 | |
MiaoWoo | 4435a239d4 | |
MiaoWoo | 4cc5e75f1d | |
MiaoWoo | 188641d57a | |
MiaoWoo | 9a25362140 | |
MiaoWoo | 54eaae96bd | |
MiaoWoo | 5bf4b1c09e | |
MiaoWoo | 54bea62735 | |
MiaoWoo | 0e4ae5d74f | |
MiaoWoo | bdad4136ec | |
MiaoWoo | a0866c1085 | |
MiaoWoo | afd3f91a3f | |
MiaoWoo | e70c78a255 | |
MiaoWoo | 9cfac1672a | |
MiaoWoo | 9126ec8035 | |
MiaoWoo | 23bc6068b5 | |
MiaoWoo | 27b428fbe2 | |
MiaoWoo | c07f1131c4 | |
MiaoWoo | 002f2c47c6 | |
MiaoWoo | 8633d9ea95 | |
MiaoWoo | 07a5d0c8de | |
MiaoWoo | dd76e563c8 | |
MiaoWoo | 7b85ff5b7c | |
MiaoWoo | 359aeb9d63 | |
MiaoWoo | 3901d9fb5f | |
MiaoWoo | c2867da047 | |
MiaoWoo | 65832c9fae | |
MiaoWoo | d9dffa704d | |
MiaoWoo | b39f29de6a | |
MiaoWoo | 56334c6f6e | |
MiaoWoo | 72673b2a67 | |
MiaoWoo | 597bdb721a | |
MiaoWoo | 6e0456d777 | |
MiaoWoo | fb67b06230 | |
MiaoWoo | 203560dcf2 | |
MiaoWoo | 3f58f5992c | |
MiaoWoo | ac16754c9c | |
MiaoWoo | 42d637dd63 | |
MiaoWoo | df0d246136 | |
MiaoWoo | e563e1b507 | |
MiaoWoo | 3b822c613a | |
MiaoWoo | 2967c2a1fe | |
MiaoWoo | 1c579c9789 | |
MiaoWoo | 2fe9bce2ea | |
MiaoWoo | 496d278a93 | |
MiaoWoo | bdf674b678 | |
MiaoWoo | 67fe13deac | |
MiaoWoo | 30846cdc87 | |
MiaoWoo | d8d03149df | |
MiaoWoo | b6d7847a79 | |
MiaoWoo | 58f59f8260 | |
MiaoWoo | f3fa14990f | |
MiaoWoo | 15d1f8392b | |
MiaoWoo | b5fac23c5c | |
MiaoWoo | 148f6c28c4 | |
MiaoWoo | 880065495e | |
MiaoWoo | 7fc70a92d5 | |
MiaoWoo | df6da12a8a |
|
@ -1,8 +1,4 @@
|
|||
.yarn*
|
||||
.vscode
|
||||
.theia
|
||||
node_modules
|
||||
dist
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
packages/nashorn/docs
|
||||
!packages/types/dist
|
||||
|
|
25
.npmignore
25
.npmignore
|
@ -1,25 +0,0 @@
|
|||
src
|
||||
test
|
||||
typings
|
||||
bundled
|
||||
build
|
||||
coverage
|
||||
docs
|
||||
wiki
|
||||
gulpfile.js
|
||||
bower.json
|
||||
karma.conf.js
|
||||
tsconfig.json
|
||||
typings.json
|
||||
CONTRIBUTING.md
|
||||
ISSUE_TEMPLATE.md
|
||||
PULL_REQUEST_TEMPLATE.md
|
||||
tslint.json
|
||||
wallaby.js
|
||||
.travis.yml
|
||||
.gitignore
|
||||
.vscode
|
||||
.theia
|
||||
type_definitions
|
||||
tsconfig.tsbuildinfo
|
||||
*.tsbuildinfo
|
47
README.MD
47
README.MD
|
@ -8,27 +8,28 @@
|
|||
|
||||
```txt
|
||||
└─packages
|
||||
├─api 全平台兼容的接口
|
||||
├─core 核心代码 用于引导加载
|
||||
├─common 公共类库代码 例如 http reflect 模块
|
||||
├─client NodeJS的Minecraft客户端 用于调试插件
|
||||
├─container IOC容器 用于注入具体实现
|
||||
├─ployfill Nashorn 的一些自定义增强
|
||||
├─nashorn Nashorn 的类型定义
|
||||
├─bungee BungeeCordAPI内部实现
|
||||
├─bukkit BukkitAPI内部实现
|
||||
├─sponge SpongeAPI内部实现
|
||||
├─nukkit NukkitAPI内部实现
|
||||
├─plugin 插件管理器
|
||||
├─websocket Netty的WebSocket注入
|
||||
├─type Java的类型定义
|
||||
| ├─bungee BungeeCord类型定义
|
||||
| ├─bukkit Bukkit类型定义
|
||||
| ├─sponge Sponge类型定义
|
||||
| └─nukkit Nukkit类型定义
|
||||
└─plugins 这里当然是插件啦
|
||||
├─bungee 只兼容BungeeCord的插件
|
||||
├─bukkit 只兼容Bukkit的插件
|
||||
├─sponge 只兼容Sponge的插件
|
||||
└─nukkit 只兼容Nukkit的插件
|
||||
├─api 全平台兼容的接口
|
||||
├─core 核心代码 用于引导加载
|
||||
├─common 公共类库代码 例如 http reflect 模块
|
||||
├─compile 编译器相关功能
|
||||
├─client NodeJS 的 Minecraft 客户端 已迁移至 ms-client
|
||||
├─container IOC容器 用于注入具体实现
|
||||
├─database 数据库相关功能
|
||||
├─protocol 协议处理相关功能
|
||||
├─service 服务相关功能
|
||||
├─i18n 多语言环境相关支持
|
||||
├─polyfill Nashorn 的一些自定义增强
|
||||
├─nashorn Nashorn 的类型定义
|
||||
├─nodejs NodeJS 的部分 Java 实现
|
||||
├─bungee BungeeCordAPI 内部实现
|
||||
├─bukkit BukkitAPI 内部实现
|
||||
├─sponge SpongeAPI 内部实现
|
||||
├─nukkit NukkitAPI 内部实现
|
||||
├─molang MoLang 解析库
|
||||
├─qrcode 二维码相关类库
|
||||
├─plugin 插件管理器
|
||||
├─websocket WebSocket 相关实现
|
||||
| ├─client 基于 Netty 的 WebSocket 客户端
|
||||
| └─server 基于 Netty 的 WebSocket 服务端
|
||||
└─type 类型定义 已迁移到 @javatypes
|
||||
```
|
||||
|
|
23
lerna.json
23
lerna.json
|
@ -1,17 +1,12 @@
|
|||
{
|
||||
"version": "0.21.0",
|
||||
"useWorkspaces": true,
|
||||
"npmClient": "yarn",
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"command": {
|
||||
"run": {
|
||||
"stream": true
|
||||
},
|
||||
"publish": {
|
||||
"access": "public",
|
||||
"registry": "https://repo.yumc.pw/repository/npm-hosted/"
|
||||
}
|
||||
"version": "0.28.0-beta.10",
|
||||
"npmClient": "pnpm",
|
||||
"command": {
|
||||
"run": {
|
||||
"stream": true
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
|
|
30
package.json
30
package.json
|
@ -6,20 +6,30 @@
|
|||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"bs": "lerna bootstrap",
|
||||
"bs": "pnpm install",
|
||||
"clean": "lerna run clean",
|
||||
"watch": "lerna run watch --parallel",
|
||||
"build": "lerna run build",
|
||||
"ug": "yarn upgrade-interactive --latest",
|
||||
"ug": "pnpm up -r -i",
|
||||
"np": "./script/push.sh",
|
||||
"lsp": "npm login --registry=https://registry.npmjs.org --scope=@ccms",
|
||||
"lp": "lerna publish --registry https://registry.npmjs.org",
|
||||
"lpb": "lerna publish --registry https://registry.npmjs.org --canary --pre-dist-tag beta"
|
||||
"lsp": "npm login -scope=@ccms",
|
||||
"lp": "lerna publish --force-publish",
|
||||
"lpb": "lerna publish prerelease --preid beta --dist-tag beta --force-publish",
|
||||
"lpc": "lerna publish --canary --preid beta --pre-dist-tag beta --force-publish",
|
||||
"lpf": "lerna publish from-package --dist-tag beta --yes",
|
||||
"sync": "./script/sync.sh",
|
||||
"postpublish": "pnpm sync"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"devDependencies": {
|
||||
"lerna": "^4.0.0"
|
||||
"@ccms/nashorn": "^0.28.0-beta.3",
|
||||
"@javatypes/jdk": "^0.0.3",
|
||||
"@lerna-lite/cli": "^2.6.0",
|
||||
"@lerna-lite/publish": "^2.6.0",
|
||||
"@lerna-lite/run": "^2.6.0",
|
||||
"@types/node": "^20.8.8",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^5.0.5",
|
||||
"tslib": "^2.6.2",
|
||||
"typescript": "^5.2.2"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,35 +0,0 @@
|
|||
{
|
||||
"name": "@ccms/amqp",
|
||||
"version": "0.21.0",
|
||||
"description": "MiaoScript amqp package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.21.0",
|
||||
"@ccms/common": "^0.21.0",
|
||||
"@ccms/container": "^0.21.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.21.0",
|
||||
"@javatypes/amqp-client": "^0.0.3",
|
||||
"@javatypes/spring-amqp": "^0.0.3",
|
||||
"@javatypes/spring-rabbit": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
}
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
import { ConnectionFactoryAdapter } from "./connection"
|
||||
import { RabbitTemplateAdapter } from "./template"
|
||||
import { JSClass } from "@ccms/container"
|
||||
|
||||
export const RabbitAdmin = Java.type('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
|
||||
export class RabbitAdminAdapter {
|
||||
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
private RabbitAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
constructor(config: RabbitTemplateAdapter | org.springframework.amqp.rabbit.core.RabbitTemplate | ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory) {
|
||||
this._Handler = new RabbitAdmin((config instanceof RabbitTemplateAdapter || config instanceof ConnectionFactoryAdapter) ? config.getHandler() : config)
|
||||
}
|
||||
getHandler(): org.springframework.amqp.rabbit.core.RabbitAdmin {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
|
@ -1,30 +0,0 @@
|
|||
export const ConfirmCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback')
|
||||
export const ReturnCallback = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback')
|
||||
|
||||
export abstract class ConfirmCallbackAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback
|
||||
constructor() {
|
||||
let ConfirmCallbackImpl = Java.extend(ReturnCallback, {
|
||||
confirm: (correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string) => this.confirm(correlationData, ack, cause)
|
||||
})
|
||||
this._Handler = new ConfirmCallbackImpl()
|
||||
}
|
||||
abstract confirm(correlationData: org.springframework.amqp.rabbit.connection.CorrelationData, ack: boolean, cause: string)
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class ReturnCallbackAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback
|
||||
constructor() {
|
||||
let ReturnCallbackImpl = Java.extend(ReturnCallback, {
|
||||
returnedMessage: (message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string) => this.returnedMessage(message, replyCode, replyText, exchange, routingKey)
|
||||
})
|
||||
this._Handler = new ReturnCallbackImpl()
|
||||
}
|
||||
abstract returnedMessage(message: org.springframework.amqp.core.Message, replyCode: number, replyText: string, exchange: string, routingKey: string)
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
|
@ -1,31 +0,0 @@
|
|||
import threadPool from '@ccms/common/dist/thread-pool'
|
||||
|
||||
export const ConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.ConnectionFactory')
|
||||
const CachingConnectionFactory = Java.type('org.springframework.amqp.rabbit.connection.CachingConnectionFactory')
|
||||
interface ConnectionConfig {
|
||||
url: string,
|
||||
username?: string,
|
||||
password?: string,
|
||||
publisherConfirms?: boolean
|
||||
cacheSize?: number
|
||||
}
|
||||
|
||||
export class ConnectionFactoryAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.connection.CachingConnectionFactory
|
||||
|
||||
constructor(config: ConnectionConfig) {
|
||||
if (!config.url) { throw new Error('Connection UrI Can\'t be undefiend!') }
|
||||
config = { publisherConfirms: true, cacheSize: 50, ...config }
|
||||
this._Handler = new CachingConnectionFactory(new java.net.URI(config.url))
|
||||
config.username && this._Handler.setUsername(config.username)
|
||||
config.password && this._Handler.setPassword(config.password)
|
||||
this._Handler.setPublisherConfirms(config.publisherConfirms)
|
||||
this._Handler.setExecutor(threadPool.create({
|
||||
groupName: '@ccms/amqp-rabbit'
|
||||
}))
|
||||
this._Handler.setChannelCacheSize(config.cacheSize)
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
|
@ -1,30 +0,0 @@
|
|||
import { ConnectionFactoryAdapter, ConnectionFactory } from "./connection"
|
||||
import { ChannelAwareMessageListenerAdapter, ChannelAwareMessageListener } from "./listener"
|
||||
|
||||
export const SimpleMessageListenerContainer = org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
||||
export const AcknowledgeMode = org.springframework.amqp.core.AcknowledgeMode
|
||||
interface ContainerConfig {
|
||||
connectionFactory: ConnectionFactoryAdapter | typeof ConnectionFactory
|
||||
queueNames: string[]
|
||||
messageListener: ChannelAwareMessageListenerAdapter | typeof ChannelAwareMessageListener
|
||||
maxConcurrentConsumers?: number
|
||||
concurrentConsumers?: number
|
||||
acknowledgeMode?: org.springframework.amqp.core.AcknowledgeMode
|
||||
}
|
||||
|
||||
export class MessageListenerContainerAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
|
||||
constructor(config: ContainerConfig) {
|
||||
config = { concurrentConsumers: 5, maxConcurrentConsumers: 10, acknowledgeMode: AcknowledgeMode.AUTO, ...config }
|
||||
this._Handler = new SimpleMessageListenerContainer(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
|
||||
//@ts-ignore
|
||||
this._Handler.setQueueNames(config.queueNames)
|
||||
this._Handler.setMaxConcurrentConsumers(config.maxConcurrentConsumers)
|
||||
this._Handler.setConcurrentConsumers(config.concurrentConsumers)
|
||||
this._Handler.setAcknowledgeMode(config.acknowledgeMode)
|
||||
this._Handler.setMessageListener(config.messageListener instanceof ChannelAwareMessageListenerAdapter ? config.messageListener.getHandler() : config.messageListener)
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
|
@ -1,37 +0,0 @@
|
|||
const JavaString = Java.type('java.lang.String')
|
||||
const MessageProperties = org.springframework.amqp.core.MessageProperties
|
||||
const Message = org.springframework.amqp.core.Message
|
||||
|
||||
export const MessageConverter = Java.type('org.springframework.amqp.support.converter.MessageConverter')
|
||||
|
||||
export class MessageConverterAdapter {
|
||||
private _Handler: org.springframework.amqp.support.converter.MessageConverter
|
||||
constructor() {
|
||||
var MessageConverterImpl = Java.extend(MessageConverter, {
|
||||
toMessage: (object: any, messageProperties: org.springframework.amqp.core.MessageProperties) => this.toMessage(object, messageProperties),
|
||||
fromMessage: (message: org.springframework.amqp.core.Message) => this.fromMessage(message)
|
||||
})
|
||||
this._Handler = new MessageConverterImpl()
|
||||
}
|
||||
toMessage(object: any, messageProperties: org.springframework.amqp.core.MessageProperties) {
|
||||
if (typeof object == "string") {
|
||||
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
|
||||
return new Message(new JavaString(object).getBytes(), messageProperties)
|
||||
} else {
|
||||
messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
return new Message(new JavaString(JSON.stringify(object)).getBytes(), messageProperties)
|
||||
}
|
||||
}
|
||||
fromMessage(message: org.springframework.amqp.core.Message) {
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_TEXT_PLAIN) {
|
||||
return new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding())
|
||||
}
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
||||
return JSON.parse(new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding()))
|
||||
}
|
||||
return message
|
||||
}
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
|
@ -1,7 +0,0 @@
|
|||
export * from './admin'
|
||||
export * from './callback'
|
||||
export * from './connection'
|
||||
export * from './container'
|
||||
export * from './converter'
|
||||
export * from './listener'
|
||||
export * from './template'
|
|
@ -1,49 +0,0 @@
|
|||
const JavaString = Java.type('java.lang.String')
|
||||
export const MessageProperties = org.springframework.amqp.core.MessageProperties
|
||||
export const ChannelAwareMessageListener = Java.type('org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener')
|
||||
export const AmqpRejectAndDontRequeueException = org.springframework.amqp.AmqpRejectAndDontRequeueException
|
||||
export const Channel: com.rabbitmq.client.Channel = Java.type('com.rabbitmq.client.Channel')
|
||||
export const Message = org.springframework.amqp.core.Message
|
||||
export type MessageHandler<T> = (content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => any
|
||||
export abstract class ChannelAwareMessageListenerAdapter<T = any> {
|
||||
private _Handler: org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener
|
||||
constructor(manual: boolean = false) {
|
||||
let ChannelAwareMessageListenerImpl = Java.extend(ChannelAwareMessageListener, {
|
||||
onMessage: (message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) => {
|
||||
let content = new JavaString(message.getBody(), message.getMessageProperties().getContentEncoding() || "UTF-8")
|
||||
try {
|
||||
if (message.getMessageProperties().getContentType() == MessageProperties.CONTENT_TYPE_JSON) {
|
||||
content = JSON.parse(content)
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (manual) {
|
||||
channel.basicReject(message.getMessageProperties().getDeliveryTag(), true)
|
||||
} else {
|
||||
throw new AmqpRejectAndDontRequeueException(`${error}`, error)
|
||||
}
|
||||
}
|
||||
manual ? this.manualOnMessage(content, message, channel) : this.onMessage(content, message, channel)
|
||||
}
|
||||
})
|
||||
this._Handler = new ChannelAwareMessageListenerImpl()
|
||||
}
|
||||
abstract onMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any
|
||||
onError(error: Error, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel): any { }
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
private manualOnMessage(content: T, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
|
||||
let deliveryTag = message.getMessageProperties().getDeliveryTag()
|
||||
try {
|
||||
if (this.onMessage(content, message, channel)) {
|
||||
channel.basicAck(deliveryTag, false)
|
||||
} else if (message.getMessageProperties().getRedelivered()) {
|
||||
channel.basicReject(deliveryTag, true)
|
||||
} else {
|
||||
channel.basicNack(deliveryTag, false, true)
|
||||
}
|
||||
} catch (error: any) {
|
||||
channel.basicReject(deliveryTag, this.onError(error, message, channel))
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,27 +0,0 @@
|
|||
import { MessageConverterAdapter } from "./converter"
|
||||
import { ConnectionFactoryAdapter } from "./connection"
|
||||
import { ConfirmCallbackAdapter, ReturnCallbackAdapter } from "./callback"
|
||||
|
||||
export const RabbitTemplate = Java.type('org.springframework.amqp.rabbit.core.RabbitTemplate')
|
||||
|
||||
interface TemplateConfig {
|
||||
connectionFactory: ConnectionFactoryAdapter | org.springframework.amqp.rabbit.connection.ConnectionFactory
|
||||
confirmCallback?: ConfirmCallbackAdapter
|
||||
returnCallback?: ReturnCallbackAdapter
|
||||
messageConverter?: MessageConverterAdapter
|
||||
}
|
||||
export class RabbitTemplateAdapter {
|
||||
private _Handler: org.springframework.amqp.rabbit.core.RabbitTemplate
|
||||
constructor(config: TemplateConfig) {
|
||||
config = { messageConverter: new MessageConverterAdapter(), ...config }
|
||||
console.debug(JSON.stringify(config))
|
||||
this._Handler = new RabbitTemplate(config.connectionFactory instanceof ConnectionFactoryAdapter ? config.connectionFactory.getHandler() : config.connectionFactory)
|
||||
config.returnCallback && this._Handler.setReturnCallback(config.returnCallback.getHandler())
|
||||
config.confirmCallback && this._Handler.setConfirmCallback(config.confirmCallback.getHandler())
|
||||
config.messageConverter && this._Handler.setMessageConverter(config.messageConverter.getHandler())
|
||||
}
|
||||
|
||||
getHandler() {
|
||||
return this._Handler
|
||||
}
|
||||
}
|
|
@ -1,89 +0,0 @@
|
|||
import { JSClass } from "@ccms/container"
|
||||
import { RabbitAdminAdapter, MessageListenerContainerAdapter, AcknowledgeMode, MessageHandler, ChannelAwareMessageListenerAdapter } from "./adapter"
|
||||
|
||||
export class AmqpAdmin {
|
||||
@JSClass('org.springframework.amqp.core.TopicExchange')
|
||||
private TopicExchange: typeof org.springframework.amqp.core.TopicExchange
|
||||
@JSClass('org.springframework.amqp.core.Queue')
|
||||
private Queue: typeof org.springframework.amqp.core.Queue
|
||||
@JSClass('org.springframework.amqp.core.Binding')
|
||||
private Binding: typeof org.springframework.amqp.core.Binding
|
||||
@JSClass('org.springframework.amqp.rabbit.core.RabbitAdmin')
|
||||
private RabbitAdmin: typeof org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
@JSClass('org.springframework.amqp.core.Binding.DestinationType')
|
||||
private DestinationType: org.springframework.amqp.core.Binding.DestinationType
|
||||
|
||||
private amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin
|
||||
|
||||
constructor(amqpAdmin: org.springframework.amqp.rabbit.core.RabbitAdmin | any) {
|
||||
if (amqpAdmin instanceof this.RabbitAdmin) {
|
||||
this.amqpAdmin = amqpAdmin
|
||||
} else if (amqpAdmin instanceof RabbitAdminAdapter) {
|
||||
this.amqpAdmin = amqpAdmin.getHandler()
|
||||
} else {
|
||||
this.amqpAdmin = new RabbitAdminAdapter(amqpAdmin).getHandler()
|
||||
}
|
||||
}
|
||||
|
||||
getHandler() {
|
||||
return this.amqpAdmin
|
||||
}
|
||||
|
||||
getQueueProperties(name: string) {
|
||||
return this.amqpAdmin.getQueueProperties(name)
|
||||
}
|
||||
|
||||
declareExchange(name: string) {
|
||||
let exchange = new this.TopicExchange(name, true, false)
|
||||
this.amqpAdmin.declareExchange(exchange)
|
||||
return this
|
||||
}
|
||||
|
||||
declareQueue(name: string) {
|
||||
let queue = new this.Queue(name, true)
|
||||
this.amqpAdmin.declareQueue(queue)
|
||||
return this
|
||||
}
|
||||
|
||||
declareBinding(queue: string, exchange: string, routerKey: string, argument: any = null) {
|
||||
let binding = new this.Binding(queue, org.springframework.amqp.core.Binding.DestinationType.QUEUE, exchange, routerKey, argument)
|
||||
this.amqpAdmin.declareBinding(binding)
|
||||
return this
|
||||
}
|
||||
|
||||
declareQueueAndBindExchange(queue: string, exchange: string, routerKey: string) {
|
||||
return this.declareQueue(queue).declareExchange(exchange).declareBinding(queue, exchange, routerKey)
|
||||
}
|
||||
|
||||
createContainer<T>(queue: string, listener: MessageHandler<T>, acknowledgeMode = AcknowledgeMode.AUTO) {
|
||||
let connection = this.amqpAdmin.getRabbitTemplate().getConnectionFactory()
|
||||
return new MessageListenerContainerAdapter({
|
||||
connectionFactory: connection,
|
||||
queueNames: [queue],
|
||||
messageListener: new SimpleMessageHandler(listener),
|
||||
acknowledgeMode: acknowledgeMode
|
||||
}).getHandler()
|
||||
}
|
||||
|
||||
send()
|
||||
send() {
|
||||
|
||||
}
|
||||
|
||||
getTemplate() {
|
||||
return this.amqpAdmin.getRabbitTemplate()
|
||||
}
|
||||
|
||||
close() {
|
||||
this.getTemplate().stop()
|
||||
}
|
||||
}
|
||||
|
||||
export class SimpleMessageHandler extends ChannelAwareMessageListenerAdapter {
|
||||
constructor(private handler: MessageHandler<any>) {
|
||||
super()
|
||||
}
|
||||
onMessage(content: any, message: org.springframework.amqp.core.Message, channel: com.rabbitmq.client.Channel) {
|
||||
return this.handler(content, message, channel)
|
||||
}
|
||||
}
|
|
@ -1,3 +0,0 @@
|
|||
export const METADATA_KEY = {
|
||||
|
||||
}
|
|
@ -1,34 +0,0 @@
|
|||
/// <reference types="@ccms/nashorn" />
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
/// <reference types="@javatypes/spring-amqp" />
|
||||
/// <reference types="@javatypes/spring-rabbit" />
|
||||
/// <reference types="@javatypes/amqp-client" />
|
||||
|
||||
import { amqp } from '@ccms/api'
|
||||
import { getContainer, reduceMetadata } from '@ccms/container'
|
||||
|
||||
function init() {
|
||||
const beanFactory = base.getInstance().getAutowireCapableBeanFactory()
|
||||
getContainer().bind(amqp.rabbit.Template).toDynamicValue((ctx) => {
|
||||
let metadata = reduceMetadata(ctx)
|
||||
if (!metadata.named) {
|
||||
return beanFactory.getBean('rabbitTemplate')
|
||||
} else {
|
||||
return beanFactory.getBean(`${metadata.named}-rabbitTemplate`)
|
||||
}
|
||||
})
|
||||
getContainer().bind(amqp.rabbit.Admin).toDynamicValue((ctx) => {
|
||||
let metadata = reduceMetadata(ctx)
|
||||
if (!metadata.named) {
|
||||
return beanFactory.getBean('rabbitAdmin')
|
||||
} else {
|
||||
return beanFactory.getBean(`${metadata.named}-rabbitAdmin`)
|
||||
}
|
||||
})
|
||||
}
|
||||
init()
|
||||
|
||||
export * from './admin'
|
||||
export * from './adapter'
|
||||
export * from './manager'
|
||||
export * from './constants'
|
|
@ -1,5 +0,0 @@
|
|||
export class AmqpListener {
|
||||
constructor() {
|
||||
|
||||
}
|
||||
}
|
|
@ -1,18 +0,0 @@
|
|||
import { amqp } from "@ccms/api"
|
||||
import { provideSingleton } from "@ccms/container"
|
||||
|
||||
import { ConnectionFactoryAdapter, RabbitTemplateAdapter, RabbitAdminAdapter } from "./adapter"
|
||||
import { AmqpAdmin } from "./admin"
|
||||
|
||||
@provideSingleton(amqp.Manager)
|
||||
export class AmqpManager {
|
||||
createConnection(url: string, username: string, password: string) {
|
||||
return new ConnectionFactoryAdapter({ url, username, password })
|
||||
}
|
||||
createTemplate(adapter: ConnectionFactoryAdapter) {
|
||||
return new RabbitTemplateAdapter({ connectionFactory: adapter })
|
||||
}
|
||||
createAdmin(adapter: RabbitTemplateAdapter | ConnectionFactoryAdapter) {
|
||||
return new AmqpAdmin(new RabbitAdminAdapter(adapter))
|
||||
}
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@ccms/api",
|
||||
"version": "0.21.0",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "MiaoScript api package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
|
@ -12,23 +12,26 @@
|
|||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/common": "^0.21.0",
|
||||
"@ccms/container": "^0.21.0",
|
||||
"@ccms/polyfill": "^0.21.0",
|
||||
"@ccms/common": "^0.28.0-beta.10",
|
||||
"@ccms/container": "^0.28.0-beta.10",
|
||||
"@ccms/i18n": "^0.28.0-beta.10",
|
||||
"@ccms/polyfill": "^0.28.0-beta.10",
|
||||
"base64-js": "^1.5.1",
|
||||
"source-map-builder": "^0.0.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/base64-js": "^1.3.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"@types/base64-js": "^1.3.0"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +0,0 @@
|
|||
export namespace amqp {
|
||||
export const Manager = Symbol('AmqpManager')
|
||||
export namespace rabbit {
|
||||
export const Admin = Symbol('RabbitAdmin')
|
||||
export const Template = Symbol('RabbitTemplate')
|
||||
}
|
||||
}
|
|
@ -5,6 +5,12 @@ import { plugin } from './plugin'
|
|||
export namespace command {
|
||||
@injectable()
|
||||
export abstract class Command {
|
||||
/**
|
||||
* first time script engine need optimize jit code
|
||||
* so ignore first slow exec notify
|
||||
*/
|
||||
private cacheSlowKeys = {};
|
||||
|
||||
/**
|
||||
* 注册插件命令
|
||||
* @param plugin 插件
|
||||
|
@ -46,36 +52,13 @@ export namespace command {
|
|||
try {
|
||||
let time = Date.now()
|
||||
let result = executor(sender, command, Java.from(args))
|
||||
let cost = Date.now() - time
|
||||
if (cost > global.ScriptSlowExecuteTime) {
|
||||
console.i18n("ms.api.command.execute.slow", {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
cost
|
||||
})
|
||||
}
|
||||
this.checkSlow(Date.now() - time,
|
||||
"ms.api.command.execute.slow",
|
||||
plugin, command, sender, args)
|
||||
return result
|
||||
} catch (ex: any) {
|
||||
console.i18n("ms.api.command.execute.error", {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
ex
|
||||
})
|
||||
console.ex(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)])
|
||||
}
|
||||
this.printError(ex, "ms.api.command.execute.error",
|
||||
plugin, command, sender, args)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
@ -87,42 +70,18 @@ export namespace command {
|
|||
var token = args[args.length - 1]
|
||||
var complete = tabCompleter(sender, command, Java.from(args)) || []
|
||||
let result = this.copyPartialMatches(complete, token)
|
||||
let cost = Date.now() - time
|
||||
if (cost > global.ScriptSlowExecuteTime) {
|
||||
console.i18n("ms.api.command.tab.completer.slow", {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
cost
|
||||
})
|
||||
}
|
||||
this.checkSlow(Date.now() - time,
|
||||
"ms.api.command.tab.completer.slow",
|
||||
plugin, command, sender, args)
|
||||
return result
|
||||
} catch (ex: any) {
|
||||
console.i18n("ms.api.command.tab.completer.error", {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
ex
|
||||
})
|
||||
console.ex(ex)
|
||||
if (sender.name != 'CONSOLE') {
|
||||
console.sender(sender, [
|
||||
i18n.translate("ms.api.command.tab.completer.error", {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
ex
|
||||
}),
|
||||
...console.stack(ex)
|
||||
])
|
||||
}
|
||||
this.printError(ex, "ms.api.command.tab.completer.error",
|
||||
plugin, command, sender, args)
|
||||
return []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected copyPartialMatches(complete: string[], token: string, array: string[] = []): string[] {
|
||||
if (!token) { return complete }
|
||||
complete.forEach(function (e) {
|
||||
|
@ -132,5 +91,35 @@ export namespace command {
|
|||
})
|
||||
return array
|
||||
}
|
||||
|
||||
private checkSlow(cost: number, key: string, plugin: plugin.Plugin, command: string, sender: any, args: any[]) {
|
||||
if (cost > global.ScriptSlowExecuteTime) {
|
||||
let completerKey = `${plugin.description.name}-${key}-${command}-${sender.name}`
|
||||
if (!this.cacheSlowKeys[completerKey]) {
|
||||
return this.cacheSlowKeys[completerKey] = cost
|
||||
}
|
||||
console.i18n(key, {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
cost
|
||||
})
|
||||
}
|
||||
}
|
||||
private printError(error: Error, key: string, plugin: plugin.Plugin, command: string, sender: any, args: any[]) {
|
||||
let message = i18n.translate(key, {
|
||||
player: sender.name,
|
||||
plugin: plugin.description.name,
|
||||
command,
|
||||
args: Java.from(args).join(' '),
|
||||
error
|
||||
})
|
||||
console.console(message)
|
||||
console.ex(error)
|
||||
if (sender.name != 'CONSOLE') {
|
||||
console.sender(sender, [message, ...console.stack(error)])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,7 +5,7 @@ import * as base64 from 'base64-js'
|
|||
const Arrays = Java.type('java.util.Arrays')
|
||||
const Level = Java.type('java.util.logging.Level')
|
||||
const Paths = Java.type('java.nio.file.Paths')
|
||||
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.nashorn.', 'org.openjdk.nashorn', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
|
||||
const ignoreLogPrefix = ['java.', 'javax.', 'sun.', 'net.minecraft.', 'org.bukkit.', 'jdk.internal.dynalink.', 'jdk.nashorn.', 'org.openjdk.nashorn', 'io.netty.', 'org.spongepowered.', 'org.apache', 'org.springframework']
|
||||
|
||||
enum LogLevel {
|
||||
ALL,
|
||||
|
@ -18,12 +18,112 @@ enum LogLevel {
|
|||
OFF
|
||||
}
|
||||
|
||||
const sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
||||
const sourceFileMaps: { [key: string]: string } = {}
|
||||
|
||||
global.setGlobal('MiaoScriptSourceMaps', sourceMaps)
|
||||
global.setGlobal('MiaoScriptSourceFileMaps', sourceFileMaps)
|
||||
|
||||
export namespace jsconsole {
|
||||
export function readSourceMap(fileName: string, lineNumber: any) {
|
||||
if (lineNumber == 1) return { fileName, lineNumber }
|
||||
try {
|
||||
if (fileName.endsWith('js') || fileName.endsWith('ms')) {
|
||||
if (sourceMaps[fileName] === undefined) {
|
||||
sourceMaps[fileName] = null
|
||||
let sourceLine = base.read(fileName).split('\n')
|
||||
let lastLine = sourceLine[sourceLine.length - 1] || sourceLine[sourceLine.length - 2]
|
||||
// lastLine is similar //# sourceMappingURL=data:application/json;base64,
|
||||
if (lastLine.startsWith('//# sourceMappingURL=')) {
|
||||
let sourceContent = null
|
||||
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
|
||||
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
||||
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
||||
} else if (sourceMappingURL.startsWith('http://') || sourceMappingURL.startsWith('https://')) {
|
||||
// TODO
|
||||
} else {
|
||||
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
|
||||
if (file.exists()) {
|
||||
sourceContent = base.read(file)
|
||||
sourceFileMaps[fileName] = file.getCanonicalPath()
|
||||
} else if (global.debug) {
|
||||
console.debug('readSourceMap can\'t found', fileName, 'source map file', sourceMappingURL)
|
||||
}
|
||||
}
|
||||
if (sourceContent) {
|
||||
sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sourceMaps[fileName]) {
|
||||
let sourceMapping = sourceMaps[fileName].getSource(lineNumber, 25, true, true)
|
||||
if (sourceMapping) {
|
||||
fileName = Paths.get(fileName, '..', sourceMapping.sourcePath).toFile().getCanonicalPath()
|
||||
lineNumber = sourceMapping.mapping.sourceLine
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
return { fileName, lineNumber }
|
||||
}
|
||||
|
||||
export function getStackTrace(ex: Error, color: boolean = true): string[] {
|
||||
if (!ex) return []
|
||||
let stack = ex.getStackTrace()
|
||||
let cache = [(color ? '§c' : '') + ex]
|
||||
//@ts-ignore
|
||||
if (stack.class) {
|
||||
stack = Arrays.asList(stack)
|
||||
}
|
||||
stack.forEach(trace => {
|
||||
if (!trace.fileName || trace.fileName.startsWith('jar:file:') || trace.fileName.startsWith('file:')) { return }
|
||||
if (trace.className.startsWith('<')) {
|
||||
let { fileName, lineNumber } = readSourceMap(trace.fileName, trace.lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${fileName}:${lineNumber}(${trace.lineNumber}) => §4${trace.methodName}`)
|
||||
} else {
|
||||
cache.push(` -> ${fileName}:${lineNumber}(${trace.lineNumber}) => ${trace.methodName}`)
|
||||
}
|
||||
} else {
|
||||
let className = trace.className
|
||||
var fileName = trace.fileName as string
|
||||
var lineNumber = trace.lineNumber
|
||||
if (className.startsWith('jdk.nashorn.internal.scripts') || className.startsWith('org.openjdk.nashorn.internal.scripts')) {
|
||||
className = className.substr(className.lastIndexOf('$') + 1)
|
||||
var { fileName, lineNumber } = readSourceMap(fileName, lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
} else {
|
||||
if (!global.debug) {
|
||||
for (let prefix in ignoreLogPrefix) {
|
||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||
return
|
||||
}
|
||||
}
|
||||
} else if (className.startsWith('jdk.nashorn.internal.') || className.startsWith('org.openjdk.nashorn.internal.')) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
|
||||
} else {
|
||||
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
|
||||
}
|
||||
}
|
||||
})
|
||||
return cache
|
||||
}
|
||||
}
|
||||
|
||||
export class MiaoScriptConsole implements Console {
|
||||
Console: any
|
||||
memory: any
|
||||
|
||||
private static sourceMaps: { [key: string]: SourceMapBuilder } = {}
|
||||
private static sourceFileMaps: { [key: string]: string } = {}
|
||||
private _name: string = ''
|
||||
private _level: LogLevel = LogLevel.INFO
|
||||
|
||||
|
@ -92,91 +192,8 @@ export class MiaoScriptConsole implements Console {
|
|||
ex(ex: Error) {
|
||||
this.stack(ex).forEach(line => this.console(line))
|
||||
}
|
||||
readSourceMap(fileName: string, lineNumber: any) {
|
||||
try {
|
||||
if (fileName.endsWith('js')) {
|
||||
if (MiaoScriptConsole.sourceMaps[fileName] === undefined) {
|
||||
MiaoScriptConsole.sourceMaps[fileName] = null
|
||||
let sourceLine = base.read(fileName).split('\n')
|
||||
let lastLine = sourceLine[sourceLine.length - 1]
|
||||
// lastLine is similar //# sourceMappingURL=data:application/json;base64,
|
||||
if (lastLine.startsWith('//# sourceMappingURL=')) {
|
||||
let sourceContent = null
|
||||
let sourceMappingURL = lastLine.split('sourceMappingURL=', 2)[1]
|
||||
if (sourceMappingURL.startsWith('data:application/json;base64,')) {
|
||||
sourceContent = String.fromCharCode(...Array.from(base64.toByteArray(sourceMappingURL.split(',', 2)[1])))
|
||||
} else if (sourceMappingURL.startsWith('http://') || sourceMappingURL.startsWith('https://')) {
|
||||
// TODO
|
||||
} else {
|
||||
let file = Paths.get(Paths.get(fileName, '..', sourceMappingURL).toFile().getCanonicalPath()).toFile()
|
||||
if (file.exists()) { sourceContent = base.read(file) }
|
||||
}
|
||||
if (sourceContent) {
|
||||
MiaoScriptConsole.sourceMaps[fileName] = new SourceMapBuilder(JSON.parse(sourceContent))
|
||||
MiaoScriptConsole.sourceFileMaps[fileName] = Paths.get(fileName, '..', MiaoScriptConsole.sourceMaps[fileName].sources[0]).toFile().getCanonicalPath()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (MiaoScriptConsole.sourceMaps[fileName]) {
|
||||
let sourceMapping = MiaoScriptConsole.sourceMaps[fileName].getSource(lineNumber, 25, true, true)
|
||||
fileName = MiaoScriptConsole.sourceFileMaps[fileName]
|
||||
if (sourceMapping && lineNumber != sourceMapping.mapping.sourceLine) { lineNumber = sourceMapping.mapping.sourceLine }
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.debug('search source map', fileName, 'line', lineNumber, 'error:', error)
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
return {
|
||||
fileName,
|
||||
lineNumber
|
||||
}
|
||||
}
|
||||
stack(ex: Error, color: boolean = true): string[] {
|
||||
if (!ex) return []
|
||||
let stack = ex.getStackTrace()
|
||||
let cache = [(color ? '§c' : '') + ex]
|
||||
//@ts-ignore
|
||||
if (stack.class) {
|
||||
stack = Arrays.asList(stack)
|
||||
}
|
||||
stack.forEach(trace => {
|
||||
if (!trace.fileName || trace.fileName.startsWith('jar:file:') || trace.fileName.startsWith('file:')) { return }
|
||||
if (trace.className.startsWith('<')) {
|
||||
let { fileName, lineNumber } = this.readSourceMap(trace.fileName, trace.lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${fileName}:${lineNumber} => §4${trace.methodName}`)
|
||||
} else {
|
||||
cache.push(` -> ${fileName}:${lineNumber} => ${trace.methodName}`)
|
||||
}
|
||||
} else {
|
||||
let className = trace.className
|
||||
var fileName = trace.fileName as string
|
||||
var lineNumber = trace.lineNumber
|
||||
if (className.startsWith('jdk.nashorn.internal.scripts') || className.startsWith('org.openjdk.nashorn.internal.scripts')) {
|
||||
className = className.substr(className.lastIndexOf('$') + 1)
|
||||
var { fileName, lineNumber } = this.readSourceMap(fileName, lineNumber)
|
||||
if (fileName.startsWith(root)) { fileName = fileName.split(root)[1] }
|
||||
} else {
|
||||
if (!global.debug) {
|
||||
for (let prefix in ignoreLogPrefix) {
|
||||
if (className.startsWith(ignoreLogPrefix[prefix])) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (color) {
|
||||
cache.push(` §e->§c ${className}.${trace.methodName}(§4${fileName}:${lineNumber}§c)`)
|
||||
} else {
|
||||
cache.push(` -> ${className}.${trace.methodName}(${fileName}:${lineNumber})`)
|
||||
}
|
||||
}
|
||||
})
|
||||
return cache
|
||||
return jsconsole.getStackTrace(ex, color)
|
||||
}
|
||||
assert(value: any, message?: string, ...optionalParams: any[]): void {
|
||||
throw new Error("Method not implemented.")
|
||||
|
|
|
@ -11,10 +11,21 @@ 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']
|
||||
getServerConnection: [
|
||||
/*spigot 1.8.8*/'aq',
|
||||
/*spigot 1.12.2*/ 'an',
|
||||
/*spigot 1.14.4+*/'getServerConnection',
|
||||
/*spigot 1.19+*/'ad',
|
||||
/*catserver 1.12.2*/'func_147137_ag'
|
||||
]
|
||||
}
|
||||
export const Field = {
|
||||
listeningChannels: [/*spigot 1.8.8-1.12.2*/'g', /*spigot 1.14.4*/'f', /*spigot 1.15.2+*/'listeningChannels', /*catserver 1.12.2*/'field_151274_e']
|
||||
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 {
|
||||
|
|
|
@ -6,6 +6,10 @@ export namespace database {
|
|||
* 数据库配置
|
||||
*/
|
||||
export interface DataBaseConfig {
|
||||
/**
|
||||
* 数据库类型
|
||||
*/
|
||||
type: 'h2' | 'mysql' | 'mongodb' | 'sqlite' | 'postgres' | 'redis'
|
||||
/**
|
||||
* 数据库连接串
|
||||
*/
|
||||
|
@ -26,6 +30,10 @@ export namespace database {
|
|||
* 链接属性
|
||||
*/
|
||||
properties?: { [key: string]: any }
|
||||
/**
|
||||
* 调试模式
|
||||
*/
|
||||
debug?: boolean
|
||||
}
|
||||
|
||||
@injectable()
|
||||
|
@ -35,6 +43,9 @@ export namespace database {
|
|||
abstract createDatabase(name: string, config: DataBaseConfig): DataBase
|
||||
abstract removeDatabase(name: string): boolean
|
||||
abstract getDatabase(name: string): DataBase
|
||||
abstract startWebManager(...args: string[])
|
||||
abstract stopWebManager()
|
||||
abstract shutdown()
|
||||
}
|
||||
@injectable()
|
||||
export abstract class DataBase {
|
||||
|
|
|
@ -25,7 +25,8 @@ export namespace event {
|
|||
public EventPriority = EventPriority;
|
||||
|
||||
private mapEvent = [];
|
||||
private listenerMap = [];
|
||||
private pluginEventMap = [];
|
||||
private cacheSlowEventKey = {};
|
||||
|
||||
protected baseEventDir = '';
|
||||
|
||||
|
@ -92,17 +93,23 @@ export namespace event {
|
|||
return eventCls
|
||||
}
|
||||
|
||||
execute(name, exec, eventCls) {
|
||||
/**
|
||||
* 创建命令执行器
|
||||
* @param name 插件名称
|
||||
* @param exec 执行方法
|
||||
* @param eventCls 事件类
|
||||
* @returns
|
||||
*/
|
||||
createExecute(name, exec, eventCls) {
|
||||
return (...args: any[]) => {
|
||||
let event = args[args.length - 1]
|
||||
try {
|
||||
let event = args[args.length - 1]
|
||||
if (eventCls.isAssignableFrom(event.getClass())) {
|
||||
let time = Date.now()
|
||||
exec(event)
|
||||
let cost = Date.now() - time
|
||||
if (cost > global.ScriptSlowExecuteTime) {
|
||||
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
|
||||
}
|
||||
if (!eventCls.isAssignableFrom(event.getClass())) { return }
|
||||
let time = Date.now(); exec(event); let cost = Date.now() - time
|
||||
if (cost > global.ScriptSlowExecuteTime && !event.async) {
|
||||
let eventKey = `${name}-${this.class2Name(eventCls)}`
|
||||
if (!this.cacheSlowEventKey[eventKey]) { return this.cacheSlowEventKey[eventKey] = cost }
|
||||
console.i18n("ms.api.event.execute.slow", { name, event: this.class2Name(eventCls), cost })
|
||||
}
|
||||
} catch (ex: any) {
|
||||
console.i18n("ms.api.event.execute.error", { name, event: this.class2Name(eventCls), ex })
|
||||
|
@ -113,17 +120,17 @@ export namespace event {
|
|||
|
||||
/**
|
||||
* 添加事件监听
|
||||
* @param plugin {any}
|
||||
* @param event {string}
|
||||
* @param exec {function}
|
||||
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
|
||||
* @param ignoreCancel
|
||||
* @param plugin {any} 插件
|
||||
* @param event {string} 事件名称
|
||||
* @param exec {function} 事件执行器
|
||||
* @param priority {string} [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR] 优先级
|
||||
* @param ignoreCancel 是否忽略已取消事件
|
||||
*/
|
||||
listen(plugin: any, event: string, exec: (event: any) => void, priority: EventPriority = EventPriority.NORMAL, ignoreCancel = false) {
|
||||
if (!plugin || !plugin.description || !plugin.description.name) throw new TypeError(i18n.translate("ms.api.event.listen.plugin.name.empty"))
|
||||
var name = plugin.description.name
|
||||
var eventCls = this.name2Class(name, event)
|
||||
if (!eventCls) { return }
|
||||
if (!eventCls) { return () => { console.warn('event ' + event + ' not found ignore off listener.') } }
|
||||
if (typeof priority === 'boolean') {
|
||||
ignoreCancel = priority
|
||||
priority = EventPriority.NORMAL
|
||||
|
@ -133,16 +140,15 @@ export namespace event {
|
|||
// @ts-ignore
|
||||
let executor = exec.name || exec.executor || '[anonymous]'
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
var listener = this.register(
|
||||
let listener = this.register(
|
||||
eventCls,
|
||||
this.execute(name, exec, eventCls),
|
||||
this.createExecute(name, exec, eventCls),
|
||||
priority,
|
||||
ignoreCancel
|
||||
)
|
||||
var listenerMap = this.listenerMap
|
||||
// add to cache Be used for close plugin to close event
|
||||
if (!listenerMap[name]) listenerMap[name] = []
|
||||
var off = () => {
|
||||
if (!this.pluginEventMap[name]) this.pluginEventMap[name] = []
|
||||
let off = () => {
|
||||
if (off['offed']) return
|
||||
off['offed'] = true
|
||||
this.unregister(eventCls, listener)
|
||||
|
@ -152,7 +158,7 @@ export namespace event {
|
|||
exec: executor
|
||||
}))
|
||||
}
|
||||
listenerMap[name].push(off)
|
||||
this.pluginEventMap[name].push(off)
|
||||
// noinspection JSUnresolvedVariable
|
||||
console.debug(i18n.translate("ms.api.event.register", {
|
||||
name,
|
||||
|
@ -169,10 +175,10 @@ export namespace event {
|
|||
* @param plugin 插件
|
||||
*/
|
||||
disable(plugin: any) {
|
||||
var eventCache = this.listenerMap[plugin.description.name]
|
||||
var eventCache = this.pluginEventMap[plugin.description.name]
|
||||
if (eventCache) {
|
||||
eventCache.forEach(off => off())
|
||||
delete this.listenerMap[plugin.description.name]
|
||||
eventCache.forEach((off: () => any) => off())
|
||||
delete this.pluginEventMap[plugin.description.name]
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,14 +1,14 @@
|
|||
import "@ccms/nashorn"
|
||||
|
||||
export * from './web'
|
||||
export * from './amqp'
|
||||
export * from './chat'
|
||||
export * from './task'
|
||||
export * from './item'
|
||||
export * from './event'
|
||||
export * from './proxy'
|
||||
export * from './plugin'
|
||||
export * from './server'
|
||||
export * from './console'
|
||||
export { jsconsole as console } from './console'
|
||||
export * from './channel'
|
||||
export * from './command'
|
||||
export * from './database'
|
||||
|
|
|
@ -0,0 +1,20 @@
|
|||
import { injectable } from '@ccms/container'
|
||||
|
||||
export namespace item {
|
||||
@injectable()
|
||||
export abstract class Item {
|
||||
abstract builder(): ItemBuilder
|
||||
abstract toJson(item: any): string
|
||||
abstract fromJson(json: string): any
|
||||
}
|
||||
export interface ItemBuilder {
|
||||
from(item: any): ItemBuilder
|
||||
create(type: string | number): ItemBuilder
|
||||
name(name: string): ItemBuilder
|
||||
lore(...lores: string[]): ItemBuilder
|
||||
amount(amount: number): ItemBuilder
|
||||
durability(durability: number): ItemBuilder
|
||||
clone(): any
|
||||
build(): any
|
||||
}
|
||||
}
|
|
@ -6,6 +6,12 @@ const UUID = Java.type('java.util.UUID')
|
|||
const Math = Java.type('java.lang.Math')
|
||||
|
||||
export namespace particle {
|
||||
@injectable()
|
||||
export abstract class ParticleSpawner {
|
||||
abstract spawn(location: any, particle: Particle)
|
||||
abstract spawnToPlayer(player: any, location: any, particle: Particle)
|
||||
}
|
||||
|
||||
/**
|
||||
* 表示一个特效对象
|
||||
*
|
||||
|
@ -23,6 +29,11 @@ export namespace particle {
|
|||
private extra: number = 0;
|
||||
private data: Object = null;
|
||||
|
||||
/**
|
||||
* Only Show To Player
|
||||
*/
|
||||
private player: any
|
||||
|
||||
constructor() {
|
||||
this.uuid = UUID.randomUUID().toString()
|
||||
}
|
||||
|
@ -105,6 +116,15 @@ export namespace particle {
|
|||
return this
|
||||
}
|
||||
|
||||
getPlayer() {
|
||||
return this.player
|
||||
}
|
||||
|
||||
setPlayer(player) {
|
||||
this.player = player
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过给定一个坐标就可以使用已经指定的参数来播放粒子
|
||||
*
|
||||
|
@ -112,9 +132,14 @@ export namespace particle {
|
|||
*/
|
||||
spawn(location: any) {
|
||||
if (!this.spawner) throw new Error(`particle ${this.uuid} not set spawner can't spawn!`)
|
||||
this.spawner.spawn(location, this)
|
||||
if (this.player) {
|
||||
this.spawner.spawnToPlayer(this.player, location, this)
|
||||
} else {
|
||||
this.spawner.spawn(location, this)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 表示一条线
|
||||
*
|
||||
|
@ -158,8 +183,7 @@ export namespace particle {
|
|||
|
||||
show() {
|
||||
for (let i = 0; i < this.length; i += this.step) {
|
||||
let vectorTemp = this.vector.clone().multiply(i)
|
||||
this.spawn(this.start.clone().add(vectorTemp))
|
||||
this.spawn(this.start.clone().add(this.vector.clone().multiply(i)))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -234,15 +258,6 @@ export namespace particle {
|
|||
this.length = this.vector.length()
|
||||
this.vector.normalize()
|
||||
}
|
||||
|
||||
public static buildLine(locA: any, locB: any, step: number, particle: any) {
|
||||
let vectorAB = locB.clone().subtract(locA).toVector()
|
||||
let vectorLength = vectorAB.length()
|
||||
vectorAB.normalize()
|
||||
for (let i = 0; i < vectorLength; i += step) {
|
||||
ParticleManager.globalSpawner.spawn(locA.clone().add(vectorAB.clone().multiply(i)), particle)
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 表示一个弧
|
||||
|
@ -331,9 +346,10 @@ export namespace particle {
|
|||
|
||||
@injectable()
|
||||
export abstract class ParticleManager {
|
||||
public static globalSpawner: ParticleSpawner = undefined
|
||||
@Autowired()
|
||||
private taskManager: task.TaskManager
|
||||
@Autowired()
|
||||
private particleSpawner: particle.ParticleSpawner
|
||||
|
||||
protected taskId: java.util.concurrent.atomic.AtomicInteger
|
||||
protected cacheTasks = new Map<string, ParticleTask>()
|
||||
|
@ -354,6 +370,10 @@ export namespace particle {
|
|||
return this.taskManager
|
||||
}
|
||||
|
||||
public getParticleSpawner() {
|
||||
return this.particleSpawner
|
||||
}
|
||||
|
||||
public create(particle: Particle, plugin?: plugin.Plugin) {
|
||||
let uuid = particle.getUUID()
|
||||
if (this.cacheTasks.has(uuid)) {
|
||||
|
@ -389,14 +409,12 @@ export namespace particle {
|
|||
}
|
||||
}
|
||||
protected create0(owner: plugin.Plugin, particle: Particle): ParticleTask {
|
||||
particle.setSpawner(this.getGlobalSpawner())
|
||||
particle.setSpawner(this.getParticleSpawner())
|
||||
return new ParticleTask(owner, particle, this)
|
||||
}
|
||||
protected abstract getGlobalSpawner(): ParticleSpawner
|
||||
}
|
||||
|
||||
export class ParticleTask {
|
||||
|
||||
private particle: Particle
|
||||
private isAsync: boolean = false
|
||||
private interval: number = 0
|
||||
|
@ -486,9 +504,4 @@ export namespace particle {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class ParticleSpawner {
|
||||
abstract spawnParticle(location: any, particle: any, count: number)
|
||||
abstract spawn(location: any, particle: Particle)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -19,14 +19,23 @@ export namespace plugin {
|
|||
@injectable()
|
||||
export abstract class PluginManager {
|
||||
abstract scan(folder: string): void
|
||||
abstract build(): void
|
||||
abstract loadFromFile(file: string, ext?: any): Plugin
|
||||
abstract load(...args: any[]): void
|
||||
abstract enable(...args: any[]): void
|
||||
abstract disable(...args: any[]): void
|
||||
abstract reload(...args: any[]): void
|
||||
abstract require(loadMetadata: PluginLoadMetadata): PluginMetadata
|
||||
abstract build(metadata: PluginMetadata): Plugin
|
||||
abstract rebuild(plugin: plugin.Plugin): void
|
||||
abstract load(plugin: plugin.Plugin): void
|
||||
abstract enable(plugin: plugin.Plugin): void
|
||||
abstract disable(plugin: plugin.Plugin): void
|
||||
abstract reload(plugin: plugin.Plugin): void
|
||||
abstract has(name: string): boolean
|
||||
abstract get(name: string): plugin.Plugin
|
||||
abstract getPlugin(name: string): plugin.Plugin
|
||||
abstract getPlugins(): Map<string, plugin.Plugin>
|
||||
abstract buildPlugins(): void
|
||||
abstract rebuildPlugins(): void
|
||||
abstract loadPlugins(): void
|
||||
abstract enablePlugins(): void
|
||||
abstract disablePlugins(): void
|
||||
}
|
||||
export const PluginScanner = Symbol("PluginScanner")
|
||||
/**
|
||||
|
@ -38,9 +47,13 @@ export namespace plugin {
|
|||
*/
|
||||
type: string
|
||||
/**
|
||||
* 插件文件
|
||||
* 插件文件(java.io.File)
|
||||
*/
|
||||
file?: string
|
||||
file?: any
|
||||
/**
|
||||
* 插件规范路径 canonicalPath
|
||||
*/
|
||||
path?: string
|
||||
/**
|
||||
* 插件实例
|
||||
*/
|
||||
|
@ -122,11 +135,6 @@ export namespace plugin {
|
|||
* @param plugin 插件
|
||||
*/
|
||||
disable?(plugin: Plugin): void
|
||||
/**
|
||||
* Reload 阶段
|
||||
* @param plugin 插件
|
||||
*/
|
||||
reload?(plugin: Plugin): void
|
||||
}
|
||||
export interface Plugin {
|
||||
description: PluginMetadata
|
||||
|
@ -149,7 +157,19 @@ export namespace plugin {
|
|||
/**
|
||||
* 插件名称 不填默认为类名
|
||||
*/
|
||||
name?: string
|
||||
name: string
|
||||
/**
|
||||
* 插件中文名称
|
||||
*/
|
||||
cname?: string
|
||||
/**
|
||||
* 付费插件ID
|
||||
*/
|
||||
pid?: number
|
||||
/**
|
||||
* 付费插件等级 付费插件自动注入
|
||||
*/
|
||||
level?: number
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
|
|
|
@ -29,6 +29,7 @@ export namespace server {
|
|||
origin: any
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export abstract class NativePluginManager {
|
||||
list(): NativePlugin[] {
|
||||
|
@ -53,6 +54,7 @@ export namespace server {
|
|||
throw new Error("Method not implemented.")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MiaoScript Server
|
||||
*/
|
||||
|
@ -98,6 +100,7 @@ export namespace server {
|
|||
throw new Error("Method not implemented.")
|
||||
}
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export class ServerChecker {
|
||||
@Autowired(ServerType)
|
||||
|
@ -116,6 +119,22 @@ export namespace server {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export class NativePluginChecker {
|
||||
@Autowired(NativePluginManager)
|
||||
private nativePluginManager: NativePluginManager
|
||||
|
||||
check(plugins: string[]) {
|
||||
// Not set plugins -> allow
|
||||
if (!plugins || !plugins.length) return true
|
||||
for (const plugin of plugins) {
|
||||
if (!this.nativePluginManager.has(plugin)) { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@injectable()
|
||||
export abstract class ReflectServer extends server.Server {
|
||||
@Autowired(ContainerInstance)
|
||||
|
@ -172,13 +191,23 @@ export namespace server {
|
|||
}
|
||||
protected reflectRootLogger(consoleServer: any) {
|
||||
try {
|
||||
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get().parent
|
||||
this.rootLogger = reflect.on(consoleServer).get('LOGGER').get()
|
||||
} catch (error: any) {
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
try {
|
||||
this.rootLogger = reflect.on(consoleServer).get(0).get().parent
|
||||
this.rootLogger = reflect.on(consoleServer).get(0).get()
|
||||
} catch (error: any) {
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this.rootLogger.class.name.indexOf('slf4j') !== -1) {
|
||||
try {
|
||||
let LogManager = Java.type('org.apache.logging.log4j.LogManager')
|
||||
this.rootLogger = LogManager.getLogger('ROOT')
|
||||
} catch (error: any) {
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
|
@ -189,11 +218,11 @@ export namespace server {
|
|||
console.error('Error Logger Class: ' + this.rootLogger.class.name)
|
||||
this.rootLogger = undefined
|
||||
}
|
||||
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
|
||||
// get root logger
|
||||
for (let index = 0; index < 5 && this.rootLogger.parent; index++) {
|
||||
this.rootLogger = this.rootLogger.parent
|
||||
}
|
||||
if (!this.rootLogger) { console.error("Can't found rootLogger!") }
|
||||
this.container.bind(constants.ServiceIdentifier.RootLogger).toConstantValue(this.rootLogger)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
import { plugin } from './index'
|
||||
import { EventEmitter } from 'events'
|
||||
import { injectable } from '@ccms/container'
|
||||
|
||||
import { plugin } from './index'
|
||||
|
||||
const AtomicInteger = Java.type("java.util.concurrent.atomic.AtomicInteger")
|
||||
|
||||
export namespace task {
|
||||
|
@ -12,6 +14,7 @@ export namespace task {
|
|||
|
||||
constructor() {
|
||||
this.taskId = new AtomicInteger(0)
|
||||
process.on('core.disable', () => { this.disable() })
|
||||
process.on('task.finish', (task: task.Task) => {
|
||||
let taskId = task.getTaskId()
|
||||
this.cacheTasks.delete(taskId)
|
||||
|
@ -22,30 +25,6 @@ export namespace task {
|
|||
})
|
||||
}
|
||||
|
||||
protected pluginCreate(plugin: plugin.Plugin, task: task.Task) {
|
||||
if (!this.pluginCacheTasks.has(plugin.description.name)) {
|
||||
this.pluginCacheTasks.set(plugin.description.name, new Map())
|
||||
}
|
||||
this.pluginCacheTasks.get(plugin.description.name).set(task.getTaskId(), task)
|
||||
return task
|
||||
}
|
||||
|
||||
protected pluginDisable(plugin: plugin.Plugin) {
|
||||
if (this.pluginCacheTasks.has(plugin.description.name)) {
|
||||
this.pluginCacheTasks.get(plugin.description.name).forEach((task) => {
|
||||
task.cancel()
|
||||
})
|
||||
this.pluginCacheTasks.delete(plugin.description.name)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得自增的任务ID
|
||||
*/
|
||||
protected nextId() {
|
||||
return this.taskId.incrementAndGet()
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建任务
|
||||
* @param func 任务内容
|
||||
|
@ -73,13 +52,35 @@ export namespace task {
|
|||
if (plugin) { return this.pluginDisable(plugin) }
|
||||
this.disable0()
|
||||
}
|
||||
|
||||
protected pluginCreate(plugin: plugin.Plugin, task: task.Task) {
|
||||
if (!this.pluginCacheTasks.has(plugin.description.name)) {
|
||||
this.pluginCacheTasks.set(plugin.description.name, new Map())
|
||||
}
|
||||
this.pluginCacheTasks.get(plugin.description.name).set(task.getTaskId(), task)
|
||||
return task
|
||||
}
|
||||
|
||||
protected pluginDisable(plugin: plugin.Plugin) {
|
||||
if (this.pluginCacheTasks.has(plugin.description.name)) {
|
||||
this.pluginCacheTasks.get(plugin.description.name).forEach((task) => task.cancel())
|
||||
this.pluginCacheTasks.delete(plugin.description.name)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得自增的任务ID
|
||||
*/
|
||||
protected nextId() {
|
||||
return this.taskId.incrementAndGet()
|
||||
}
|
||||
protected abstract create0(owner: plugin.Plugin, func: Function, id: number): task.Task
|
||||
protected abstract disable0()
|
||||
}
|
||||
/**
|
||||
* 任务抽象
|
||||
*/
|
||||
export abstract class Task implements Cancelable {
|
||||
export abstract class Task extends EventEmitter implements Cancelable {
|
||||
protected func: Function
|
||||
protected isAsync: boolean = false;
|
||||
protected laterTime: number = 0;
|
||||
|
@ -88,10 +89,16 @@ export namespace task {
|
|||
protected taskId: number
|
||||
protected innerTask: any
|
||||
|
||||
private cancelled: boolean = false
|
||||
|
||||
constructor(owner: plugin.Plugin, func: Function, id: number) {
|
||||
super()
|
||||
this.owner = owner
|
||||
this.func = func
|
||||
this.taskId = id
|
||||
this.on('finish', () => {
|
||||
process.emit('task.finish', this)
|
||||
})
|
||||
}
|
||||
|
||||
getOwner() {
|
||||
|
@ -134,20 +141,35 @@ export namespace task {
|
|||
*/
|
||||
cancel(): boolean {
|
||||
let result = this.cancel0()
|
||||
process.emit('task.finish', this)
|
||||
this.finish()
|
||||
this.cancelled = true
|
||||
return result
|
||||
}
|
||||
|
||||
protected run(...args: any[]): void {
|
||||
try {
|
||||
this.emit('before', this)
|
||||
if (this.cancelled) { return }
|
||||
this.func(...args)
|
||||
!this.interval && process.emit('task.finish', this)
|
||||
} catch (ex: any) {
|
||||
console.console('§4插件执行任务时发生错误', ex)
|
||||
console.ex(ex)
|
||||
this.emit('after', this)
|
||||
} catch (error: any) {
|
||||
try {
|
||||
this.emit('error', error)
|
||||
} catch (ignore) {
|
||||
console.console('§4插件执行任务时发生错误', error)
|
||||
console.ex(error)
|
||||
this.cancel()
|
||||
}
|
||||
} finally {
|
||||
this.emit('finally', this)
|
||||
if (!this.interval && !this.cancelled) { this.finish() }
|
||||
}
|
||||
}
|
||||
|
||||
protected finish() {
|
||||
this.emit('finish', this)
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交任务
|
||||
* @param args 任务参数
|
||||
|
@ -161,7 +183,7 @@ export namespace task {
|
|||
* 提交任务
|
||||
* @param args 任务参数
|
||||
*/
|
||||
protected abstract submit0(...args: any[]): any
|
||||
protected abstract submit0(...args: any[]): Cancelable
|
||||
/**
|
||||
* 取消任务
|
||||
*/
|
||||
|
|
|
@ -1,3 +0,0 @@
|
|||
export namespace web {
|
||||
export const Server = Symbol('Server')
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@ccms/bukkit",
|
||||
"version": "0.21.0",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "MiaoScript bukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
|
@ -12,21 +12,23 @@
|
|||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/spigot-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"@javatypes/spigot-api": "^0.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.21.0",
|
||||
"@ccms/common": "^0.21.0",
|
||||
"@ccms/container": "^0.21.0"
|
||||
"@ccms/api": "^0.28.0-beta.10",
|
||||
"@ccms/common": "^0.28.0-beta.10",
|
||||
"@ccms/container": "^0.28.0-beta.10"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,6 +2,7 @@ import { event, plugin } from '@ccms/api'
|
|||
import { inject, provideSingleton } from '@ccms/container'
|
||||
import * as reflect from '@ccms/common/dist/reflect'
|
||||
|
||||
const URL = Java.type('java.net.URL')
|
||||
const Bukkit = Java.type("org.bukkit.Bukkit")
|
||||
const Event = Java.type("org.bukkit.event.Event")
|
||||
const Modifier = Java.type("java.lang.reflect.Modifier")
|
||||
|
@ -19,7 +20,15 @@ export class BukkitEvent extends event.Event {
|
|||
}
|
||||
|
||||
getJarFile(resource: string) {
|
||||
return super.getJarFile('org/bukkit/Bukkit.class', Bukkit.class.classLoader)
|
||||
try {
|
||||
return super.getJarFile('org/bukkit/Bukkit.class', Bukkit.class.classLoader)
|
||||
} catch (error) {
|
||||
// 兼容 LoliServer 的 Bukkit 包无法获取的问题
|
||||
let ModList = Java.type('net.minecraftforge.fml.ModList').get()
|
||||
let forgeFile = ModList.getModFileById("forge").getFile().getFilePath()
|
||||
let jarPath = `jar:file:${forgeFile}!/org/bukkit/Bukkit.class`
|
||||
return new URL(jarPath).openConnection().jarFile
|
||||
}
|
||||
}
|
||||
isValidEvent(clazz: any): boolean {
|
||||
// 继承于 org.bukkit.event.Event
|
||||
|
|
|
@ -4,6 +4,7 @@ import { server } from '@ccms/api'
|
|||
import { Container } from '@ccms/container'
|
||||
|
||||
import { BukkitConsole } from './console'
|
||||
import './item'
|
||||
import './chat'
|
||||
import './task'
|
||||
import './event'
|
||||
|
|
|
@ -6,12 +6,14 @@ let bukkitChatInvoke: BukkitChatInvoke
|
|||
abstract class BukkitChatInvoke {
|
||||
private downgrade: boolean = false
|
||||
protected RemapUtils: any
|
||||
protected ComponentSerializer: any
|
||||
|
||||
protected ChatSerializer: any
|
||||
protected nmsChatSerializerMethodName: string
|
||||
protected PacketPlayOutChat: any
|
||||
protected chatMessageTypes: any
|
||||
protected playerConnectionFieldName: string
|
||||
protected playerFieldName: string
|
||||
protected sendPacketMethodName: string
|
||||
|
||||
constructor(private nmsVersion) {
|
||||
|
@ -20,12 +22,12 @@ abstract class BukkitChatInvoke {
|
|||
init() {
|
||||
try {
|
||||
try {
|
||||
this.ComponentSerializer = Java.type('net.md_5.bungee.chat.ComponentSerializer')
|
||||
this.RemapUtils = Java.type('catserver.server.remapper.RemapUtils')
|
||||
} catch (ex: any) {
|
||||
}
|
||||
let nmsChatSerializerClass = this.getNmsChatSerializerClass()
|
||||
let nmsChatSerializerMethod = this.remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
|
||||
this.nmsChatSerializerMethodName = nmsChatSerializerMethod.getName()
|
||||
this.nmsChatSerializerMethodName = this.getNmsChatSerializerMethodName(nmsChatSerializerClass)
|
||||
this.ChatSerializer = Java.type(nmsChatSerializerClass.getName())
|
||||
let packetTypeClass = this.getPacketPlayOutChatClass()
|
||||
this.PacketPlayOutChat = Java.type(packetTypeClass.getName())
|
||||
|
@ -37,12 +39,14 @@ abstract class BukkitChatInvoke {
|
|||
if (nmsChatMessageTypeClass.isEnum()) {
|
||||
this.chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants()
|
||||
break
|
||||
} else if (nmsChatMessageTypeClass.getName() == 'int') {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
let playerConnectionField = this.getPlayerConnectionField()
|
||||
this.playerConnectionFieldName = playerConnectionField.getName()
|
||||
this.sendPacketMethodName = this.remapMethod(playerConnectionField.getType(), 'sendPacket', 'func_179290_a', this.getPacketClass()).getName()
|
||||
this.sendPacketMethodName = this.getSendPacketMethodName(playerConnectionField.getType())
|
||||
} catch (ex: any) {
|
||||
org.bukkit.Bukkit.getConsoleSender().sendMessage(`§6[§cMS§6][§bbukkit§6][§achat§6] §cNMS Inject Error §4${ex} §cDowngrade to Command Mode...`)
|
||||
this.downgrade = true
|
||||
|
@ -50,10 +54,12 @@ abstract class BukkitChatInvoke {
|
|||
}
|
||||
|
||||
abstract getNmsChatSerializerClass()
|
||||
abstract getNmsChatSerializerMethodName(nmsChatSerializerClass: any)
|
||||
abstract getPacketPlayOutChatClass()
|
||||
abstract getPacketPlayOutChat(sender: any, json: any, type: number)
|
||||
abstract getPlayerConnectionField()
|
||||
abstract getPacketClass()
|
||||
abstract getSendPacketMethodName(playerConnectionClass: any)
|
||||
|
||||
nmsCls(name: string) {
|
||||
return base.getClass(['net.minecraft.server', this.nmsVersion, name].join('.'))
|
||||
|
@ -83,9 +89,9 @@ abstract class BukkitChatInvoke {
|
|||
}
|
||||
}
|
||||
|
||||
json(sender: { name: string }, json: string) {
|
||||
json(sender: any, json: string) {
|
||||
if (this.downgrade) {
|
||||
return '/tellraw ' + sender.name + ' ' + json
|
||||
return sender.spigot().sendMessage(this.ComponentSerializer.parse(json))
|
||||
} else {
|
||||
this.send(sender, json, 0)
|
||||
return false
|
||||
|
@ -100,6 +106,13 @@ abstract class BukkitChatInvoke {
|
|||
}
|
||||
|
||||
class BukkitChatInvokeBase extends BukkitChatInvoke {
|
||||
getSendPacketMethodName(playerConnectionClass: any) {
|
||||
return this.remapMethod(playerConnectionClass, 'sendPacket', 'func_179290_a', this.getPacketClass()).getName()
|
||||
}
|
||||
getNmsChatSerializerMethodName(nmsChatSerializerClass: any) {
|
||||
let nmsChatSerializerMethod = this.remapMethod(nmsChatSerializerClass, 'a', 'func_150699_a', base.getClass('java.lang.String'))
|
||||
return nmsChatSerializerMethod.getName()
|
||||
}
|
||||
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
||||
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), type)
|
||||
}
|
||||
|
@ -148,18 +161,35 @@ class BukkitChatInvoke_1_17_1 extends BukkitChatInvoke_1_16_5 {
|
|||
return base.getClass('net.minecraft.network.protocol.Packet')
|
||||
}
|
||||
}
|
||||
class BukkitChatInvoke_1_18_2 extends BukkitChatInvoke_1_17_1 {
|
||||
getSendPacketMethodName(playerConnectionClass: any) {
|
||||
return playerConnectionClass.getMethod('a', this.getPacketClass()).getName()
|
||||
}
|
||||
}
|
||||
class BukkitChatInvoke_1_19 extends BukkitChatInvoke_1_18_2 {
|
||||
getPacketPlayOutChatClass() {
|
||||
return base.getClass('net.minecraft.network.protocol.game.ClientboundSystemChatPacket')
|
||||
}
|
||||
getPacketPlayOutChat(sender: any, json: any, type: number) {
|
||||
return new this.PacketPlayOutChat(this.ChatSerializer[this.nmsChatSerializerMethodName](json), type)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
let Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||
// @ts-ignore
|
||||
let nmsVersion = Bukkit.getServer().class.name.split('.')[3]
|
||||
let nmsSubVersion = nmsVersion.split("_")[1]
|
||||
if (nmsSubVersion >= 8) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_8(nmsVersion)
|
||||
} else if (nmsSubVersion >= 16) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_16_5(nmsVersion)
|
||||
if (nmsSubVersion >= 19) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_19(nmsVersion)
|
||||
} else if (nmsSubVersion >= 18) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_18_2(nmsVersion)
|
||||
} else if (nmsSubVersion >= 17) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_17_1(nmsVersion)
|
||||
} else if (nmsSubVersion >= 16) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_16_5(nmsVersion)
|
||||
} else if (nmsSubVersion >= 8) {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_8(nmsVersion)
|
||||
} else {
|
||||
bukkitChatInvoke = new BukkitChatInvoke_1_7_10(nmsVersion)
|
||||
}
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,128 @@
|
|||
import { item } from "@ccms/api"
|
||||
import { provideSingleton } from "@ccms/container"
|
||||
|
||||
import { itemIds } from './internal/item'
|
||||
|
||||
const Material: typeof org.bukkit.Material = Java.type('org.bukkit.Material')
|
||||
const ItemStack: typeof org.bukkit.inventory.ItemStack = Java.type('org.bukkit.inventory.ItemStack')
|
||||
|
||||
@provideSingleton(item.Item)
|
||||
export class BukkitItem extends item.Item {
|
||||
private CraftItemStack: any
|
||||
private NBTTagCompound: any
|
||||
private nmsSaveNBTMethodName: any
|
||||
private MojangsonParser: any
|
||||
private nmsItemStack: any
|
||||
private mpParseMethodName: any
|
||||
private nmsVersion: any
|
||||
constructor() {
|
||||
super()
|
||||
this.reflect()
|
||||
}
|
||||
builder(): item.ItemBuilder {
|
||||
return new BukkitItemBuilder()
|
||||
}
|
||||
toJson(item: any): string {
|
||||
let nbt = new this.NBTTagCompound()
|
||||
return this.CraftItemStack.asNMSCopy(item)[this.nmsSaveNBTMethodName](nbt).toString()
|
||||
}
|
||||
fromJson(json: string) {
|
||||
return this.CraftItemStack.asBukkitCopy(new this.nmsItemStack(this.MojangsonParser[this.mpParseMethodName](json)))
|
||||
}
|
||||
private obcCls(name: string) {
|
||||
return base.getClass(['org.bukkit.craftbukkit', this.nmsVersion, name].join('.'))
|
||||
}
|
||||
private nmsCls(name: string) {
|
||||
return base.getClass(['net.minecraft.server', this.nmsVersion, name].join('.'))
|
||||
}
|
||||
private reflect() {
|
||||
try {
|
||||
let Bukkit: typeof org.bukkit.Bukkit = Java.type('org.bukkit.Bukkit')
|
||||
// @ts-ignore
|
||||
this.nmsVersion = Bukkit.getServer().class.name.split('.')[3]
|
||||
let CraftItemStackClass = this.obcCls('inventory.CraftItemStack')
|
||||
this.CraftItemStack = Java.type(CraftItemStackClass.getName())
|
||||
// @ts-ignore
|
||||
let asNMSCopyMethod = CraftItemStackClass.getMethod('asNMSCopy', ItemStack.class)
|
||||
let nmsItemStackClass = asNMSCopyMethod.getReturnType()
|
||||
this.nmsItemStack = Java.type(nmsItemStackClass.getName())
|
||||
let nmsNBTTagCompoundClass = undefined
|
||||
for (let method of Java.from(nmsItemStackClass.getMethods())) {
|
||||
let rt = method.getReturnType()
|
||||
if (method.getParameterTypes().length == 0 && "NBTTagCompound" == rt.getSimpleName()) {
|
||||
nmsNBTTagCompoundClass = rt
|
||||
}
|
||||
}
|
||||
this.NBTTagCompound = Java.type(nmsNBTTagCompoundClass.getName())
|
||||
for (let method of Java.from(nmsItemStackClass.getMethods())) {
|
||||
let params = method.getParameterTypes()
|
||||
let rt = method.getReturnType()
|
||||
if (params.length == 1 && "NBTTagCompound" == params[0].getSimpleName() && "NBTTagCompound" == rt.getSimpleName()) {
|
||||
this.nmsSaveNBTMethodName = method.getName()
|
||||
break
|
||||
}
|
||||
}
|
||||
try {
|
||||
this.MojangsonParser = this.nmsCls('MojangsonParser').static
|
||||
} catch (error) {
|
||||
this.MojangsonParser = Java.type('net.minecraft.nbt.MojangsonParser')
|
||||
}
|
||||
for (let method of Java.from(this.MojangsonParser.class.getMethods())) {
|
||||
let params = method.getParameterTypes()
|
||||
let rt = method.getReturnType()
|
||||
if (params.length == 1 && "String" == params[0].getSimpleName() && "NBTTagCompound" == rt.getSimpleName()) {
|
||||
this.mpParseMethodName = method.getName()
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.log('Bukkit 物品管理器初始化失败:', error)
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class BukkitItemBuilder implements item.ItemBuilder {
|
||||
private itemStack: org.bukkit.inventory.ItemStack
|
||||
private itemMeta: org.bukkit.inventory.meta.ItemMeta
|
||||
|
||||
from(itemStack: any): item.ItemBuilder {
|
||||
this.itemStack = itemStack
|
||||
this.itemMeta = this.itemStack.getItemMeta()
|
||||
return this
|
||||
}
|
||||
create(type: string | number): item.ItemBuilder {
|
||||
let material = undefined
|
||||
if (typeof type == 'number') {
|
||||
type = itemIds[type]
|
||||
}
|
||||
material = Material[type] || Material[Material['LEGACY_PREFIX'] + type]
|
||||
this.itemStack = new ItemStack(material)
|
||||
this.itemMeta = this.itemStack.getItemMeta()
|
||||
return this
|
||||
}
|
||||
name(name: string): item.ItemBuilder {
|
||||
this.itemMeta.setDisplayName(name)
|
||||
return this
|
||||
}
|
||||
lore(...lores: string[]): item.ItemBuilder {
|
||||
this.itemMeta.setLore(lores)
|
||||
return this
|
||||
}
|
||||
amount(amount: number): item.ItemBuilder {
|
||||
this.itemStack.setAmount(amount)
|
||||
return this
|
||||
}
|
||||
durability(durability: number): item.ItemBuilder {
|
||||
this.itemStack.setDurability(durability)
|
||||
return this
|
||||
}
|
||||
clone() {
|
||||
return this.build().clone()
|
||||
}
|
||||
build() {
|
||||
this.itemStack.setItemMeta(this.itemMeta)
|
||||
return this.itemStack
|
||||
}
|
||||
}
|
|
@ -3,20 +3,11 @@ import { particle } from '@ccms/api'
|
|||
|
||||
@provideSingleton(particle.ParticleManager)
|
||||
export class BukkitParticleManager extends particle.ParticleManager {
|
||||
private globalSpawner = new BukkitParticleSpawner()
|
||||
constructor() {
|
||||
super()
|
||||
particle.ParticleManager.globalSpawner = this.globalSpawner
|
||||
}
|
||||
protected getGlobalSpawner() {
|
||||
return this.globalSpawner
|
||||
}
|
||||
}
|
||||
|
||||
@provideSingleton(particle.ParticleSpawner)
|
||||
export class BukkitParticleSpawner extends particle.ParticleSpawner {
|
||||
spawnParticle(location: any, particle: any, count: number = 1) {
|
||||
location.getWorld().spawnParticle(particle, location, count)
|
||||
}
|
||||
spawn(location: any, particle: particle.Particle) {
|
||||
spawn(location: org.bukkit.Location, particle: particle.Particle) {
|
||||
location.getWorld().spawnParticle(
|
||||
particle.getParticle(),
|
||||
location,
|
||||
|
@ -28,4 +19,15 @@ export class BukkitParticleSpawner extends particle.ParticleSpawner {
|
|||
particle.getData()
|
||||
)
|
||||
}
|
||||
spawnToPlayer(player: org.bukkit.entity.Player, location: org.bukkit.Location, particle: particle.Particle) {
|
||||
player.spawnParticle(
|
||||
particle.getParticle(),
|
||||
location,
|
||||
particle.getCount(),
|
||||
particle.getOffsetX(),
|
||||
particle.getOffsetY(),
|
||||
particle.getOffsetZ(),
|
||||
particle.getExtra(),
|
||||
particle.getData())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,6 +2,7 @@
|
|||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
"outDir": "dist",
|
||||
"resolveJsonModule": true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@ccms/bungee",
|
||||
"version": "0.21.0",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "MiaoScript bungee package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
|
@ -12,21 +12,23 @@
|
|||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/bungee-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"@javatypes/bungee-api": "^0.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.21.0",
|
||||
"@ccms/common": "^0.21.0",
|
||||
"@ccms/container": "^0.21.0"
|
||||
"@ccms/api": "^0.28.0-beta.10",
|
||||
"@ccms/common": "^0.28.0-beta.10",
|
||||
"@ccms/container": "^0.28.0-beta.10"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
src/emp.ts
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,37 +0,0 @@
|
|||
{
|
||||
"private": true,
|
||||
"name": "@ccms/client",
|
||||
"version": "0.21.0",
|
||||
"description": "MiaoScript client package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"dev": "ts-node-dev --respawn --debounce=1500 src/index.ts",
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"start": "node dist/index.js",
|
||||
"debug": "DEBUG=minecraft-protocol node dist/index.js",
|
||||
"emp": "node dist/emp.js",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^0.27.2",
|
||||
"minecraft-protocol": "^1.34.0",
|
||||
"minecraft-protocol-forge": "^1.0.0",
|
||||
"proxy-agent": "^5.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^17.0.25",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
}
|
||||
}
|
|
@ -1,101 +0,0 @@
|
|||
class MessagePart {
|
||||
text: string
|
||||
color: string
|
||||
clickEvent: MessagePartEvent
|
||||
hoverEvent: MessagePartEvent
|
||||
translate: string
|
||||
with: MessagePart[]
|
||||
extra: MessagePart[]
|
||||
}
|
||||
|
||||
class MessagePartEvent {
|
||||
action: string
|
||||
value: string
|
||||
}
|
||||
|
||||
var colorMap = []
|
||||
colorMap['0'] = '38;5;0'
|
||||
colorMap['1'] = '38;5;4'
|
||||
colorMap['2'] = '38;5;2'
|
||||
colorMap['3'] = '38;5;6'
|
||||
colorMap['4'] = '38;5;1'
|
||||
colorMap['5'] = '38;5;5'
|
||||
colorMap['6'] = '38;5;3'
|
||||
colorMap['7'] = '38;5;7'
|
||||
colorMap['8'] = '38;5;8'
|
||||
colorMap['9'] = '38;5;12'
|
||||
colorMap['a'] = '38;5;10'
|
||||
colorMap['b'] = '38;5;14'
|
||||
colorMap['c'] = '38;5;9'
|
||||
colorMap['d'] = '38;5;13'
|
||||
colorMap['e'] = '38;5;11'
|
||||
colorMap['f'] = '38;5;15'
|
||||
colorMap['r'] = '0'
|
||||
colorMap['l'] = '1'
|
||||
colorMap['n'] = '4'
|
||||
var regexMap = []
|
||||
for (const c in colorMap) {
|
||||
regexMap[colorMap[c]] = new RegExp(`§${c}`, "g")
|
||||
}
|
||||
function mcColor2ANSI(str) {
|
||||
for (const regex in regexMap) {
|
||||
str = str.replace(regexMap[regex], `\u001b[${regex}m`)
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
let jsonColorMap = {
|
||||
"black": '0',
|
||||
"dark_blue": '1',
|
||||
"dark_green": '2',
|
||||
"dark_aqua": '3',
|
||||
"dark_red": '4',
|
||||
"dark_purple": '5',
|
||||
"gold": '6',
|
||||
"gray": '7',
|
||||
"dark_gray": '8',
|
||||
"blue": '9',
|
||||
"green": 'a',
|
||||
"aqua": 'b',
|
||||
"red": 'c',
|
||||
"light_purple": 'd',
|
||||
"yellow": 'e',
|
||||
"white": 'f',
|
||||
"obfuscated": 'k',
|
||||
"bold": 'l',
|
||||
"strikethrough": 'm',
|
||||
"underline": 'n',
|
||||
"italic": 'o',
|
||||
"reset": 'r',
|
||||
};
|
||||
|
||||
function json2text(json: MessagePart): string {
|
||||
let temp = "";
|
||||
if (json.color) {
|
||||
temp += `§${jsonColorMap[json.color]}`
|
||||
}
|
||||
temp += json.text || json.translate || ''
|
||||
if (json.extra) {
|
||||
json.extra.forEach((ext) => {
|
||||
temp += json2text(ext)
|
||||
})
|
||||
}
|
||||
return temp += '§r'
|
||||
}
|
||||
|
||||
function $(input: any) {
|
||||
if (typeof input === "string") {
|
||||
input = JSON.parse(input)
|
||||
}
|
||||
input = json2text(input) + '§r'
|
||||
if (input.startsWith('§卐')) {
|
||||
input = input.substring(2)
|
||||
}
|
||||
return mcColor2ANSI(input)
|
||||
}
|
||||
|
||||
export {
|
||||
json2text,
|
||||
mcColor2ANSI,
|
||||
$
|
||||
}
|
|
@ -1,33 +0,0 @@
|
|||
import { $ } from './color'
|
||||
|
||||
export function attachEvents(client) {
|
||||
client.on('chat', (packet) => {
|
||||
// Listen for chat messages and echo them back.
|
||||
var jsonMsg = JSON.parse(packet.message)
|
||||
console.log($(jsonMsg))
|
||||
})
|
||||
client.on('state', (newState, oldState) => {
|
||||
console.log('Client Change State', oldState, 'to', newState)
|
||||
let targetServer = process.argv[6]
|
||||
if (newState == "play" && targetServer) {
|
||||
setTimeout(() => {
|
||||
client.write('chat', {
|
||||
message: '/server ' + targetServer
|
||||
})
|
||||
}, 3000)
|
||||
}
|
||||
})
|
||||
client.on('update_health', (packet) => {
|
||||
if (packet.health <= 0) {
|
||||
console.log("Player Dead Auto Respawn...")
|
||||
client.write('client_command', { payload: 0 })
|
||||
} else if (packet.health > 0) {
|
||||
}
|
||||
})
|
||||
client.on('kick_disconnect', (packet) => {
|
||||
console.log($(packet.reason))
|
||||
})
|
||||
client.on('disconnect', (packet) => {
|
||||
console.log($(packet.reason))
|
||||
})
|
||||
}
|
|
@ -1,14 +0,0 @@
|
|||
export function attachForge(client) {
|
||||
client.on('custom_payload', function(packet) {
|
||||
if (packet.channel === 'FML|HS') {
|
||||
client.write('custom_payload', {
|
||||
channel: 'FML|HS',
|
||||
data: Buffer.of(0x01, 0x02)
|
||||
});
|
||||
client.write('custom_payload', {
|
||||
channel: 'FML|HS',
|
||||
data: Buffer.of(0x02, 0x00)
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
|
@ -1,124 +0,0 @@
|
|||
import { createInterface } from 'readline'
|
||||
import { Client, createClient } from 'minecraft-protocol'
|
||||
|
||||
import { attachForge } from './forge'
|
||||
import { attachEvents } from './event'
|
||||
|
||||
let readUserInfo = process.argv[2] || 'Mr_jtb'
|
||||
let realUserInfo = readUserInfo.split(":")
|
||||
let username = realUserInfo[0]
|
||||
let password = realUserInfo[1] || ''
|
||||
let version = process.argv[3] || '1.12.2'
|
||||
let readAddress = process.argv[4] || '192.168.2.25:25565'
|
||||
let realAddress = readAddress.split(":")
|
||||
let address = realAddress[0]
|
||||
let port = parseInt(realAddress[1] || "25565")
|
||||
let client = commandLineCreateClient()
|
||||
|
||||
function commandLineCreateClient() {
|
||||
return createConnection(address, port, username, password)
|
||||
}
|
||||
|
||||
function createConnection(host: string, port: number, username: string, password: string) {
|
||||
let clientOptions: any = {
|
||||
version,
|
||||
host,
|
||||
port,
|
||||
username,
|
||||
password,
|
||||
// clientToken: 'd02c7f39-2376-45da-a5a5-50e24fa8b185',
|
||||
//@ts-ignore
|
||||
// authServer: 'https://skin.yumc.pw/api/yggdrasil/authserver',
|
||||
// sessionServer: 'https://skin.yumc.pw/api/yggdrasil/sessionserver'
|
||||
}
|
||||
if (clientOptions.password) {
|
||||
clientOptions.clientToken = 'd02c7f39-2376-45da-a5a5-50e24fa8b185'
|
||||
clientOptions.authServer = 'https://skin.yumc.pw/api/yggdrasil/authserver'
|
||||
clientOptions.sessionServer = 'https://skin.yumc.pw/api/yggdrasil/sessionserver'
|
||||
}
|
||||
let client = createClient(clientOptions)
|
||||
|
||||
attachCommon(client)
|
||||
attachForge(client)
|
||||
attachEvents(client)
|
||||
return client
|
||||
}
|
||||
|
||||
function attachCommon(client: Client) {
|
||||
client.on('login', () => {
|
||||
// client.registerChannel('updater', ['string', []])
|
||||
// client.registerChannel('updater-enabled', ['string', []])
|
||||
// client.registerChannel('dragoncore', ['string', []])
|
||||
// client.registerChannel('dragoncore:main', ['string', []])
|
||||
client.on('REGISTER', (array) => {
|
||||
for (const channel of array) {
|
||||
client.on('channel', console.log)
|
||||
}
|
||||
})
|
||||
// client.on('dragoncore:main', (data) => {
|
||||
// console.log(data)
|
||||
// })
|
||||
})
|
||||
client.on('custom_payload', (data) => {
|
||||
console.log('custom_payload' + JSON.stringify(data))
|
||||
})
|
||||
client.on('error', (error) => {
|
||||
console.log("Client Error", error)
|
||||
})
|
||||
client.on('end', (resone) => {
|
||||
console.log("Client End Resone:", resone)
|
||||
if (`${resone}` != "SocketClosed") {
|
||||
setTimeout(() => {
|
||||
client = commandLineCreateClient()
|
||||
}, 500)
|
||||
} else {
|
||||
process.exit(0)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const rl = createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
completer: (line, func) => {
|
||||
let args = line.split(' ')
|
||||
let comp = args[args.length - 1]
|
||||
client.once('tab_complete', (msg) => {
|
||||
let mcts = msg.matches.filter(s => s)
|
||||
func(null, [mcts, comp])
|
||||
})
|
||||
client.write('tab_complete', {
|
||||
text: line
|
||||
})
|
||||
},
|
||||
terminal: true,
|
||||
prompt: ''
|
||||
})
|
||||
|
||||
rl.on('line', function (line) {
|
||||
switch (line) {
|
||||
case "":
|
||||
break
|
||||
case "eval":
|
||||
break
|
||||
case "write":
|
||||
break
|
||||
case "/respawn":
|
||||
client.write('client_command', { payload: 0 })
|
||||
break
|
||||
case "//reco":
|
||||
client.end("")
|
||||
client = commandLineCreateClient()
|
||||
break
|
||||
case "//quit":
|
||||
console.info('Disconnected')
|
||||
client.end("")
|
||||
break
|
||||
case "//end":
|
||||
console.info('Forcibly ended client')
|
||||
process.exit(0)
|
||||
default:
|
||||
client.write('chat', { message: line })
|
||||
}
|
||||
rl.prompt()
|
||||
})
|
|
@ -1,5 +0,0 @@
|
|||
while :; do
|
||||
yarn emp
|
||||
echo 进程退出 休眠120秒!
|
||||
sleep 120
|
||||
done
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "@ccms/common",
|
||||
"version": "0.21.0",
|
||||
"description": "MiaoScript api package",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "MiaoScript common package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
|
@ -12,18 +12,20 @@
|
|||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.21.0",
|
||||
"@javatypes/jdk": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"@ccms/nashorn": "^0.28.0-beta.10",
|
||||
"@javatypes/jdk": "^0.0.3"
|
||||
},
|
||||
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
|
||||
}
|
||||
|
|
|
@ -19,12 +19,20 @@ interface RequestConfig {
|
|||
method?: Method
|
||||
headers?: { [key: string]: string }
|
||||
params?: { [key: string]: string }
|
||||
data?: any
|
||||
data?: any,
|
||||
connectTimeout?: number,
|
||||
readTimeout?: number,
|
||||
}
|
||||
|
||||
function request(config: RequestConfig) {
|
||||
// @ts-ignore XMLHttpRequest class only exist nashorn polyfill
|
||||
let xhr = new XMLHttpRequest()
|
||||
if (config.connectTimeout) {
|
||||
xhr.connectTimeout = config.connectTimeout
|
||||
}
|
||||
if (config.readTimeout) {
|
||||
xhr.readTimeout = config.readTimeout
|
||||
}
|
||||
xhr.open(config.method, config.url, false)
|
||||
for (const header in config.headers) {
|
||||
xhr.setRequestHeader(header, config.headers[header])
|
||||
|
|
|
@ -54,6 +54,7 @@ class Reflect {
|
|||
}
|
||||
}
|
||||
if (!field) throw new Error(`can't reflect field ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${this.class.getName()}!`)
|
||||
fieldCache.set(key, field)
|
||||
return accessible(field)
|
||||
}
|
||||
|
||||
|
@ -129,12 +130,14 @@ function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.Str
|
|||
let field = null
|
||||
// noinspection JSUnresolvedVariable
|
||||
while (target !== JavaObject.class) {
|
||||
console.debug(`reflect field ${name} from ${target.getName()}`)
|
||||
try {
|
||||
field = target.getDeclaredField(name)
|
||||
if (field !== null) { break }
|
||||
} catch (error: any) {
|
||||
if (target === undefined) { break }
|
||||
target = target.getSuperclass()
|
||||
console.debug(`switch to super class: ${target.getName()}`)
|
||||
}
|
||||
}
|
||||
if (field === null) {
|
||||
|
@ -146,21 +149,32 @@ function declaredField(clazz: java.lang.Class<any>, name: string | java.lang.Str
|
|||
function declaredMethod(clazz: java.lang.Class<any>, nameOrIndex: string | number, ...clazzs: java.lang.Class<any>[]): java.lang.reflect.Method {
|
||||
let key = clazz.getName() + '.' + nameOrIndex + ':' + (clazzs || []).map(c => c.getName()).join(':')
|
||||
if (methodCache.has(key)) { return methodCache.get(key) }
|
||||
let target = clazz
|
||||
if (typeof nameOrIndex === "number") {
|
||||
methodCache.set(key, declaredMethods(clazz)[nameOrIndex])
|
||||
} else {
|
||||
try {
|
||||
methodCache.set(key, clazz.getMethod(nameOrIndex, clazzs as any))
|
||||
} catch (ex: any) {
|
||||
while (target !== JavaObject.class && !methodCache.has(key)) {
|
||||
try {
|
||||
methodCache.set(key, clazz.getDeclaredMethod(nameOrIndex, clazzs as any))
|
||||
} catch (ex: any) {
|
||||
for (const m of Java.from(declaredMethods(clazz))) {
|
||||
if (m.getName() == nameOrIndex) {
|
||||
methodCache.set(key, m)
|
||||
break
|
||||
console.debug(`reflect method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} from ${target.getName()}`)
|
||||
try {
|
||||
methodCache.set(key, target.getMethod(nameOrIndex, clazzs as any))
|
||||
} catch (ex: any) {
|
||||
try {
|
||||
methodCache.set(key, target.getDeclaredMethod(nameOrIndex, clazzs as any))
|
||||
} catch (ex: any) {
|
||||
for (const m of Java.from(declaredMethods(target))) {
|
||||
if (m.getName() == nameOrIndex) {
|
||||
methodCache.set(key, m)
|
||||
break
|
||||
}
|
||||
}
|
||||
throw new Error(`method ${typeof nameOrIndex == "number" ? 'index' : 'name'} ${nameOrIndex} not found.`)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (target === undefined) { break }
|
||||
target = target.getSuperclass()
|
||||
console.debug(`switch to super class: ${target.getName()}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -173,7 +187,7 @@ function declaredMethods(clazz: java.lang.Class<any>) {
|
|||
}
|
||||
|
||||
function mapToObject(javaObj) {
|
||||
if (!Java.isJavaObject(javaObj)) { throw new TypeError(`参数 ${javaObj} 不是一个Java对象!`) }
|
||||
if (!Java.isJavaObject(javaObj)) { throw new TypeError(`argument ${javaObj} is not a java object.`) }
|
||||
let target = Proxy.newProxy(javaObj, {
|
||||
apply: (target, name, args) => { return args ? javaObj[name](args) : javaObj[name]() }
|
||||
})
|
||||
|
|
|
@ -17,14 +17,14 @@ class ChatMessagePart {
|
|||
}
|
||||
|
||||
convert() {
|
||||
return this.internal;
|
||||
return this.internal
|
||||
}
|
||||
}
|
||||
|
||||
class Tellraw {
|
||||
static duplicateChar = '§卐'
|
||||
static create() {
|
||||
return new Tellraw().then(Tellraw.duplicateChar);
|
||||
return new Tellraw().then(Tellraw.duplicateChar)
|
||||
}
|
||||
|
||||
private cache: string = '';
|
||||
|
@ -32,77 +32,81 @@ class Tellraw {
|
|||
|
||||
then(part: ChatMessagePart | string) {
|
||||
if (typeof part === "string") {
|
||||
var newPart = new ChatMessagePart();
|
||||
var newPart = new ChatMessagePart()
|
||||
newPart.text = part
|
||||
this.then(newPart);
|
||||
return this;
|
||||
this.then(newPart)
|
||||
return this
|
||||
}
|
||||
var last = this.latest();
|
||||
var last = this.latest()
|
||||
if (!last.text) {
|
||||
last.text = part.text;
|
||||
last.text = part.text
|
||||
} else {
|
||||
this.parts.push(part);
|
||||
this.parts.push(part)
|
||||
}
|
||||
this.cache = null;
|
||||
this.cache = null
|
||||
}
|
||||
|
||||
text(text: string) {
|
||||
this.latest().text = text;
|
||||
return this;
|
||||
this.latest().text = text
|
||||
return this
|
||||
}
|
||||
|
||||
tip(text: string) {
|
||||
this.latest().hover("show_text", text);
|
||||
return this;
|
||||
tip(texts: string) {
|
||||
return this.hover(texts)
|
||||
}
|
||||
|
||||
item(text: string) {
|
||||
this.latest().hover("show_item", text);
|
||||
return this;
|
||||
hover(texts: string) {
|
||||
this.latest().hover("show_text", texts)
|
||||
return this
|
||||
}
|
||||
|
||||
item(item: string) {
|
||||
this.latest().hover("show_item", item)
|
||||
return this
|
||||
}
|
||||
|
||||
command(command: string) {
|
||||
this.latest().click("run_command", command);
|
||||
return this;
|
||||
this.latest().click("run_command", command)
|
||||
return this
|
||||
}
|
||||
|
||||
suggest(url: string) {
|
||||
this.latest().click("suggest_command", url);
|
||||
return this;
|
||||
this.latest().click("suggest_command", url)
|
||||
return this
|
||||
}
|
||||
|
||||
file(path: string) {
|
||||
this.latest().click("open_file", path);
|
||||
return this;
|
||||
this.latest().click("open_file", path)
|
||||
return this
|
||||
}
|
||||
|
||||
link(url: string) {
|
||||
this.latest().click("open_url", url);
|
||||
return this;
|
||||
this.latest().click("open_url", url)
|
||||
return this
|
||||
}
|
||||
|
||||
latest() {
|
||||
return this.parts[this.parts.length - 1];
|
||||
return this.parts[this.parts.length - 1]
|
||||
}
|
||||
|
||||
json() {
|
||||
if (!this.cache) {
|
||||
var temp = [];
|
||||
var temp = []
|
||||
this.parts.forEach(t => {
|
||||
temp.push(t.convert());
|
||||
});
|
||||
this.cache = JSON.stringify(temp);
|
||||
console.trace(this.cache);
|
||||
temp.push(t.convert())
|
||||
})
|
||||
this.cache = JSON.stringify(temp)
|
||||
console.trace(this.cache)
|
||||
}
|
||||
return this.cache;
|
||||
return this.cache
|
||||
}
|
||||
|
||||
string() {
|
||||
var temp = '';
|
||||
var temp = ''
|
||||
this.parts.forEach(t => {
|
||||
temp += t.text
|
||||
});
|
||||
return temp;
|
||||
})
|
||||
return temp
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,35 @@
|
|||
export type Version = [string, string, string]
|
||||
|
||||
export class VersionUtils {
|
||||
static isEqual(version: string, targetVersion: string): boolean {
|
||||
return version == targetVersion
|
||||
}
|
||||
static isGreaterOrEqual(version: string, targetVersion: string): boolean {
|
||||
const v1 = parseVersion(version)
|
||||
const v2 = parseVersion(targetVersion)
|
||||
|
||||
return (
|
||||
v1[0] > v2[0] ||
|
||||
(v1[0] === v2[0] && v1[1] > v2[1]) ||
|
||||
(v1[0] === v2[0] && v1[1] === v2[1] && v1[2] >= v2[2])
|
||||
)
|
||||
}
|
||||
static isGreater(version: string, targetVersion: string): boolean {
|
||||
const v1 = parseVersion(version)
|
||||
const v2 = parseVersion(targetVersion)
|
||||
|
||||
return (
|
||||
v1[0] > v2[0] ||
|
||||
(v1[0] === v2[0] && v1[1] > v2[1]) ||
|
||||
(v1[0] === v2[0] && v1[1] === v2[1] && v1[2] > v2[2])
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function parseVersion(version: string = ""): Version {
|
||||
const v: Version = ['0', '0', '0']
|
||||
|
||||
version.split(".").forEach((value, i) => (v[i] = value))
|
||||
|
||||
return v
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@ccms/compile",
|
||||
"version": "0.21.0",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "MiaoScript compile package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
|
@ -12,15 +12,15 @@
|
|||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@ccms/container",
|
||||
"version": "0.21.0",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "MiaoScript container package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
|
@ -12,17 +12,19 @@
|
|||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.21.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"@ccms/nashorn": "^0.28.0-beta.10"
|
||||
},
|
||||
"dependencies": {
|
||||
"inversify": "^6.0.1",
|
||||
|
|
|
@ -32,18 +32,28 @@ export const provideSingletonNamed = (identifier: interfaces.ServiceIdentifier<a
|
|||
return fluentProvide(identifier).inSingletonScope().whenTargetNamed(name).done()
|
||||
}
|
||||
|
||||
export function getJavaClass(className: string) {
|
||||
try { return Java.type(className).class; return } catch (error: any) { }
|
||||
try { return base.getClass(className); return } catch (error: any) { }
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得一个 java.lang.Class
|
||||
* @param className Java全类名
|
||||
*/
|
||||
export const JavaClass = (className: string) => {
|
||||
return function (target: object, propertyKey: string, index?: number) {
|
||||
try { target[propertyKey] = Java.type(className).class; return } catch (error: any) { }
|
||||
try { target[propertyKey] = base.getClass(className); return } catch (error: any) { }
|
||||
console.warn('JavaClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
_proxyGetter(target, propertyKey, () => {
|
||||
return getJavaClass(className) || console.warn('JavaClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
}, true)
|
||||
}
|
||||
}
|
||||
|
||||
export function getJSClass(className: string) {
|
||||
try { return Java.type(className) } catch (error: any) { }
|
||||
try { return base.getClass(className).static } catch (error: any) { }
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得一个JS的Java类
|
||||
* @param className Java 全类名
|
||||
|
@ -51,9 +61,7 @@ export const JavaClass = (className: string) => {
|
|||
export const JSClass = (className: string) => {
|
||||
return function (target: object, propertyKey: string, index?: number) {
|
||||
_proxyGetter(target, propertyKey, () => {
|
||||
try { return Java.type(className) } catch (error: any) { }
|
||||
try { return base.getClass(className).static } catch (error: any) { }
|
||||
console.warn('JSClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
return getJSClass(className) || console.warn('JSClass', className, 'Inject target', target.constructor.name, 'propertyKey', propertyKey, 'failed!')
|
||||
}, true)
|
||||
}
|
||||
}
|
||||
|
@ -102,8 +110,8 @@ export const MavenDepend = (groupId: string, artifactId: string, version: string
|
|||
const loadedMavenDepend = new Set<string>()
|
||||
|
||||
export function loadMavenDepend(groupId: string, artifactId: string, version: string, recursion = false) {
|
||||
const key = `${groupId}:${artifactId}:${version}`
|
||||
try {
|
||||
const key = `${groupId}:${artifactId}:${version}`
|
||||
if (loadedMavenDepend.has(key)) { return }
|
||||
console.info('loading maven dependency', key)
|
||||
let [pom, _] = base.loadMavenDepend(groupId, artifactId, version)
|
||||
|
@ -137,7 +145,7 @@ export function loadMavenDepend(groupId: string, artifactId: string, version: st
|
|||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.warn('attachMavenDepend failed. Error: ' + error)
|
||||
console.warn('load maven dependency', key, 'failed. Error:', error)
|
||||
if (global.debug) {
|
||||
console.ex(error)
|
||||
}
|
||||
|
@ -154,8 +162,10 @@ export const reduceMetadata = (ctx: interfaces.Context): any => {
|
|||
function initAutowired(container: Container) {
|
||||
container.bind(ioc.Autowired).toDynamicValue((ctx) => {
|
||||
var metadata: any = reduceMetadata(ctx)
|
||||
let key = Object.toString.call(metadata.named)
|
||||
let key = Object.prototype.toString.call(metadata.named)
|
||||
if (key === "[object Function]" || key === "[object Symbol]") { return container.get(metadata.named) }
|
||||
console.warn('container Autowired', metadata.named, 'failed. Error: illegal serviceIdentifier type', key)
|
||||
console.debug(metadata.named, 'metadata', JSON.stringify(metadata))
|
||||
return undefined
|
||||
})
|
||||
}
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "@ccms/core",
|
||||
"version": "0.21.0",
|
||||
"description": "MiaoScript api package",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "MiaoScript core package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
|
@ -12,20 +12,28 @@
|
|||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"watch": "pnpm rollup -c rollup.config.js --watch",
|
||||
"build": "pnpm clean && pnpm rollup -c rollup.config.js",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"@rollup/plugin-typescript": "^11.1.5",
|
||||
"rollup": "^2.79.1",
|
||||
"rollup-obfuscator": "^3.0.2",
|
||||
"rollup-plugin-peer-deps-external": "^2.2.4"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.21.0",
|
||||
"@ccms/container": "^0.21.0"
|
||||
"@ccms/api": "^0.28.0-beta.10",
|
||||
"@ccms/common": "^0.28.0-beta.10",
|
||||
"@ccms/container": "^0.28.0-beta.10",
|
||||
"js-yaml": "^4.1.0"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
|
|
@ -0,0 +1,49 @@
|
|||
import typescript from '@rollup/plugin-typescript'
|
||||
import peerDepsExternal from 'rollup-plugin-peer-deps-external'
|
||||
import { obfuscator } from 'rollup-obfuscator'
|
||||
|
||||
import pkg from './package.json'
|
||||
|
||||
const external = ['path', 'fs', 'typescript', 'tslib']
|
||||
/**
|
||||
* @type {import('rollup').RollupOptions}
|
||||
*/
|
||||
export default {
|
||||
input: 'src/index.ts',
|
||||
plugins: [
|
||||
peerDepsExternal(),
|
||||
typescript(),
|
||||
obfuscator({
|
||||
compact: true,
|
||||
deadCodeInjection: true,
|
||||
deadCodeInjectionThreshold: 1,
|
||||
identifierNamesGenerator: 'mangled-shuffled',
|
||||
numbersToExpressions: true,
|
||||
simplify: true,
|
||||
stringArray: true,
|
||||
stringArrayThreshold: 1,
|
||||
stringArrayEncoding: ['rc4'],
|
||||
stringArrayCallsTransform: true,
|
||||
stringArrayCallsTransformThreshold: 1,
|
||||
stringArrayWrappersChainedCalls: true,
|
||||
stringArrayWrappersParametersMaxCount: 3,
|
||||
sourceMap: true,
|
||||
sourceMapSourcesMode: 'sources',
|
||||
inputFileName: `${pkg.name}.ts`,
|
||||
transformObjectKeys: true,
|
||||
unicodeEscapeSequence: true,
|
||||
target: 'browser-no-eval'
|
||||
}),
|
||||
],
|
||||
external,
|
||||
treeshake: false,
|
||||
output: [
|
||||
{
|
||||
format: 'cjs',
|
||||
interop: "auto",
|
||||
exports: "named",
|
||||
sourcemap: true,
|
||||
file: pkg.main || `dist/${pkg.name}.js`
|
||||
}
|
||||
]
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
script
|
|
@ -1,6 +1,6 @@
|
|||
let containerStartTime = Date.now()
|
||||
console.i18n("ms.core.ioc.initialize", { scope: global.scope })
|
||||
import { plugin, server, task, constants } from '@ccms/api'
|
||||
import { plugin, server, task, constants, console as jsconsole } from '@ccms/api'
|
||||
import { DefaultContainer as container, provideSingleton, ContainerInstance, buildProviderModule, Autowired } from '@ccms/container'
|
||||
console.i18n("ms.core.ioc.completed", { scope: global.scope, time: (Date.now() - containerStartTime) / 1000 })
|
||||
import * as yaml from 'js-yaml'
|
||||
|
@ -8,61 +8,55 @@ import http from '@ccms/common/dist/http'
|
|||
import * as fs from '@ccms/common/dist/fs'
|
||||
|
||||
const UUID = Java.type('java.util.UUID')
|
||||
const MiaoScriptAPI = Java.type('pw.yumc.MiaoScript.api.MiaoScriptAPI')
|
||||
|
||||
@provideSingleton(MiaoScriptCore)
|
||||
class MiaoScriptCore {
|
||||
@Autowired(server.Console)
|
||||
private Console: Console
|
||||
@Autowired(plugin.PluginFolder)
|
||||
private pluginFolder: string
|
||||
@Autowired()
|
||||
private taskManager: task.TaskManager
|
||||
@Autowired()
|
||||
private pluginManager: plugin.PluginManager
|
||||
|
||||
enable() {
|
||||
process.emit('core.before.enable')
|
||||
process.emit('core.before.enable', this)
|
||||
this.loadServerConsole()
|
||||
this.loadPlugins()
|
||||
process.emit('core.after.enable')
|
||||
try {
|
||||
MiaoScriptAPI.setPluginManager(this.pluginManager)
|
||||
} catch (error) {
|
||||
}
|
||||
process.emit('core.enable', this)
|
||||
process.emit('core.after.enable', this)
|
||||
console.i18n("ms.core.engine.completed", {
|
||||
loader: base.version,
|
||||
version: 'v' + global.ScriptEngineVersion,
|
||||
time: (Date.now() - global.ScriptEngineStartTime) / 1000
|
||||
})
|
||||
return () => this.disable()
|
||||
}
|
||||
|
||||
loadServerConsole() {
|
||||
process.emit('core.before.load.console')
|
||||
process.emit('core.before.load.console', this)
|
||||
//@ts-ignore
|
||||
global.setGlobal('console', new this.Console(), { writable: false, configurable: false })
|
||||
process.emit('core.after.load.console')
|
||||
}
|
||||
|
||||
loadPlugins() {
|
||||
process.emit('core.before.load.plugins')
|
||||
let loadPluginStartTime = new Date().getTime()
|
||||
console.i18n("ms.core.plugin.initialize")
|
||||
this.pluginManager.scan(this.pluginFolder)
|
||||
this.pluginManager.build()
|
||||
this.pluginManager.load(this.pluginManager.getPlugins())
|
||||
this.pluginManager.enable(this.pluginManager.getPlugins())
|
||||
console.i18n("ms.core.plugin.completed", { time: (new Date().getTime() - loadPluginStartTime) / 1000 })
|
||||
process.emit('core.after.load.plugins')
|
||||
process.emit('core.after.load.console', this)
|
||||
}
|
||||
|
||||
disable() {
|
||||
process.emit('core.before.disable')
|
||||
process.emit('core.before.disable', this)
|
||||
let disableStartTime = Date.now()
|
||||
console.i18n("ms.core.engine.disable")
|
||||
this.pluginManager.disable(this.pluginManager.getPlugins())
|
||||
this.taskManager.disable()
|
||||
process.emit('core.after.disable')
|
||||
process.emit('core.disable', this)
|
||||
process.emit('core.after.disable', this)
|
||||
loadCoreScript('exit')
|
||||
process.emit('core.before.exit')
|
||||
process.emit('core.before.exit', this)
|
||||
process.exit(0)
|
||||
process.emit('core.exit', this)
|
||||
console.i18n("ms.core.engine.disable.finish", {
|
||||
loader: base.version,
|
||||
version: 'v' + global.ScriptEngineVersion,
|
||||
time: (new Date().getTime() - disableStartTime) / 1000
|
||||
})
|
||||
process.emit('core.after.exit')
|
||||
process.emit('core.after.exit', this)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -99,7 +93,7 @@ function loadCoreScript(name) {
|
|||
try {
|
||||
let scriptname = name + (global.debug ? '-debug' : '')
|
||||
engineLoad({
|
||||
script: http.get(`https://ms.yumc.pw/api/plugin/download/name/${scriptname}`),
|
||||
script: http.get(`https://mscript.yumc.pw/api/plugin/download/name/${scriptname}`),
|
||||
name: `core/${scriptname}.js`
|
||||
})
|
||||
} catch (error: any) {
|
||||
|
@ -123,6 +117,31 @@ function loadMiaoScriptConfig() {
|
|||
global.ScriptSlowExecuteTime = global.ScriptEngineConfig.slow_execute || 50
|
||||
}
|
||||
|
||||
function createCore() {
|
||||
let corePackageStartTime = new Date().getTime()
|
||||
container.bind(ContainerInstance).toConstantValue(container)
|
||||
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance())
|
||||
container.bind(plugin.PluginFolder).toConstantValue('plugins')
|
||||
let type = detectServer()
|
||||
|
||||
process.emit('core.before.initialize.detect')
|
||||
console.i18n("ms.core.initialize.detect", { scope: global.scope, type })
|
||||
container.bind(server.ServerType).toConstantValue(type)
|
||||
container.bind(server.ServerChecker).toSelf().inSingletonScope()
|
||||
container.bind(server.NativePluginManager).toSelf().inSingletonScope()
|
||||
container.bind(server.NativePluginChecker).toSelf().inSingletonScope()
|
||||
process.emit('core.after.initialize.detect')
|
||||
|
||||
process.emit('core.before.package.initialize')
|
||||
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
|
||||
require(`${global.scope}/${type}`).default(container)
|
||||
require(`${global.scope}/plugin`)
|
||||
container.load(buildProviderModule())
|
||||
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 })
|
||||
process.emit('core.after.package.initialize')
|
||||
return container.get<MiaoScriptCore>(MiaoScriptCore)
|
||||
}
|
||||
|
||||
function initialize() {
|
||||
process.emit('core.before.initialize')
|
||||
loadMiaoScriptConfig()
|
||||
|
@ -130,43 +149,14 @@ function initialize() {
|
|||
global.setGlobal('loadCoreScript', loadCoreScript)
|
||||
loadCoreScript('initialize')
|
||||
try {
|
||||
let corePackageStartTime = new Date().getTime()
|
||||
container.bind(ContainerInstance).toConstantValue(container)
|
||||
container.bind(plugin.PluginInstance).toConstantValue(base.getInstance())
|
||||
container.bind(plugin.PluginFolder).toConstantValue('plugins')
|
||||
let type = detectServer()
|
||||
|
||||
process.emit('core.before.initialize.detect')
|
||||
console.i18n("ms.core.initialize.detect", { scope: global.scope, type })
|
||||
container.bind(server.ServerType).toConstantValue(type)
|
||||
container.bind(server.ServerChecker).toSelf().inSingletonScope()
|
||||
container.bind(server.NativePluginManager).toSelf().inSingletonScope()
|
||||
process.emit('core.after.initialize.detect')
|
||||
|
||||
process.emit('core.before.package.initialize')
|
||||
console.i18n("ms.core.package.initialize", { scope: global.scope, type })
|
||||
require(`${global.scope}/${type}`).default(container)
|
||||
require(`${global.scope}/plugin`)
|
||||
container.load(buildProviderModule())
|
||||
console.i18n("ms.core.package.completed", { scope: global.scope, type, time: (Date.now() - corePackageStartTime) / 1000 })
|
||||
process.emit('core.after.package.initialize')
|
||||
|
||||
let disable = container.get<MiaoScriptCore>(MiaoScriptCore).enable()
|
||||
console.i18n("ms.core.engine.completed", {
|
||||
loader: base.version,
|
||||
version: 'v' + global.ScriptEngineVersion,
|
||||
time: (Date.now() - global.ScriptEngineStartTime) / 1000
|
||||
})
|
||||
process.emit('core.after.initialize')
|
||||
return disable
|
||||
return createCore()
|
||||
} catch (error: any) {
|
||||
if (console.console) {
|
||||
console.i18n("ms.core.initialize.error", { error })
|
||||
console.ex(error)
|
||||
} else {
|
||||
error.printStackTrace()
|
||||
}
|
||||
return () => console.i18n('ms.core.engine.disable.abnormal')
|
||||
console.i18n("core.initialize.error", { error })
|
||||
jsconsole.getStackTrace(error, false).forEach(line => console.log(line))
|
||||
process.emit('core.initialize.error')
|
||||
return { enable: () => () => console.i18n('ms.core.engine.disable.abnormal') }
|
||||
} finally {
|
||||
process.emit('core.after.initialize')
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@ccms/database",
|
||||
"version": "0.21.0",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "MiaoScript database package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
|
@ -12,20 +12,22 @@
|
|||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/spring-jdbc": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"@javatypes/spring-jdbc": "^0.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.21.0",
|
||||
"@ccms/container": "^0.21.0"
|
||||
"@ccms/api": "^0.28.0-beta.10",
|
||||
"@ccms/container": "^0.28.0-beta.10"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
import { database } from '@ccms/api'
|
||||
import { JSClass, postConstruct } from '@ccms/container'
|
||||
import { JSClass } from '@ccms/container'
|
||||
|
||||
const Thread = Java.type('java.lang.Thread')
|
||||
const JavaString = Java.type('java.lang.String')
|
||||
const Properties = Java.type('java.util.Properties')
|
||||
|
||||
/**
|
||||
|
@ -25,9 +27,21 @@ export class DataBase extends database.DataBase {
|
|||
|
||||
private createDataSource(dbConfig: database.DataBaseConfig) {
|
||||
if (typeof dbConfig.url === "string") {
|
||||
let originClassLoader = Thread.currentThread().getContextClassLoader()
|
||||
Thread.currentThread().setContextClassLoader(base.getInstance().class.classLoader)
|
||||
let config = new this.HikariConfig()
|
||||
if (dbConfig.driverClassName) {
|
||||
config.setDriverClassName(dbConfig.driverClassName)
|
||||
} else {
|
||||
switch (dbConfig.type) {
|
||||
case "h2":
|
||||
config.setDriverClassName("org.h2.Driver")
|
||||
break
|
||||
case "sqlite":
|
||||
config.setDriverClassName("org.sqlite.JDBC")
|
||||
break
|
||||
default:
|
||||
}
|
||||
}
|
||||
if (dbConfig.username) {
|
||||
config.setUsername(dbConfig.username)
|
||||
|
@ -43,15 +57,17 @@ export class DataBase extends database.DataBase {
|
|||
}
|
||||
config.setDataSourceProperties(properties)
|
||||
}
|
||||
console.debug('createDataSource from config ' + JSON.stringify(dbConfig))
|
||||
this.dataSource = new this.HikariDataSource(config)
|
||||
Thread.currentThread().setContextClassLoader(originClassLoader)
|
||||
} else {
|
||||
this.dataSource = dbConfig.url
|
||||
}
|
||||
this.jdbcTemplate = new this.JdbcTemplate(this.dataSource)
|
||||
}
|
||||
|
||||
@postConstruct()
|
||||
private initialize() {
|
||||
this.jdbcTemplate = new this.JdbcTemplate(this.dataSource)
|
||||
getDataSource() {
|
||||
return this.dataSource
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -62,7 +78,7 @@ export class DataBase extends database.DataBase {
|
|||
query<T>(sql: string, ...args: any[]): Array<T> {
|
||||
let startTime = Date.now()
|
||||
let result = Java.from<any>(this.jdbcTemplate.queryForList(sql, args))
|
||||
console.debug(java.lang.String.format(`\n[DB] query \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
console.debug(JavaString.format(`\n[DB] query \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
return result
|
||||
}
|
||||
|
||||
|
@ -74,7 +90,7 @@ export class DataBase extends database.DataBase {
|
|||
update(sql: string, ...args: any[]): number {
|
||||
let startTime = Date.now()
|
||||
let result = this.jdbcTemplate.update(sql, args)
|
||||
console.debug(java.lang.String.format(`\n[DB] update \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
console.debug(JavaString.format(`\n[DB] update \nSQL : ${sql.replace(/\?/ig, '%s')} \nCOST : ${Date.now() - startTime}ms`, args))
|
||||
return result
|
||||
}
|
||||
|
||||
|
@ -85,7 +101,7 @@ export class DataBase extends database.DataBase {
|
|||
execute(sql: string): void {
|
||||
let startTime = Date.now()
|
||||
this.jdbcTemplate.execute(sql)
|
||||
console.debug(java.lang.String.format(`\n[DB] execute \nSQL : sql} \nCOST : ${Date.now() - startTime}ms`))
|
||||
console.debug(`\n[DB] execute \nSQL : ${sql} \nCOST : ${Date.now() - startTime}ms`)
|
||||
}
|
||||
|
||||
close() {
|
||||
|
|
|
@ -1,7 +0,0 @@
|
|||
import 'reflect-metadata'
|
||||
|
||||
export function id() {
|
||||
return (target: Object, propertyKey: string | symbol) => void {
|
||||
|
||||
}
|
||||
}
|
|
@ -1,5 +1,5 @@
|
|||
import { database } from '@ccms/api'
|
||||
import { provideSingleton } from '@ccms/container'
|
||||
import { JSClass, provideSingleton } from '@ccms/container'
|
||||
import { DataBase } from './database'
|
||||
|
||||
@provideSingleton(database.DataBaseManager)
|
||||
|
@ -7,11 +7,32 @@ export class DataBaseManager extends database.DataBaseManager {
|
|||
private mainDatabase: DataBase
|
||||
private databases = new Map<string, DataBase>()
|
||||
|
||||
@JSClass('org.h2.tools.Server')
|
||||
private Server: any
|
||||
|
||||
private webManager: any
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
process.on('exit', () => this.disable())
|
||||
process.on('exit', () => this.shutdown())
|
||||
}
|
||||
|
||||
startWebManager(...args: string[]) {
|
||||
this.webManager = this.Server.createWebServer(args)
|
||||
this.webManager.start()
|
||||
}
|
||||
|
||||
stopWebManager() {
|
||||
if (this.webManager) {
|
||||
this.webManager.stop()
|
||||
this.webManager.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
shutdown() {
|
||||
this.stopWebManager()
|
||||
this.disable()
|
||||
}
|
||||
/**
|
||||
* 设置主数据库
|
||||
* @param mainDatabase 主数据库
|
||||
|
|
|
@ -1,11 +0,0 @@
|
|||
import { DataBase } from "./database"
|
||||
|
||||
export class Model<T> {
|
||||
constructor(private database: DataBase) {
|
||||
|
||||
}
|
||||
queryForList(): Array<T> {
|
||||
|
||||
return []
|
||||
}
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -34,7 +34,7 @@ ms.api.command.tab.completer.slow: "§c注意! §6玩家 §a{player} §6执行
|
|||
ms.api.command.tab.completer.error: "§6玩家 §a{player} §6执行 §b{plugin} §6插件 §d{command} {args} §6补全时发生异常 §4{ex}"
|
||||
|
||||
ms.plugin.initialize: "初始化 MiaoScript 插件系统: 实例: {plugin} 加载器: {loader}..."
|
||||
ms.plugin.event.map: "总计 {count} 个 {type} 事件 映射完成..."
|
||||
ms.plugin.event.map: "映射 {type} 事件 成功 总计 {count} 个 {type} 事件..."
|
||||
ms.plugin.event.map.error: "映射 {type} 事件 异常 将无法使用事件简称. Error: {error}"
|
||||
ms.plugin.manager.scan: "扫描器 {scanner} 扫描 {folder} 中的插件..."
|
||||
ms.plugin.manager.scan.finish: "扫描器 {scanner} 在 {folder} 中 发现 {size} 个插件 开始编译..."
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@ccms/i18n",
|
||||
"version": "0.21.0",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "MiaoScript i18n package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
|
@ -12,18 +12,21 @@
|
|||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map",
|
||||
"languages"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.21.0",
|
||||
"@types/js-yaml": "^4.0.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"@ccms/nashorn": "^0.28.0-beta.10",
|
||||
"@types/js-yaml": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"js-yaml": "^4.1.0"
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,36 +0,0 @@
|
|||
{
|
||||
"name": "@ccms/keyvalue",
|
||||
"version": "0.21.0",
|
||||
"description": "MiaoScript keyvalue package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
"bukkit",
|
||||
"sponge"
|
||||
],
|
||||
"author": "MiaoWoo <admin@yumc.pw>",
|
||||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.21.0",
|
||||
"@ccms/common": "^0.21.0",
|
||||
"@ccms/container": "^0.21.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.21.0",
|
||||
"@javatypes/amqp-client": "^0.0.3",
|
||||
"@javatypes/spring-amqp": "^0.0.3",
|
||||
"@javatypes/spring-rabbit": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
},
|
||||
"gitHead": "2589633069d24f646ac09261b1b2304c21d4ea75"
|
||||
}
|
|
@ -1,3 +0,0 @@
|
|||
/// <reference types="@ccms/nashorn" />
|
||||
/// <reference types="@javatypes/jdk" />
|
||||
export { }
|
|
@ -1,7 +0,0 @@
|
|||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "src",
|
||||
"outDir": "dist"
|
||||
}
|
||||
}
|
|
@ -1,13 +1,18 @@
|
|||
{
|
||||
"name": "@ccms/molang",
|
||||
"version": "0.21.0",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "A fast parser for Minecraft's MoLang",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"repository": {
|
||||
|
@ -21,9 +26,6 @@
|
|||
},
|
||||
"homepage": "https://github.com/solvedDev/MoLang#readme",
|
||||
"devDependencies": {
|
||||
"@types/node": "^17.0.25",
|
||||
"rimraf": "^3.0.2",
|
||||
"tslib": "^2.3.1",
|
||||
"typescript": "^4.6.3"
|
||||
"@types/node": "^18.17.15"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "@ccms/nashorn",
|
||||
"version": "0.21.0",
|
||||
"description": "MiaoScript api package",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "MiaoScript nashorn package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
|
@ -13,15 +13,15 @@
|
|||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -48,7 +48,10 @@ declare global {
|
|||
scope: string
|
||||
logger: any
|
||||
debug: boolean
|
||||
level: string
|
||||
/**
|
||||
* 引擎日志等级
|
||||
*/
|
||||
ScriptEngineLoggerLevel: string
|
||||
/**
|
||||
* 引擎配置
|
||||
*/
|
||||
|
@ -61,8 +64,18 @@ declare global {
|
|||
* 引擎渠道
|
||||
*/
|
||||
ScriptEngineChannel: string
|
||||
/**
|
||||
* 慢执行检测时间
|
||||
*/
|
||||
ScriptSlowExecuteTime: number
|
||||
ScriptEngineStartTime: number
|
||||
/**
|
||||
* 设置全局对象
|
||||
* @param key 对象名称
|
||||
* @param value 对象值
|
||||
* @param config 对象属性
|
||||
* @returns
|
||||
*/
|
||||
setGlobal: (key: string, value: any, config?: PropertyDescriptor & ThisType<any>) => void
|
||||
noop: () => void
|
||||
console: Console
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@ccms/nodejs",
|
||||
"version": "0.21.0",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "MiaoScript nodejs package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
|
@ -12,18 +12,19 @@
|
|||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ccms/nashorn": "^0.21.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"tslib": "^2.3.1",
|
||||
"typescript": "^4.6.3"
|
||||
"@ccms/nashorn": "^0.28.0-beta.10"
|
||||
},
|
||||
"gitHead": "781524f83e52cad26d7c480513e3c525df867121"
|
||||
}
|
||||
|
|
|
@ -20,6 +20,7 @@
|
|||
// USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
'use strict';
|
||||
var Throwable = Java.type('java.lang.Throwable')
|
||||
var R = typeof Reflect === 'object' ? Reflect : null
|
||||
var ReflectApply = R && typeof R.apply === 'function'
|
||||
? R.apply
|
||||
|
@ -136,13 +137,19 @@ EventEmitter.prototype.emit = function emit(type) {
|
|||
var er;
|
||||
if (args.length > 0)
|
||||
er = args[0];
|
||||
if (er instanceof Error) {
|
||||
if (er instanceof Error || er instanceof Throwable) {
|
||||
// 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
|
||||
}
|
||||
if (er.error instanceof Error || er.error instanceof Throwable) {
|
||||
throw er.error; // Unhandled 'error' event
|
||||
}
|
||||
if (er.cause instanceof Error || er.cause instanceof Throwable) {
|
||||
throw er.cause; // Unhandled 'error' event
|
||||
}
|
||||
// At least give some kind of context to the user
|
||||
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
|
||||
var err = new Error('Unhandled error.' + (er ? ' (' + (er.message || er.error || er.cause || er) + ')' : ''));
|
||||
// @ts-ignore
|
||||
err.context = er;
|
||||
throw err; // Unhandled 'error' event
|
||||
|
|
|
@ -5,6 +5,7 @@ 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 Paths = Java.type("java.nio.file.Paths");
|
||||
const Collector = Java.type("java.util.stream.Collector")
|
||||
const separatorChar = File.separatorChar;
|
||||
const StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
|
||||
|
@ -37,7 +38,7 @@ function javaFile(...opts: any[]) {
|
|||
}
|
||||
|
||||
export function renameSync(oldPath: PathLike, newPath: PathLike): void {
|
||||
|
||||
Files.move(Paths.get(oldPath), Paths.get(oldPath), StandardCopyOption['ATOMIC_MOVE'])
|
||||
}
|
||||
export function truncateSync() {
|
||||
|
||||
|
|
|
@ -715,6 +715,7 @@ function callbackify(original) {
|
|||
// implications (stack, `uncaughtException`, `async_hooks`)
|
||||
// @ts-ignore
|
||||
original.apply(this, args)
|
||||
// @ts-ignore
|
||||
.then(function (ret) { process.nextTick(cb.bind(null, null, ret)) },
|
||||
function (rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) });
|
||||
}
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@ccms/nukkit",
|
||||
"version": "0.21.0",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "MiaoScript nukkit package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
|
@ -12,21 +12,23 @@
|
|||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@javatypes/nukkit-api": "^0.0.3",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"@javatypes/nukkit-api": "^0.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.21.0",
|
||||
"@ccms/common": "^0.21.0",
|
||||
"@ccms/container": "^0.21.0"
|
||||
"@ccms/api": "^0.28.0-beta.10",
|
||||
"@ccms/common": "^0.28.0-beta.10",
|
||||
"@ccms/container": "^0.28.0-beta.10"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
../../.npmignore
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "@ccms/plugin",
|
||||
"version": "0.21.0",
|
||||
"description": "MiaoScript api package",
|
||||
"version": "0.28.0-beta.10",
|
||||
"description": "MiaoScript plugin package",
|
||||
"keywords": [
|
||||
"miaoscript",
|
||||
"minecraft",
|
||||
|
@ -12,25 +12,27 @@
|
|||
"homepage": "https://github.com/circlecloud/ms.git",
|
||||
"license": "ISC",
|
||||
"main": "dist/index.js",
|
||||
"files": [
|
||||
"dist/**/*.js",
|
||||
"dist/**/*.ts",
|
||||
"dist/**/*.map"
|
||||
],
|
||||
"scripts": {
|
||||
"clean": "rimraf dist",
|
||||
"watch": "tsc --watch",
|
||||
"build": "yarn clean && tsc",
|
||||
"build": "pnpm clean && tsc",
|
||||
"test": "echo \"Error: run tests from root\" && exit 1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/crypto-js": "^4.1.1",
|
||||
"@types/js-yaml": "^4.0.5",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"typescript": "^4.6.3"
|
||||
"@types/crypto-js": "^4.1.2",
|
||||
"@types/js-yaml": "^4.0.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ccms/api": "^0.21.0",
|
||||
"@ccms/common": "^0.21.0",
|
||||
"@ccms/container": "^0.21.0",
|
||||
"@ccms/i18n": "^0.21.0",
|
||||
"@ccms/verify": "^0.21.1",
|
||||
"@ccms/api": "^0.28.0-beta.10",
|
||||
"@ccms/common": "^0.28.0-beta.10",
|
||||
"@ccms/container": "^0.28.0-beta.10",
|
||||
"@ccms/i18n": "^0.28.0-beta.10",
|
||||
"@ccms/verify": "^0.26.1",
|
||||
"crypto-js": "^4.1.1",
|
||||
"js-yaml": "^4.1.0"
|
||||
}
|
||||
|
|
|
@ -15,51 +15,51 @@ export class PluginCommandManager {
|
|||
process.on('plugin.after.disable', this.unregistryCommand.bind(this))
|
||||
}
|
||||
|
||||
private registryCommand(pluginInstance: plugin.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
let tabs = getPluginTabCompleterMetadata(pluginInstance)
|
||||
public registryCommand(pluginInstance: plugin.Plugin, executor: any = pluginInstance) {
|
||||
let cmds = getPluginCommandMetadata(executor)
|
||||
let tabs = getPluginTabCompleterMetadata(executor)
|
||||
for (const cmd of cmds) {
|
||||
if (!this.ServerChecker.check(cmd.servers)) {
|
||||
console.debug(`[${pluginInstance.description.name}] ${cmd.target.constructor.name} incompatible command ${cmd.name} server(${cmd.servers}) ignore.`)
|
||||
continue
|
||||
}
|
||||
for (let command of [cmd.name, ...cmd.alias]) {
|
||||
let [cmdExecutor, cmdCompleter] = this.generateAutoMainCommand(pluginInstance, cmd, tabs.get(command))
|
||||
let [cmdExecutor, cmdCompleter] = this.generateAutoMainCommand(pluginInstance, executor, cmd, tabs.get(command))
|
||||
this.CommandManager.on(pluginInstance, command, {
|
||||
cmd: cmdExecutor.bind(pluginInstance),
|
||||
tab: cmdCompleter?.bind(pluginInstance)
|
||||
cmd: cmdExecutor.bind(executor),
|
||||
tab: cmdCompleter?.bind(executor)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private unregistryCommand(pluginInstance: plugin.Plugin) {
|
||||
let cmds = getPluginCommandMetadata(pluginInstance)
|
||||
public unregistryCommand(pluginInstance: plugin.Plugin, executor: any = pluginInstance) {
|
||||
let cmds = getPluginCommandMetadata(executor)
|
||||
for (const cmd of cmds) {
|
||||
if (!this.ServerChecker.check(cmd.servers)) {
|
||||
console.debug(`[${pluginInstance.description.name}] ${cmd.target.constructor.name} incompatible command ${cmd.name} server(${cmd.servers}) ignore.`)
|
||||
continue
|
||||
}
|
||||
for (let command of [cmd.name, ...cmd.alias]) {
|
||||
this.CommandManager.off(pluginInstance, command)
|
||||
this.CommandManager.off(executor, command)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private generateAutoMainCommand(pluginInstance: plugin.Plugin, cmd: interfaces.CommandMetadata, tab: interfaces.CommandMetadata) {
|
||||
let cmdExecutor = pluginInstance[cmd.executor]
|
||||
let cmdCompleter = tab ? pluginInstance[tab.executor] : undefined
|
||||
let cmdSubCache = Object.keys(pluginInstance.constructor.prototype).filter(s => s.startsWith('cmd')).map(s => s.substring(3))
|
||||
private generateAutoMainCommand(pluginInstance: plugin.Plugin, executor: any, cmd: interfaces.CommandMetadata, tab: interfaces.CommandMetadata) {
|
||||
let cmdExecutor = executor[cmd.executor]
|
||||
let cmdCompleter = tab ? executor[tab.executor] : undefined
|
||||
let cmdSubCache = Object.keys(executor.constructor.prototype).filter(s => s.startsWith('cmd')).map(s => s.substring(3))
|
||||
if (cmd.autoMain) {
|
||||
cmdExecutor = (sender: any, command: string, args: string[]) => {
|
||||
let subcommand = args[0]
|
||||
let cmdKey = 'cmd' + subcommand
|
||||
if (!cmdSubCache.includes(subcommand)) {
|
||||
if (!pluginInstance[cmd.executor].apply(pluginInstance, [sender, command, args])) {
|
||||
if (!executor[cmd.executor].apply(executor, [sender, command, args])) {
|
||||
subcommand && pluginInstance.logger.sender(sender, `§4未知的命令: §b/${command} §c${subcommand}`)
|
||||
pluginInstance.logger.sender(
|
||||
sender,
|
||||
pluginInstance['cmdhelp'] ?
|
||||
executor['cmdhelp'] ?
|
||||
`§6请执行 §b/${command} §ahelp §6查看帮助!` :
|
||||
[
|
||||
`§6插件: §b${pluginInstance.description.name}`,
|
||||
|
@ -69,7 +69,7 @@ export class PluginCommandManager {
|
|||
}
|
||||
return
|
||||
}
|
||||
let subcommandexec = pluginInstance[cmdKey]
|
||||
let subcommandexec = executor[cmdKey]
|
||||
let permission: string
|
||||
if (cmd.permission && sender.hasPermission) {
|
||||
if (typeof cmd.permission == "string") {
|
||||
|
@ -78,11 +78,11 @@ export class PluginCommandManager {
|
|||
permission = `${pluginInstance.description.name.toLocaleLowerCase()}.${command}.${subcommand || 'main'}`
|
||||
}
|
||||
if (!sender.hasPermission(permission)) {
|
||||
return pluginInstance.logger.sender(sender, `§c你需要 ${permission} 权限 才可执行此命令.`)
|
||||
return pluginInstance.logger.sender(sender, `§c你需要 §4${permission} §c权限 才可执行此命令.`)
|
||||
}
|
||||
}
|
||||
args.shift()
|
||||
return subcommandexec.apply(pluginInstance, [sender, ...args])
|
||||
return subcommandexec.apply(executor, [sender, ...args])
|
||||
}
|
||||
let originCompleter = cmdCompleter
|
||||
cmdCompleter = (sender: any, command: string, args: string[]) => {
|
||||
|
@ -95,10 +95,10 @@ export class PluginCommandManager {
|
|||
}
|
||||
if (!sender.hasPermission(permission)) { return [] }
|
||||
}
|
||||
return (args.length == 1 ? cmdSubCache : []).concat(originCompleter?.apply(pluginInstance, [sender, command, args]) || [])
|
||||
return (args.length == 1 ? cmdSubCache : []).concat(originCompleter?.apply(executor, [sender, command, args]) || [])
|
||||
}
|
||||
}
|
||||
if (!cmdCompleter) { console.warn(`[${pluginInstance.description.name}] command ${cmd.name} is not registry tabCompleter`) }
|
||||
if (!cmdCompleter) { console.debug(`[${pluginInstance.description.name}] command ${cmd.name} is not registry tabCompleter`) }
|
||||
return [cmdExecutor, cmdCompleter]
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,13 +7,14 @@ import { interfaces } from './interfaces'
|
|||
import { getPluginConfigMetadata } from './utils'
|
||||
|
||||
import { PluginConfigLoader } from './config/interfaces'
|
||||
import './config/loader/json-loader'
|
||||
import './config/loader/yaml-loader'
|
||||
import './config/loader'
|
||||
|
||||
@provideSingleton(PluginConfigManager)
|
||||
export class PluginConfigManager {
|
||||
@Autowired(ContainerInstance)
|
||||
private container: Container
|
||||
@Autowired(plugin.PluginFolder)
|
||||
private pluginFolder: string
|
||||
|
||||
private configLoaderMap = new Map<string, PluginConfigLoader>()
|
||||
|
||||
|
@ -32,7 +33,7 @@ export class PluginConfigManager {
|
|||
}
|
||||
|
||||
getConfigLoader(format: string) {
|
||||
if (!this.configLoaderMap.has(format)) { throw new Error(`Unsupport config format ${format} !`) }
|
||||
if (!this.configLoaderMap.has(format)) { throw new Error(`unsupport config format ${format} !`) }
|
||||
return this.configLoaderMap.get(format)
|
||||
}
|
||||
|
||||
|
@ -68,30 +69,26 @@ export class PluginConfigManager {
|
|||
private loadConfig0(plugin: plugin.Plugin, metadata: interfaces.ConfigMetadata) {
|
||||
try {
|
||||
let defaultValue = metadata.default ?? plugin[metadata.variable]
|
||||
let configValue = defaultValue || {}
|
||||
if (defaultValue) {
|
||||
metadata.file = fs.concat(
|
||||
fs.file(plugin.description.loadMetadata.file).parent,
|
||||
plugin.description.name,
|
||||
metadata.filename
|
||||
)
|
||||
let configLoader = this.getConfigLoader(metadata.format)
|
||||
if (!fs.exists(metadata.file)) {
|
||||
base.save(metadata.file, configLoader.dump(defaultValue))
|
||||
console.i18n("ms.plugin.manager.config.save.default", {
|
||||
plugin: plugin.description.name,
|
||||
name: metadata.name,
|
||||
format: metadata.format
|
||||
})
|
||||
} else {
|
||||
configValue = configLoader.load(base.read(metadata.file)) || {}
|
||||
if (defaultValue && this.setDefaultValue(configValue, defaultValue, !!metadata.default)) {
|
||||
base.save(metadata.file, configLoader.dump(configValue))
|
||||
}
|
||||
console.debug(`[${plugin.description.name}] Load Config ${metadata.variable} from file ${metadata.file} =>
|
||||
${JSON.stringify(configValue, undefined, 4).substring(0, 500)}`)
|
||||
}
|
||||
metadata.file = fs.concat(
|
||||
root,
|
||||
this.pluginFolder,
|
||||
plugin.description.name,
|
||||
metadata.filename
|
||||
)
|
||||
let configLoader = this.getConfigLoader(metadata.format)
|
||||
if (!fs.exists(metadata.file) && defaultValue) {
|
||||
base.save(metadata.file, configLoader.dump(defaultValue))
|
||||
console.i18n("ms.plugin.manager.config.save.default", {
|
||||
plugin: plugin.description.name,
|
||||
name: metadata.name,
|
||||
format: metadata.format
|
||||
})
|
||||
}
|
||||
let configValue = configLoader.load(base.read(metadata.file)) || {}
|
||||
if (metadata.migrate && defaultValue && this.setDefaultValue(configValue, defaultValue, !!metadata.default)) {
|
||||
base.save(metadata.file, configLoader.dump(configValue))
|
||||
}
|
||||
console.debug(`[${plugin.description.name}] load config ${metadata.variable} from file ${metadata.file}`)
|
||||
this.defienConfigProp(plugin, metadata, configValue)
|
||||
} catch (error: any) {
|
||||
console.i18n("ms.plugin.manager.config.load.error", {
|
||||
|
@ -124,7 +121,7 @@ ${JSON.stringify(configValue, undefined, 4).substring(0, 500)}`)
|
|||
metadata.file = fs.concat(fs.file(plugin.description.loadMetadata.file).parent, plugin.description.name, metadata.filename)
|
||||
let result = this.getConfigLoader(metadata.format).dump(plugin[metadata.variable])
|
||||
base.save(metadata.file, result)
|
||||
console.debug(`[${plugin.description.name}] Save Config ${metadata.variable} to file ${metadata.file} =>
|
||||
console.debug(`[${plugin.description.name}] save config ${metadata.variable} to file ${metadata.file} =>
|
||||
${result.substring(0, 500)}`)
|
||||
return true
|
||||
} catch (error: any) {
|
||||
|
|
|
@ -76,6 +76,7 @@ export function config(metadata: interfaces.ConfigMetadata = {}) {
|
|||
metadata.variable = key
|
||||
metadata.version = metadata.version ?? 1
|
||||
metadata.format = metadata.format ?? 'yml'
|
||||
metadata.migrate = metadata.migrate ?? true
|
||||
metadata.autosave = metadata.autosave ?? false
|
||||
metadata.filename = metadata.filename ?? metadata.name + '.' + metadata.format
|
||||
let previousMetadata = getPluginConfigMetadata(target)
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue