feat: 格式化代码 添加d.ts文件 去除引擎无关代码 清理单元测试

This commit is contained in:
502647092 2018-05-17 18:30:40 +08:00
parent 967e7d1beb
commit 88d71abb2a
44 changed files with 494 additions and 565 deletions

View File

@ -1,19 +1,8 @@
package pw.yumc.MiaoScript;
import java.io.File;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.java.JavaPlugin;
import lombok.SneakyThrows;
import lombok.val;
import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.commands.CommandSub;
import pw.yumc.YumCore.commands.annotation.Cmd;
import pw.yumc.YumCore.commands.annotation.Help;
import pw.yumc.YumCore.commands.interfaces.Executor;
/**
* 喵式脚本
@ -21,62 +10,14 @@ import pw.yumc.YumCore.commands.interfaces.Executor;
* @author
* @since 2016年8月29日 上午7:50:39
*/
public class MiaoScript extends JavaPlugin implements Executor {
public class MiaoScript extends JavaPlugin {
private ScriptEngine engine;
@Override
@SneakyThrows
public void onEnable() {
new CommandSub("ms", this);
engine = new ScriptEngine(getDataFolder().getCanonicalPath(), getLogger());
enableEngine();
}
@Cmd
@Help("执行 JS 代码")
@SneakyThrows
public void js(CommandSender sender, String script) {
result(sender, engine.getEngine().eval(script));
}
@Cmd
@Help("执行 JS 代码文件")
@SneakyThrows
public void file(CommandSender sender, String file) {
result(sender, engine.getEngine().eval("load('" + new File(getDataFolder(), file).getCanonicalPath() + "')"));
}
@Cmd
@Help("重启脚本引擎")
public void reload(CommandSender sender) {
engine.disableEngine();
val server = Bukkit.getServer();
try {
server.getScheduler().cancelTasks(this);
server.getServicesManager().unregisterAll(this);
HandlerList.unregisterAll(this);
server.getMessenger().unregisterIncomingPluginChannel(this);
server.getMessenger().unregisterOutgoingPluginChannel(this);
} catch (Exception ex) {
Log.d("Error reload", ex);
}
enableEngine();
Log.sender(sender, "§bMiaoScript §eEngine §a重启完成!");
}
private void result(CommandSender sender, Object result) {
if (result == null) {
Log.sender(sender, "§a运行成功! §c没有返回结果!");
} else {
Log.sender(sender, "§a运行成功! §b数据类型: §r%s §d结果: §r%s", result.getClass().getName(), result);
}
}
private void enableEngine() {
val origin = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClassLoader());
engine.enableEngine();
Thread.currentThread().setContextClassLoader(origin);
}
@Override

View File

@ -1,23 +1,13 @@
package pw.yumc.MiaoScript;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.script.ScriptException;
import org.slf4j.Logger;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameInitializationEvent;
import org.spongepowered.api.event.game.state.GameStartedServerEvent;
import org.spongepowered.api.event.game.state.GameStoppingServerEvent;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.text.Text;
import com.google.inject.Inject;
import lombok.SneakyThrows;
@ -38,78 +28,16 @@ public class MiaoScriptSponge {
@ConfigDir(sharedRoot = false)
private File pluginConfigDir;
@Listener
public void onInit(GameInitializationEvent event) {
}
private CommandSpec main() {
return CommandSpec.builder()
.description(Text.of("喵式脚本主命令"))
.permission("MiaoScript.admin")
.child(js(), "js")
.child(file(), "file")
.child(reload(), "reload")
.build();
}
private CommandSpec js() {
return CommandSpec.builder()
.description(Text.of("执行JS命令"))
.arguments(GenericArguments.onlyOne(GenericArguments.remainingJoinedStrings(Text.of("js"))))
.executor((src, args) -> {
try {
result(src, engine.getEngine().eval(args.<String>getOne("js").orElse("")));
} catch (ScriptException e) {
e.printStackTrace();
}
return CommandResult.success();
})
.build();
}
private CommandSpec file() {
return CommandSpec.builder()
.description(Text.of("执行JS文件"))
.arguments(GenericArguments.onlyOne(GenericArguments.remainingJoinedStrings(Text.of("js"))))
.executor((src, args) -> {
try {
result(src, engine.getEngine().eval(new FileReader(new File(pluginConfigDir, args.<String>getOne("js").orElse("")))));
} catch (ScriptException | IOException e) {
e.printStackTrace();
}
return CommandResult.success();
})
.build();
}
private CommandSpec reload() {
return CommandSpec.builder()
.description(Text.of("重载 JS 引擎"))
.executor((src, args) -> {
engine.disableEngine();
Sponge.getEventManager().unregisterPluginListeners(this);
engine.enableEngine();
src.sendMessage(Text.of("§6[§bMiaoScript§6]§r §bMiaoScript §eEngine §a重启完成!"));
return CommandResult.success();
})
.build();
}
private void result(CommandSource sender, Object result) {
if (result == null) {
sender.sendMessage(Text.of("§a运行成功! §c没有返回结果!"));
} else {
sender.sendMessage(Text.of(String.format("§a运行成功! §b数据类型: §r%s §d结果: §r%s", result.getClass().getName(), result)));
}
}
@Listener
@SneakyThrows
public void onStart(GameStartedServerEvent event) {
Sponge.getServer().getConsole();
Sponge.getCommandManager().register(this, main(), "ms", "mscript", "MiaoScript");
engine = new ScriptEngine(pluginConfigDir.getCanonicalPath(), logger);
engine.enableEngine();
}
@Listener
@SneakyThrows
public void onStop(GameStoppingServerEvent event) {
engine.disableEngine();
}
}

View File

@ -31,6 +31,7 @@ public class ScriptEngine {
ScriptEngineManager manager = new ScriptEngineManager();
this.engine = new MiaoScriptEngine(manager, "nashorn");
this.engine.put("base", new Base());
this.engine.put("ScriptEngineContextHolder", this);
Path bios = Paths.get(root, "bios.js");
// 如果存在自定义bios就加载自定义的
if (Files.exists(bios)) {

View File

@ -1,51 +0,0 @@
package pw.yumc.MiaoScript;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
/**
* Created with IntelliJ IDEA
*
* @author
* Created on 2017/9/30 21:32.
*/
public class ScriptEvent extends Event implements Cancellable {
private ScriptObjectMirror mirror;
private boolean cancelled = false;
public ScriptEvent(ScriptObjectMirror mirror) {
this.mirror = mirror;
}
public ScriptObjectMirror getMirror() {
return mirror;
}
public void setMirror(ScriptObjectMirror mirror) {
this.mirror = mirror;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}
private static HandlerList handlerList = new HandlerList();
public static HandlerList getHandlerList() {
return handlerList;
}
@Override
public HandlerList getHandlers() {
return handlerList;
}
}

View File

@ -1,5 +1,6 @@
/*global Java, base, module, exports, require*/
function ChatHandlerDefault() {
// noinspection JSUnusedGlobalSymbols
this.tellraw = function(sender, raw) {
this.json(sender, JSON.stringify(raw));
}

View File

@ -2,16 +2,19 @@
/**
* Bukkit 事件相关类
*/
/*global Java, base, module, exports, require, __FILE__*/
function EventHandlerDefault() {
var Thread = Java.type("java.lang.Thread");
// noinspection JSUnresolvedVariable
this.plugin = require('./server').plugin.self;
this.mapEvent = [];
this.listenerMap = [];
this.baseEventDir = '';
// noinspection JSUnusedLocalSymbols
var self = this;
/**
@ -40,9 +43,10 @@ function EventHandlerDefault() {
try {
var clz = base.getClass(i.substring(0, i.length - 6));
// 继承于 org.bukkit.event.Event 访问符为Public
if (this.isVaildEvent(clz)) {
if (this.isValidEvent(clz)) {
// noinspection JSUnresolvedVariable
var simpleName = this.class2Name(clz).toLowerCase();
/** @namespace clz.canonicalName */
console.debug("Mapping Event [%s] => %s".format(clz.canonicalName, simpleName));
this.mapEvent[simpleName] = clz;
count++;
@ -55,11 +59,11 @@ function EventHandlerDefault() {
}
}
return count;
}
};
this.class2Name = function class2Name(clazz) {
return clazz.simpleName;
}
};
this.name2Class = function name2Class(name, event) {
var eventCls = this.mapEvent[event.toLowerCase()] || this.mapEvent[event.toLowerCase() + 'event'];
@ -69,30 +73,31 @@ function EventHandlerDefault() {
this.mapEvent[event] = eventCls;
} catch (ex) {
console.console("§6插件 §b%s §6注册事件 §c%s §6失败 §4事件未找到!".format(name, event));
console.ex(new Error("插件 %s 注册事件 %s 失败 事件未找到!".format(name, event)))
console.ex(new Error("插件 %s 注册事件 %s 失败 事件未找到!".format(name, event)));
return;
}
}
return eventCls;
}
};
// noinspection JSUnusedLocalSymbols
/**
* 判断是否为一个有效的事件类
* @param clz
* @returns {*|boolean}
*/
this.isVaildEvent = function isVaildEvent(clz) {
this.isValidEvent = function isValidEvent(clz) {
throw new Error("当前服务器不支持事件系统!");
}
};
// noinspection JSUnusedLocalSymbols
this.register = function register(eventCls, exec, priority, ignoreCancel) {
throw new Error("当前服务器不支持事件系统!");
}
};
// noinspection JSUnusedLocalSymbols
this.unregister = function unregister(event, listener) {
throw new Error("当前服务器不支持事件系统!");
}
};
this.execute = function execute(name, exec, eventCls) {
return function execute() {
try {
@ -102,8 +107,8 @@ function EventHandlerDefault() {
console.ex(ex);
}
}.bind(this);
}
};
/**
* 添加事件监听
* @param jsp
@ -116,7 +121,9 @@ function EventHandlerDefault() {
if (!jsp || !jsp.description || !jsp.description.name) throw new TypeError('插件名称为空 请检查传入参数!');
var name = jsp.description.name;
var eventCls = this.name2Class(name, event);
if (!eventCls) { return; }
if (!eventCls) {
return;
}
if (typeof priority === 'boolean') {
ignoreCancel = priority;
priority = 'NORMAL';
@ -143,6 +150,7 @@ function EventHandlerDefault() {
return off;
}
}
var EventHandler = Object.assign(new EventHandlerDefault(), requireInternal('event'));
// 映射事件名称
console.info('%s 事件映射完毕 共计 %s 个事件!'.format(DetectServerType, EventHandler.mapEventName().toFixed(0)));

View File

@ -1,9 +1,9 @@
'use strict';
/**
* MiaoScript脚本插件加载类
* @namespace plugin.configFile.parentFile, command.enable, permission.enable
*/
/*global Java, module, exports, require, __FILE__*/
// var zip = require("core/zip");
var fs = require('core/fs');
var yaml = require('modules/yaml');
var event = require('./event');
@ -95,7 +95,7 @@ function readPlugin(file) {
hook: function (origin) {
return beforeLoadHook(origin);
}
})
});
console.debug("插件编译结果: %s".format(JSON.stringify(plugin)));
plugin.__FILE__ = file;
return plugin;
@ -141,7 +141,7 @@ function internalInitPlugin(plugin) {
// 初始化 getDataFolder()
plugin.getDataFolder = function getDataFolder() {
return plugin.__DATA__;
}
};
// 初始化 getFile()
plugin.getFile = plugin.file = function getFile(name) {
return fs.file(plugin.getDataFolder(), name);
@ -149,7 +149,9 @@ function internalInitPlugin(plugin) {
// 初始化插件配置相关方法
initPluginConfig(plugin);
/** @namespace command.enable */
if (command.enable) command.enable(plugin);
/** @namespace permission.enable */
if (permission.enable) permission.enable(plugin);
}
@ -173,9 +175,9 @@ function initPluginConfig(plugin) {
if (!file.isFile) {
file = plugin.getFile(file);
}
return yaml.safeLoad(fs.read(file), { json: true });
return yaml.safeLoad(fs.read(file), {json: true});
}
}
};
/**
* 重载配置文件
* @constructor
@ -183,7 +185,7 @@ function initPluginConfig(plugin) {
*/
plugin.reloadConfig = function () {
plugin.config = plugin.getConfig(plugin.configFile);
}
};
/**
* 保存配置文件
* @constructor
@ -191,6 +193,7 @@ function initPluginConfig(plugin) {
*/
plugin.saveConfig = function () {
// 判断插件目录是否存在 并且不为文件 否则删除重建
// noinspection JSValidateTypes
if (!plugin.configFile.parentFile.isDirectory()) {
fs.del(plugin.configFile.parentFile);
}
@ -203,7 +206,8 @@ function initPluginConfig(plugin) {
fs.save(fs.file(plugin.__DATA__, arguments[0]), yaml.safeDump(arguments[1]));
break;
}
}
};
// noinspection JSValidateTypes
if (plugin.configFile.isFile()) {
plugin.config = plugin.getConfig('config.yml');
} else if (plugin.description.config) {
@ -247,27 +251,27 @@ function checkAndRun(args, name, ext) {
var plugins = [];
function init(path) {
var plugin = exports.$
var plugin = exports.$;
if (plugin !== null) {
// 如果plugin不等于null 则代表是正式环境
console.info("初始化 MiaoScript 插件系统: %s".format(plugin));
}
loadPlugins(path);
};
}
function load() {
checkAndRun(arguments, 'load');
};
}
function enable() {
checkAndRun(arguments, 'enable');
};
}
function disable() {
checkAndRun(arguments, 'disable', function eventDisable() {
event.disable(this);
});
};
}
function reload() {
checkAndGet(arguments).forEach(function (p) {
@ -276,8 +280,9 @@ function reload() {
load(p);
enable(p);
});
};
}
// noinspection JSUnresolvedVariable
exports = module.exports = {
$: server.plugin.self,
plugins: plugins,
@ -287,4 +292,4 @@ exports = module.exports = {
disable: disable,
reload: reload,
loadPlugin: loadPlugin
}
};

View File

@ -2,4 +2,4 @@
var player = requireInternal('wrapper/player');
module.exports = {
player: player.$
}
};

View File

@ -2,6 +2,7 @@
var log;
var boot;
var disable;
// noinspection ThisExpressionReferencesGlobalObjectJS
var global = this;
/**
* 初始化框架引擎
@ -35,6 +36,7 @@ var global = this;
var pluginYml;
function checkClassLoader() {
// noinspection JSUnresolvedVariable
var classLoader = java.lang.Thread.currentThread().contextClassLoader;
pluginYml = classLoader.getResource("plugin.yml");
if (pluginYml === null) {
@ -47,8 +49,8 @@ var global = this;
}
function release(root, regex, replace) {
var upath = pluginYml.getFile().substring(pluginYml.getFile().indexOf("/") + 1);
var jarPath = java.net.URLDecoder.decode(upath.substring(0, upath.indexOf('!')));
var filePath = pluginYml.getFile().substring(pluginYml.getFile().indexOf("/") + 1);
var jarPath = java.net.URLDecoder.decode(filePath.substring(0, filePath.indexOf('!')));
if (!java.nio.file.Files.exists(java.nio.file.Paths.get(jarPath))) {
jarPath = "/" + jarPath;
}
@ -56,9 +58,11 @@ var global = this;
var r = new RegExp(regex);// "[core|modules]/.*"
jar.stream().forEach(function (entry) {
try {
// noinspection JSValidateTypes
if (!entry.isDirectory()) {
if (r.test(entry.name)) {
var path = java.nio.file.Paths.get(root, entry.name);
// noinspection JSUnresolvedVariable
var parentFile = path.toFile().parentFile;
if (!parentFile.exists()) { parentFile.mkdirs(); }
if (!java.nio.file.Files.exists(path) || replace) {

View File

@ -12,6 +12,7 @@
}.bind(this),
set: function (name) {
this._name = name ? '[' + name + '] ' : '';
// noinspection JSUnusedGlobalSymbols
this.prefix = name ? '§6[§cMS§6][§b' + name + '§6]§r ' : '§6[§bMiaoScript§6]§r ';
}.bind(this)
});
@ -19,6 +20,7 @@
this.log = this.info = function () {
log.info(this.name + Array.prototype.join.call(arguments, ' '));
};
// noinspection JSUnusedGlobalSymbols
this.warn = function () {
log.warning(this.name + Array.prototype.join.call(arguments, ' '));
};
@ -35,7 +37,7 @@
for (var i in obj) {
this.log(i, '=>', obj[i])
}
}
};
this.ex = function (message, ex) {
if (!ex) {
this.console('§4' + message);
@ -55,6 +57,6 @@
}
}.bind(this));
};
}
};
global.Console = ConsoleDefault;
})(global);

View File

@ -3,18 +3,21 @@
/*global Java, base, module, exports, require, __FILE__*/
var File = Java.type("java.io.File");
var Files = Java.type("java.nio.file.Files");
// noinspection JSUnresolvedVariable
var separatorChar = File.separatorChar;
var StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
// noinspection JSUnusedLocalSymbols
var _toString = function (obj) {
return Object.prototype.toString.call(obj);
}
};
/**
* 用文件分割符合并路径
*/
function concat() {
return Array.prototype.join.call(arguments, separatorChar);
};
}
/**
* 获得文件
* @constructor(file)
@ -27,39 +30,43 @@ function file() {
}
switch (arguments.length) {
case 1:
var f = arguments[0]
var f = arguments[0];
if (f instanceof File) {
return f;
}
if (typeof f === "string") {
return new File(f);
}
if (f instanceof Path) {
if (f instanceof java.nio.file.Path) {
return f.toFile();
}
case 2:
break;
default:
return new File(exports.file(arguments[0]), arguments[1]);
}
};
}
/**
* 创建目录
* @param file
* @param path
*/
function mkdirs(path) {
// noinspection JSUnresolvedVariable
fs.file(path).parentFile.mkdirs();
};
}
/**
* 创建文件
* @param file
*/
function create(path) {
var file = fs.file(path)
if (!file.exists()) {
mkdirs(file);
file.createNewFile();
function create(file) {
var f = fs.file(path);
if (!f.exists()) {
mkdirs(f);
f.createNewFile();
}
};
}
/**
* 获得文件规范路径
* @param file
@ -68,7 +75,8 @@ function create(path) {
function path(file) {
// noinspection JSUnresolvedVariable
return fs.file(file).canonicalPath;
};
}
/**
* 复制文件
* @param inputStream 输入流
@ -77,7 +85,8 @@ function path(file) {
*/
function copy(inputStream, target, override) {
Files.copy(inputStream, target.toPath(), StandardCopyOption[override ? 'REPLACE_EXISTING' : 'ATOMIC_MOVE']);
};
}
/**
* 读取文件
* @param path 文件路径
@ -90,7 +99,8 @@ function read(path) {
}
// noinspection JSPrimitiveTypeWrapperUsage
return new java.lang.String(Files.readAllBytes(file.toPath()), "UTF-8");
};
}
/**
* 保存内容文件
* @param path 路径
@ -101,19 +111,22 @@ function save(path, content, override) {
var file = fs.file(path);
file.getParentFile().mkdirs();
Files.write(file.toPath(), new java.lang.String(content).getBytes("UTF-8"));
};
}
/**
* 列出目录文件
* @param path
*/
function list(path) {
var dir = file(path);
// noinspection JSValidateTypes
if (dir.isDirectory()) {
return Files.list(dir.toPath());
}
console.debug('路径', path, '不是一个目录 返回空数组!');
return [];
};
}
/**
* 移动文件
* @param src 原始目录
@ -123,29 +136,37 @@ function list(path) {
function move(src, des, override) {
Files.move(fs.file(src).toPath(), fs.file(des).toPath(),
override ? StandardCopyOption['REPLACE_EXISTING'] : StandardCopyOption['ATOMIC_MOVE'])
};
}
function del(file) {
file = fs.file(file);
if (!file.exists()) { return; }
if (!file.exists()) {
return;
}
// noinspection JSValidateTypes
if (file.isDirectory()) {
Files.list(file.toPath()).collect(Collectors.toList()).forEach(function (f) { del(f); })
// noinspection JSUnresolvedVariable
Files.list(file.toPath()).collect(java.util.stream.Collector.toList()).forEach(function (f) {
del(f);
})
}
Files.delete(file.toPath());
}
// noinspection JSUnusedLocalSymbols
function exists(file) {
return fs.file(file).exists()
}
var fs = {};
fs.path = fs.canonical = fs.realpath = path
fs.write = fs.save = save
fs.readdir = fs.list = list
fs.rename = fs.move = move
fs.delete = fs.del = del
fs.path = fs.canonical = fs.realpath = path;
fs.write = fs.save = save;
fs.readdir = fs.list = list;
fs.rename = fs.move = move;
fs.delete = fs.del = del;
// noinspection JSUnusedGlobalSymbols
Object.assign(fs, {
concat: concat,
create: create,
@ -153,6 +174,6 @@ Object.assign(fs, {
file: file,
copy: copy,
read: read
})
});
exports = module.exports = fs
exports = module.exports = fs;

View File

@ -38,7 +38,7 @@
global.engineLoad = load;
global.load = function __denyGlobalLoad__() {
throw new Error('系统内部不许允许使用 load 如需执行脚本 请使用 engineLoad !');
}
};
// 初始化加载器
global.require = engineLoad(root + '/core/require.js')(root);
global.requireInternal = function requireInternal(name) {

View File

@ -2,6 +2,7 @@
* 补丁和方法扩展
*/
(function () {
// noinspection JSUnresolvedVariable
if (!Array.prototype.copyPartialMatches) {
Object.defineProperty(Array.prototype, "copyPartialMatches", {
enumerable: false,
@ -10,7 +11,7 @@
if (e.toLowerCase().startsWith(token.toLowerCase())) {
array.push(e)
}
})
});
return array
}
});

View File

@ -9,7 +9,7 @@
* @param fmt 格式化字符串
* @returns {*}
*/
Date.prototype.format = function (fmt) { //author: meizz
Date.prototype.format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日

View File

@ -9,7 +9,7 @@
enumerable: false,
configurable: true,
writable: true,
value: function(target) {
value: function (target) {
"use strict";
if (target === undefined || target === null)
throw new TypeError("Cannot convert first argument to object");
@ -34,31 +34,31 @@
enumerable: false,
configurable: true,
writable: true,
value: function(target) {
value: function (target) {
"use strict";
var vals = [];
var values = [];
for (var key in target) {
var desc = Object.getOwnPropertyDescriptor(target, key);
if (desc !== undefined && desc.enumerable) vals.push(target[key]);
if (desc !== undefined && desc.enumerable) values.push(target[key]);
}
return vals;
return values;
}
});
}
// JSON快捷方法
if(!Object.toJson){
if (!Object.toJson) {
Object.defineProperty(Object.prototype, "toJson", {
enumerable: false,
configurable: true,
writable: true,
value: function() {
value: function () {
return JSON.stringify(this);
}
});
}
// Object.prototype.toJson = function () {
// return JSON.stringify(this);
// };

View File

@ -1,7 +1,6 @@
/**
* 补丁和方法扩展
*/
(function () {
// Java格式化方法
var str = Java.type('java.lang.String');

View File

@ -33,12 +33,12 @@
var cacheDir = parent + separatorChar + "runtime";
var paths = [parent, parent + separatorChar + 'core', parent + separatorChar + 'api', parent + separatorChar + 'modules'];
try{
try {
base.delete(cacheDir);
} catch (ex) {
console.ex(ex);
}
/**
* 判断是否为一个文件
* @param file
@ -129,6 +129,7 @@
var _package = new File(dir, 'package.json');
if (_package.exists()) {
var json = JSON.parse(base.read(_package));
/** @namespace json.main */
if (json.main) {
return resolveAsFile(dir, json.main);
}
@ -181,6 +182,7 @@
compileJson(module, file, optional);
}
if (_canonical(file).endsWith('.msm')) {
// noinspection ExceptionCaughtLocallyJS
throw Error("暂不支持解析 MiaoScript 模块");
}
} catch (ex) {
@ -192,6 +194,7 @@
/**
* 预编译JS
* @param module JS模块
* @param file JS文件
* @param optional 附加选项
* @returns {Object}
@ -218,6 +221,7 @@
/**
* 预编译Json
* @param module Json模块
* @param file Json 文件
* @param optional 附加选项
* @returns {Object}

View File

@ -2,7 +2,6 @@
var bukkit = require('api/server');
var nmsChatSerializerClass;
var nmsIChatBaseComponentClass;
var packetTypeClass;
var nmsChatMessageTypeClass;
@ -10,23 +9,29 @@ var chatMessageTypes;
var String = Java.type('java.lang.String');
function init () {
function init() {
/** @namespace bukkit.nmsVersion */
nmsChatSerializerClass = bukkit.nmsCls(bukkit.nmsVersion.split("_")[1] > 7 ? "IChatBaseComponent$ChatSerializer" : "ChatSerializer");
nmsIChatBaseComponentClass = bukkit.nmsCls('IChatBaseComponent');
packetTypeClass = bukkit.nmsCls("PacketPlayOutChat");
var packetTypeConstructor;
Java.from(packetTypeClass.class.constructors).forEach(function (c) {
if (c.parameterTypes.length == 2) { packetTypeConstructor = c };
})
if (c.parameterTypes.length === 2) {
packetTypeConstructor = c
}
});
// noinspection JSUnusedAssignment
nmsChatMessageTypeClass = packetTypeConstructor.parameterTypes[1];
if (nmsChatMessageTypeClass.isEnum()) {
chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants();
} else {
/** @namespace nmsChatMessageTypeClass.name */
switch (nmsChatMessageTypeClass.name) {
case "int":
nmsChatMessageTypeClass = java.lang.Integer;
break;
case "byte":
nmsChatMessageTypeClass = java.lang.Byte;
break;
}
}
}
@ -36,7 +41,8 @@ function json(sender, json) {
}
function send(sender, json, type) {
var serialized = nmsChatSerializerClass.a(json)
var serialized = nmsChatSerializerClass.a(json);
// noinspection all
var typeObj = chatMessageTypes == null ? nmsChatMessageTypeClass.valueOf(String.valueOf(type)) : chatMessageTypes[type];
sendPacket(sender, new packetTypeClass(serialized, typeObj))
}

View File

@ -10,34 +10,37 @@ var plugin = bukkit.plugin.self;
var commandMap = ref.on(bukkit.plugin.manager).get('commandMap').get();
var PluginCommand = Java.type('org.bukkit.command.PluginCommand');
var StringUtil = Java.type('org.bukkit.util.StringUtil');
var ArrayList = Java.type('java.util.ArrayList');
var Arrays = Java.type('java.util.Arrays');
function enable(jsp) {
var commands = jsp.description.commands;
if (commands) {
var pluginCmds = [];
var pluginCommands = [];
for (var name in commands) {
// noinspection JSUnfilteredForInLoop
var command = commands[name];
if (typeof command !== 'object') continue;
// noinspection JSUnfilteredForInLoop
var newCmd = create(jsp, name);
if (command.description) newCmd.setDescription(command.description);
if (command.usage) newCmd.setUsage(command.usage);
/** @namespace command.aliases */
if (command.aliases) newCmd.setAliases(Arrays.asList(command.aliases));
if (command.permission) newCmd.setPermission(command.permission);
if (command['permission-message']) newCmd.setPermissionMessage(command['permission-message']);
pluginCmds.push(newCmd);
pluginCommands.push(newCmd);
// noinspection JSUnfilteredForInLoop
console.debug('插件 %s 注册命令 %s ...'.format(jsp.description.name, name));
}
commandMap.registerAll(jsp.description.name, Arrays.asList(pluginCmds));
commandMap.registerAll(jsp.description.name, Arrays.asList(pluginCommands));
}
}
// noinspection JSUnusedLocalSymbols
function disable(jsp) {
var commands = jsp.description.commands;
if (commands) {
// noinspection JSUnusedLocalSymbols
for (var name in commands) {
//TODO 删除插件命令
}
@ -62,13 +65,14 @@ function on(jsp, name, exec) {
console.debug('插件 %s 设置命令 %s(%s) 执行器 ...'.format(jsp.description.name, name, c));
if (exec.cmd) {
// 必须指定需要实现的接口类型 否则MOD服会报错
// noinspection JSUnusedGlobalSymbols
c.setExecutor(new org.bukkit.command.CommandExecutor({
onCommand: function (sender, cmd, command, args) {
try {
return exec.cmd(sender, command, args);
} catch (ex) {
console.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6命令时发生异常 §4%s'
.format(sender.name, jsp.description.name, command, Java.from(args).join(' '), ex));
.format(sender.name, jsp.description.name, command, Java.from(args).join(' '), ex));
console.ex(ex);
}
}
@ -76,15 +80,16 @@ function on(jsp, name, exec) {
}
if (exec.tab) {
// 必须指定需要实现的接口类型 否则MOD服会报错
// noinspection JSUnusedGlobalSymbols
c.setTabCompleter(new org.bukkit.command.TabCompleter({
onTabComplete: function (sender, cmd, command, args) {
try {
var token = args[args.length - 1];
var complate = exec.tab(sender, command, args) || []
return Arrays.asList(complate.copyPartialMatches(token, []));
var complete = exec.tab(sender, command, args) || [];
return Arrays.asList(complete.copyPartialMatches(token, []));
} catch (ex) {
console.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6补全时发生异常 §4%s'
.format(sender.name, jsp.description.name, command, Java.from(args).join(' '), ex));
.format(sender.name, jsp.description.name, command, Java.from(args).join(' '), ex));
console.ex(ex);
}
}

View File

@ -15,7 +15,7 @@ var EventExecutor = Java.type("org.bukkit.plugin.EventExecutor");
* @param clz
* @returns {*|boolean}
*/
function isVaildEvent(clz) {
function isValidEvent(clz) {
// noinspection JSUnresolvedVariable 继承于 org.bukkit.event.Event
return Event.class.isAssignableFrom(clz) &&
// 访问符为Public
@ -44,7 +44,7 @@ function unregister(event, listener) {
exports = module.exports = {
baseEventDir: 'org/bukkit/event',
isVaildEvent: isVaildEvent,
isValidEvent: isValidEvent,
register: register,
unregister: unregister
};

View File

@ -16,15 +16,18 @@ function enable(plugin) {
var permissions = plugin.description.permissions;
if (permissions) {
for (var name in permissions) {
// noinspection JSUnfilteredForInLoop
var permission = permissions[name];
if (typeof permission !== 'object') continue;
var desc = permission.description;
var def = permission.default || 'OP';
try {
// noinspection JSUnfilteredForInLoop
manager.addPermission(new Permission(name, desc, PermissionDefault.getByName(def)));
} catch (ex) {
// ignore eg: java.lang.IllegalArgumentException: The permission xxxxxx.default is already defined!
}
// noinspection JSUnfilteredForInLoop
console.debug('插件 %s 注册权限 %s Default %s ...'.format(plugin.description.name, name, def));
}
}
@ -35,10 +38,12 @@ function disable(plugin) {
if (permissions) {
for (var name in permissions) {
try {
// noinspection JSUnfilteredForInLoop
manager.removePermission(name);
} catch (ex) {
// ignore eg: java.lang.IllegalArgumentException: The permission xxxxxx.default is already defined!
}
// noinspection JSUnfilteredForInLoop
console.debug('插件 %s 注销权限 %s ...'.format(plugin.description.name, name));
}
}

View File

@ -6,7 +6,7 @@
/*global Java, base, module, exports, require, __FILE__*/
var Bukkit = MServer;
var Server = Bukkit.server;
var Server = MServer.server;
exports.$ = Bukkit;
/**
* 获取NMS版本
@ -43,16 +43,16 @@ exports.player = function () {
exports.players = function () {
switch (arguments.length) {
case 1:
return Server.onlinePlayers.forEach(arguments[0]);
return Bukkit.onlinePlayers.forEach(arguments[0]);
default:
return Server.onlinePlayers;
return Bukkit.onlinePlayers;
}
};
/**
* 插件管理
* @type {{manager: *, get: exports.plugin.get, load: exports.plugin.load}}
*/
var PluginManager = Server.pluginManager;
var PluginManager = Bukkit.pluginManager;
exports.plugin = {
/**
* 插件管理工具
@ -84,7 +84,7 @@ exports.plugin = {
* 服务管理
* @type {{manager: *, get: exports.plugin.get, load: exports.plugin.load}}
*/
var ServicesManager = Server.servicesManager;
var ServicesManager = Bukkit.servicesManager;
exports.service = {
/**
* 服务管理工具
@ -99,7 +99,7 @@ exports.service = {
var reg = ServicesManager.getRegistration(base.getClass(name));
return reg && reg.provider || null;
}
}
};
/**
* 公告
* @param message 消息
@ -125,13 +125,13 @@ exports.console = function (command) {
/**
* 玩家以OP权限执行命令
* @param player
* @param exper
* @param command
*/
exports.opcommand = function (player, exper) {
exports.opcommand = function (player, command) {
var origin = player.isOp();
player.setOp(true);
try {
exports.command(player, exper);
exports.command(player, command);
} finally {
player.setOp(origin);
}

View File

@ -0,0 +1,82 @@
interface Class {
name;
class;
static;
methods;
simpleName;
constructors;
parameterTypes;
}
interface Task {
submit(plugin);
}
interface Registration {
provider;
}
interface PluginManager {
isEnabled();
}
interface bukkit {
nmsVersion: string;
}
interface Server {
server;
service;
consoleSender;
onlinePlayers;
pluginManager;
serviceManager;
servicesManager;
onlinePlayers;
}
interface Player {
handle: NMSPlayer;
getName();
openInventory();
}
interface Inventory {
setItem(index: number, item: Item);
}
interface PlayerEvent {
targetEntity;
}
interface ItemEvent {
entity: Item;
}
interface InventoryClickEvent {
inventory;
whoClicked;
rawSlot;
}
interface NMSPlayer {
playerConnection;
}
interface File {
canonicalPath;
isDirectory();
}
interface Item {
itemStack: ItemStack;
}
interface ItemStack {
typeId;
itemMeta;
amount;
}

View File

@ -8,9 +8,6 @@ var Sponge = MServer;
var server = require('./server');
var plugin = server.plugin.self;
var CommandManager = server.CommandManager;
var CommandSpec = Java.type('org.spongepowered.api.command.spec.CommandSpec');
var CommandCallable = Java.type('org.spongepowered.api.command.CommandCallable');
var CommandResult = Java.type('org.spongepowered.api.command.CommandResult');
@ -21,13 +18,16 @@ var Optional = Java.type('java.util.Optional');
var ArrayList = Java.type('java.util.ArrayList');
var Arrays = Java.type('java.util.Arrays');
var commandMap=[];
var commandMap = [];
var SimpleCommandCallable = function (command) {
var that = this;
this.name = command.name;
this.cmd = noop;
this.tab = function() { return new ArrayList(); };
this.tab = function () {
return new ArrayList();
};
// noinspection JSUnusedGlobalSymbols,JSUnusedLocalSymbols
this.callable = new CommandCallable({
//CommandResult process(CommandSource source, String arguments) throws CommandException;
process: function (src, args) {
@ -60,29 +60,32 @@ var SimpleCommandCallable = function (command) {
this.setTabCompleter = function (exec) {
that.tab = exec;
}
}
};
function enable(jsp) {
var pname = jsp.description.name;
// noinspection JSUnusedLocalSymbols
var plugin = jsp.description.name;
var commands = jsp.description.commands;
if (commands) {
var pluginCmds = [];
// noinspection JSUnusedLocalSymbols
var pluginCommands = [];
for (var name in commands) {
var command = commands[name];
if (typeof command !== 'object') continue;
command.name = name
create(jsp, command)
command.name = name;
create(jsp, command);
console.debug('插件 %s 注册命令 %s ...'.format(jsp.description.name, name));
}
}
}
// noinspection JSUnusedLocalSymbols
function get(name) {
}
function create(jsp, command) {
var commandKey = jsp.description.name.toLowerCase() + ":" + command.name;
if(!commandMap[commandKey]){
if (!commandMap[commandKey]) {
commandMap[commandKey] = new SimpleCommandCallable(command);
Sponge.getCommandManager().register(plugin, commandMap[commandKey].callable, command.name, commandKey);
}
@ -98,7 +101,7 @@ function on(jsp, name, exec) {
return exec.cmd(sender, command, args);
} catch (ex) {
console.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6命令时发生异常'
.format(sender.name, jsp.description.name, command, args.join(' ')));
.format(sender.name, jsp.description.name, command, args.join(' ')));
console.ex(ex);
}
});
@ -107,19 +110,18 @@ function on(jsp, name, exec) {
c.setTabCompleter(function execTab(sender, command, args) {
try {
var token = args[args.length - 1];
var complate = exec.tab(sender, command, args) || []
return Arrays.asList(complate.copyPartialMatches(token, []));
var complete = exec.tab(sender, command, args) || [];
return Arrays.asList(complete.copyPartialMatches(token, []));
} catch (ex) {
console.console('§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6补全时发生异常'
.format(sender.name, jsp.description.name, command, args.join(' ')));
.format(sender.name, jsp.description.name, command, args.join(' ')));
console.ex(ex);
}
});
}
}
var exist = Sponge.getCommandManager().getOwnedBy(plugin);
exist.forEach(function(commandMapping) {
Sponge.getCommandManager().getOwnedBy(plugin).forEach(function (commandMapping) {
if (!commandMapping.getAllAliases().contains("ms")) {
Sponge.getCommandManager().removeMapping(commandMapping);
}
@ -129,4 +131,4 @@ exports = module.exports = {
enable: enable,
on: on,
off: noop
}
};

View File

@ -14,6 +14,7 @@
this.console = function () {
this.sender(MServer.server.console, Array.prototype.join.call(arguments, ' '));
};
// noinspection JSUnusedGlobalSymbols
this.warn = function () {
log.warn(this.name + Array.prototype.join.call(arguments, ' '));
};

View File

@ -15,14 +15,14 @@ var priorityMap = {
'HIGH': 'LATE',
'HIGHEST': 'LAST',
'MONITOR': 'POST'
}
};
/**
* 判断是否为一个有效的事件类
* @param clz
* @returns {*|boolean}
*/
function isVaildEvent(clz) {
* 判断是否为一个有效的事件类
* @param clz
* @returns {*|boolean}
*/
function isValidEvent(clz) {
// noinspection JSUnresolvedVariable 继承于 org.spongepowered.api.event.Event
return Event.class.isAssignableFrom(clz) &&
// 访问符为Public
@ -46,9 +46,11 @@ function register(eventCls, exec, priority, ignoreCancel) {
function unregister(event, listener) {
MServer.getEventManager().unregisterListeners(listener);
}
// noinspection JSUnusedGlobalSymbols
exports = module.exports = {
baseEventDir: 'org/spongepowered/api/event',
isVaildEvent: isVaildEvent,
isValidEvent: isValidEvent,
class2Name: class2Name,
register: register,
unregister: unregister

View File

@ -6,13 +6,13 @@
/*global Java, base, module, exports, require, __FILE__*/
var Sponge = MServer;
var Server = Sponge.server;
var PluginManager = Sponge.pluginManager;
var Server = MServer.server;
exports.$ = Sponge;
/**
* 插件管理
* @type {{manager: *, get: exports.plugin.get, load: exports.plugin.load}}
*/
var PluginManager = Sponge.pluginManager;
exports.plugin = {
/**
* 插件管理工具
@ -54,7 +54,7 @@ exports.service = {
get: function (name) {
return ServicesManager.provide(base.getClass(name)).orElse(null);
}
}
};
/**
* 获取玩家
*/

View File

@ -5,14 +5,14 @@
* Created by 蒋天蓓 on 2017/2/9 0009.
*/
var plugin = require('./server').plugin.self;
var Comsumer = Java.type('java.util.function.Consumer');
var Consumer = Java.type('java.util.function.Consumer');
var Task = Java.type("org.spongepowered.api.scheduler.Task");
/**
* 创建任务对象
* @param func 任务
*/
exports.create = function (func) {
return Task.builder().execute(new Comsumer(function () {
return Task.builder().execute(new Consumer(function () {
try {
func();
} catch (ex) {

View File

@ -22,8 +22,8 @@
}
}
// constants
var b64chars
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// noinspection SpellCheckingInspection
var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var b64tab = function (bin) {
var t = {};
for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i;
@ -39,7 +39,7 @@
+ fromCharCode(0x80 | (cc & 0x3f)))
: (fromCharCode(0xe0 | ((cc >>> 12) & 0x0f))
+ fromCharCode(0x80 | ((cc >>> 6) & 0x3f))
+ fromCharCode(0x80 | ( cc & 0x3f)));
+ fromCharCode(0x80 | (cc & 0x3f)));
} else {
var ccc = 0x10000
+ (c.charCodeAt(0) - 0xD800) * 0x400
@ -47,7 +47,7 @@
return (fromCharCode(0xf0 | ((ccc >>> 18) & 0x07))
+ fromCharCode(0x80 | ((ccc >>> 12) & 0x3f))
+ fromCharCode(0x80 | ((ccc >>> 6) & 0x3f))
+ fromCharCode(0x80 | ( ccc & 0x3f)));
+ fromCharCode(0x80 | (ccc & 0x3f)));
}
};
var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
@ -173,6 +173,7 @@
return Base64;
};
// export Base64
// noinspection JSUnusedGlobalSymbols
global.Base64 = {
VERSION: version,
atob: atob,

View File

@ -9,29 +9,32 @@
var URL = Java.type("java.net.URL");
var Files = Java.type("java.nio.file.Files");
var Paths = Java.type("java.nio.file.Paths");
var String = Java.type("java.lang.String");
var Str = Java.type("java.lang.String");
var HttpURLConnection = Java.type("java.net.HttpURLConnection");
var HttpsURLConnection = Java.type("javax.net.ssl.HttpsURLConnection");
var SSLContext = Java.type("javax.net.ssl.SSLContext");
var HostnameVerifier = Java.type("javax.net.ssl.HostnameVerifier");
var X509TrustManager = Java.type("javax.net.ssl.X509TrustManager");
// noinspection JSUnusedGlobalSymbols,JSUnusedLocalSymbols
var TrustAnyHostnameVerifier = new HostnameVerifier({
verify: function (hostname, session) {
return true;
}
})
});
var SSLSocketFactory = function initSSLSocketFactory() {
var sslContext = SSLContext.getInstance("TLS");
// noinspection JSUnusedGlobalSymbols
sslContext.init(null, [new X509TrustManager({
getAcceptedIssuers: function () {
return null;
},
checkClientTrusted: function (chain, authType) {},
checkServerTrusted: function (chain, authType) {}
checkClientTrusted: function (chain, authType) {
},
checkServerTrusted: function (chain, authType) {
}
})], new java.security.SecureRandom());
return sslContext.getSocketFactory();
}();
@ -41,7 +44,7 @@ var config = {
ConnectTimeout: 10000,
ReadTimeout: 10000,
Debug: false
}
};
function open(url, method, header) {
// conn.setRequestProperty
@ -57,6 +60,7 @@ function open(url, method, header) {
conn.setReadTimeout(config.ReadTimeout);
if (header) {
for (var key in header) {
// noinspection JSUnfilteredForInLoop
conn.setRequestProperty(key, header[key]);
}
}
@ -66,7 +70,7 @@ function open(url, method, header) {
function buildUrl(url, params) {
if (params && Object.keys(params).length > 0) {
var queryStart = url.indexOf('?');
if (queryStart == -1) {
if (queryStart === -1) {
url += '?';
}
return url += object2URLSearchParams(params);
@ -85,12 +89,13 @@ function request(config) {
var type = config.header['Content-Type'];
switch (type) {
case "application/x-www-form-urlencoded":
data = object2URLSearchParams(params);
data = object2URLSearchParams(data);
break;
default:
data = JSON.stringify(data)
}
}
out.write(new String(data).getBytes(config.Charset));
out.write(new Str(data).getBytes(config.Charset));
out.flush();
out.close();
}
@ -100,17 +105,17 @@ function request(config) {
}
}
function response (conn) {
function response(conn) {
var temp = Paths.get(java.lang.System.getProperty("java.io.tmpdir"), java.util.UUID.randomUUID().toString());
Files.copy(conn.getInputStream(), temp);
var result = new String(Files.readAllBytes(temp), config.Charset);
var result = new Str(Files.readAllBytes(temp), config.Charset);
var tempFile = temp.toFile();
tempFile.delete() || tempFile.deleteOnExit();
return result;
}
function object2URLSearchParams (params) {
var temp = []
function object2URLSearchParams(params) {
var temp = [];
for (var key in params) {
temp.push('%s=%s'.format(encodeURIComponent(key), encodeURIComponent(params[key])))
}

View File

@ -0,0 +1,3 @@
interface requestConfig {
header;
}

View File

@ -8,9 +8,9 @@ var server = require('api/server');
PlaceholderAPI = {
setPlaceholders: function () {
return arguments[1].replace(/&([1-9a-fA-F])/,'§$1');
return arguments[1].replace(/&([1-9a-fA-F])/, '§$1');
}
}
};
// 尝试加载 Bukkit 的 PlaceholderAPI
try {
@ -21,15 +21,16 @@ try {
// 尝试加载 Sponge 的 PlaceholderAPI
try {
var spapi = server.service.get('me.rojo8399.placeholderapi.PlaceholderService');
/** @namespace server.service */
var spongePapi = server.service.get('me.rojo8399.placeholderapi.PlaceholderService');
var TextSerializers = Java.type('org.spongepowered.api.text.serializer.TextSerializers');
var s = TextSerializers.formattingCode('§');
if (spapi) {
if (spongePapi) {
PlaceholderAPI = {
setPlaceholders: function () {
return s.serialize(spapi.replacePlaceholders(arguments[1], arguments[0], arguments[0]));
return s.serialize(spongePapi.replacePlaceholders(arguments[1], arguments[0], arguments[0]));
}
}
};
console.log('[PAPI] Found Sponge PlaceholderAPI Hooking...')
}
} catch (ex) {
@ -45,4 +46,4 @@ function replace() {
exports = module.exports = {
$: replace
}
};

View File

@ -44,6 +44,7 @@ function Reflect(obj) {
return arguments.length === 1 ? this.field(arguments[0]) : this.obj;
};
// noinspection JSUnusedGlobalSymbols
this.set = function (name, value) {
accessible(declaredField(this.class, name)).set(this.obj, value);
return this;
@ -113,27 +114,15 @@ function declaredField(clazz, name) {
}
function declaredMethod(clazz, name, clazzs) {
var mkey = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
if (!methodCache[mkey]) {
var key = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
if (!methodCache[key]) {
try {
methodCache[mkey] = clazz.getMethod(name, clazzs);
methodCache[key] = clazz.getMethod(name, clazzs);
} catch (ex) {
methodCache[mkey] = clazz.getDeclaredMethod(name, clazzs);
methodCache[key] = clazz.getDeclaredMethod(name, clazzs);
}
}
return methodCache[mkey];
}
function declaredMethod(clazz, name, clazzs) {
var mkey = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
if (!methodCache[mkey]) {
try {
methodCache[mkey] = clazz.getMethod(name, clazzs);
} catch (ex) {
methodCache[mkey] = clazz.getDeclaredMethod(name, clazzs);
}
}
return methodCache[mkey];
return methodCache[key];
}
function declaredMethods(clazz) {
@ -143,18 +132,22 @@ function declaredMethods(clazz) {
var classMethodsCache = [];
function mapToObject(javaObj) {
if (!javaObj || !javaObj.class) { throw new TypeError('参数 %s 不是一个Java对象!'.format(javaObj)) }
if (!javaObj || !javaObj.class) {
throw new TypeError('参数 %s 不是一个Java对象!'.format(javaObj))
}
var target = {};
getJavaObjectMethods(javaObj).forEach(function proxyMethod(t){ mapMethod(target, javaObj, t) })
getJavaObjectMethods(javaObj).forEach(function proxyMethod(t) {
mapMethod(target, javaObj, t)
});
return target;
}
function getJavaObjectMethods(javaObj) {
var className = javaObj.class.name
var className = javaObj.class.name;
if (!classMethodsCache[className]) {
var names = [];
var methods = javaObj.class.methods;
for (var i in methods){
for (var i in methods) {
names.push(methods[i].name);
}
classMethodsCache[className] = names;
@ -162,7 +155,7 @@ function getJavaObjectMethods(javaObj) {
return classMethodsCache[className];
}
function mapMethod (target, source, name) {
function mapMethod(target, source, name) {
target[name] = function __SimpleDynamicMethod__() {
if (arguments.length > 0) {
return source[name](Array.prototype.slice.call(arguments));
@ -173,13 +166,16 @@ function mapMethod (target, source, name) {
}
function on(obj) {
if (!obj || !obj.class) { throw new TypeError('参数 %s 不是一个Java对象!'.format(obj)) }
if (!obj || !obj.class) {
throw new TypeError('参数 %s 不是一个Java对象!'.format(obj))
}
return new Reflect(obj);
}
// noinspection JSUnusedGlobalSymbols
exports = module.exports = {
on: on,
accessible: accessible,
declaredMethods: declaredMethods,
mapToObject: mapToObject
}
};

View File

@ -13,12 +13,12 @@ var ChatMessagePart = function () {
this.click = function (action, value) {
this.clickEventAction = action;
this.clickEventValue = value;
}
};
this.hover = function (action, value) {
this.hoverEventAction = action;
this.hoverEventValue = value;
}
};
this.convert = function () {
var str = {};
@ -42,7 +42,7 @@ var ChatMessagePart = function () {
}
return str;
}
}
};
var Tellraw = function () {
var parts = [new ChatMessagePart()];
@ -63,12 +63,12 @@ var Tellraw = function () {
parts.push(part);
}
this.cache = null;
}
};
this.text = function (text) {
this.latest().text = text;
return this;
}
};
this.tip = function (str) {
if (toString.call(str) === "[object Array]") {
@ -76,63 +76,63 @@ var Tellraw = function () {
}
this.latest().hover("show_text", str);
return this;
}
};
this.item = function (str) {
this.latest().hover("show_item", str);
return this;
}
};
this.cmd = this.command = function (command) {
this.latest().click("run_command", command);
return this;
}
};
this.suggest = function (url) {
this.latest().click("suggest_command", url);
return this;
}
};
this.file = function (path) {
this.latest().click("open_file", path);
return this;
}
};
this.link = function (url) {
this.latest().click("open_url", url);
return this;
}
};
this.latest = function () {
return parts[parts.length - 1];
}
};
this.json = function () {
if (!this.cache) {
var temp = [];
parts.forEach(function (t) {
temp.push(t.convert());
})
});
this.cache = JSON.stringify(temp);
console.debug(this.cache);
}
return this.cache;
}
};
this.send = function (player) {
chat.json(player, self.json());
}
};
this.sendAll = function () {
server.players(function sendAllMessage(p) {
self.send(p);
})
}
}
};
Tellraw.create = function () {
return new Tellraw().then(Tellraw.duplicateChar);
}
};
Tellraw.duplicateChar = '§卐';

View File

@ -26,10 +26,10 @@ function compare(prop) {
return 1;
} else {
return 0;
}
}
}
}
}
exports = module.exports = {
compare: compare
}
};

View File

@ -16,9 +16,9 @@ function unzip(zipFile, target) {
return;
}
if (target === undefined) {
var fname = zipFile.name;
var fileName = zipFile.name;
// noinspection JSUnresolvedVariable
target = fs.file(zipFile.parentFile.canonicalPath, fname.substring(0, fname.length() - 4));
target = fs.file(zipFile.parentFile.canonicalPath, fileName.substring(0, fileName.length() - 4));
}
console.debug("解压文件 %s 到目录 %s".format(zipFile.canonicalPath, target));
var zipObj = new ZipFile(zipFile);

View File

@ -25,6 +25,7 @@ function load() {
}
function enable() {
// noinspection JSUnusedLocalSymbols
command.on(this, 'hello', {
cmd: function (sender, command, args) {
engineLoad(fs.file(root, 'test.js'));
@ -34,20 +35,19 @@ function enable() {
console.log('启用 Hello World 测试插件!');
switch (DetectServerType) {
case ServerType.Bukkit:
event.on(this, 'playerloginevent', function join(event) {
event.on(this, 'PlayerLoginEvent', function join(event) {
send(event, wrapper.player(event.player));
});
break;
case ServerType.Sponge:
// clientconnectionevent.join
event.on(this, 'clientconnectionevent.join', function join(event) {
event.on(this, 'ClientConnectionEvent.Join', function join(event) {
send(event, wrapper.player(event.targetEntity));
});
break;
}
}
function send(event, player){
function send(event, player) {
// noinspection JSUnresolvedVariable
console.debug('玩家', player.getName(), "触发事件", event.class.simpleName);
setTimeout(function () {

View File

@ -1,7 +1,5 @@
'use strict';
/*global Java, base, module, exports, require*/
var server = require('api/server');
var event = require('api/event');
var task = require('api/task');
var http = require('http');
@ -32,39 +30,39 @@ function enable() {
case ServerType.Bukkit:
event.on(self, 'ItemMergeEvent', function (event) {
bukkit(event.target, event.entity.itemStack.amount + event.target.itemStack.amount);
})
});
event.on(self, 'ItemSpawnEvent', function (event) {
if (event.entity.itemStack) {
bukkit(event.entity, event.entity.itemStack.amount);
}
})
});
break;
case ServerType.Sponge:
Keys = Java.type('org.spongepowered.api.data.key.Keys');
event.on(self, 'ItemMergeItemEvent', function (event) {
// Sponge 暂未实现当前事件
})
});
event.on(self, 'SpawnEntityEvent', function (event) {
event.entities.forEach(function (entity) {
if (entity.type.name === "item") sponge(entity);
})
})
});
break;
}
}
function bukkit(item , amount) {
function bukkit(item, amount) {
item.setCustomName('§b' + getItemName(item.itemStack.type) + getItemCount(amount));
item.setCustomNameVisible(true);
}
function sponge(entity) {
var itemOptional = entity.get(Keys.REPRESENTED_ITEM);
var itemOptional = entity.get(Keys['REPRESENTED_ITEM']);
if (itemOptional.isPresent()) {
var item = itemOptional.get();
var itemName = '§b' + getItemName(item.type.name.split(':')[1]) + getItemCount(item.count);
entity.offer(Keys.DISPLAY_NAME, org.spongepowered.api.text.Text.of(itemName));
entity.offer(Keys.CUSTOM_NAME_VISIBLE, true);
entity.offer(Keys['DISPLAY_NAME'], org.spongepowered.api.text.Text.of(itemName));
entity.offer(Keys['CUSTOM_NAME_VISIBLE'], true);
}
}
@ -72,8 +70,8 @@ function getItemName(name) {
return itemConfig[(name + '').toUpperCase()] || name;
}
function getItemCount(amount){
return amount == 1 ? "" : "*" + amount;
function getItemCount(amount) {
return amount === 1 ? "" : "*" + amount;
}
module.exports = {

View File

@ -5,14 +5,13 @@
/*global Java, base, module, exports, require*/
var event = require('api/event');
var wrapper = require('api/wrapper');
var command = require('api/command');
var server = require('api/server');
var fs = require('fs');
var tellraw = require('tellraw');
var papi = require('papi');
var utils = require('utils')
var utils = require('utils');
var Player;
var description = {
name: 'MiaoChat',
@ -34,45 +33,45 @@ var description = {
}
},
config: {
"Version":"1.8.5",
"BungeeCord":true,
"Server":"生存服",
"ChatFormats":{
"default":{
"index":50,
"permission":"MiaoChat.default",
"range":0,
"format":"[world][player]: ",
"item":true,
"itemformat":"&6[&b%s&6]&r"
Version: "1.8.5",
BungeeCord: true,
Server: "生存服",
ChatFormats: {
"default": {
"index": 50,
"permission": "MiaoChat.default",
"range": 0,
"format": "[world][player]: ",
"item": true,
"itemformat": "&6[&b%s&6]&r"
},
"admin":{
"index":49,
"permission":"MiaoChat.admin",
"format":"[admin][world][player][help]: ",
"range":0,
"item":true,
"itemformat":"&6[&b%s&6]&r"
"admin": {
"index": 49,
"permission": "MiaoChat.admin",
"format": "[admin][world][player][help]: ",
"range": 0,
"item": true,
"itemformat": "&6[&b%s&6]&r"
}
},
StyleFormats: {
"world":{
"text":"&6[&a%player_world%&6]",
"hover":[
"world": {
"text": "&6[&a%player_world%&6]",
"hover": [
"&6当前所在位置:",
"&6世界: &d%player_world%",
"&6坐标: &aX:%player_x% Y: %player_y% Z: %player_z%",
"",
"&c点击即可TP我!"
],
"click":{
"type":"COMMAND",
"command":"/tpa %player_name%"
"click": {
"type": "COMMAND",
"command": "/tpa %player_name%"
}
},
"player":{
"text":"&b%player_name%",
"hover":[
"player": {
"text": "&b%player_name%",
"hover": [
"&6玩家名称: &b%player_name%",
"&6玩家等级: &a%player_level%",
"&6玩家血量: &c%player_health%",
@ -81,22 +80,22 @@ var description = {
"",
"&c点击与我聊天"
],
"click":{
"type":"SUGGEST",
"command":"/tell %player_name%"
"click": {
"type": "SUGGEST",
"command": "/tell %player_name%"
}
},
"admin":{
"text":"&6[&c管理员&6]"
"admin": {
"text": "&6[&c管理员&6]"
},
"help":{
"text":"&4[求助]",
"hover":[
"help": {
"text": "&4[求助]",
"hover": [
"点击求助OP"
],
"click":{
"type":"COMMAND",
"command":"管理员@%player_name% 我需要你的帮助!"
"click": {
"type": "COMMAND",
"command": "管理员@%player_name% 我需要你的帮助!"
}
}
}
@ -120,11 +119,11 @@ function initFormat(chat_formats) {
chat_formats.forEach(function (chat_format) {
var chat_format_str = chat_format.format;
var temp = [];
var r = [];
while(r = FORMAT_PATTERN.exec(chat_format_str)) {
var r;
while (r = FORMAT_PATTERN.exec(chat_format_str)) {
temp.push(r[1]);
}
var format_list = []
var format_list = [];
temp.forEach(function splitStyle(t) {
var arr = chat_format_str.split('[' + t + ']', 2);
if (arr[0]) {
@ -147,11 +146,12 @@ function enable() {
function registerCommand() {
command.on(self, 'mchat', {
cmd: mchat
cmd: mainCommand
});
}
function mchat(sender, command, args) {
// noinspection JSUnusedLocalSymbols
function mainCommand(sender, command, args) {
return true;
}
@ -161,29 +161,36 @@ function registerEvent() {
event.on(self, 'AsyncPlayerChatEvent', handlerBukkitChat);
break;
case ServerType.Sponge:
Player = org.spongepowered.api.entity.living.player.Player;
event.on(self, 'MessageChannelEvent.Chat', handlerSpongeChat);
break;
}
}
function handlerBukkitChat(event) {
sendChat(event.player, event.message, function() { event.setCancelled(true); });
sendChat(event.player, event.message, function () {
event.setCancelled(true);
});
}
function handlerSpongeChat(event) {
var player = event.getCause().first(org.spongepowered.api.entity.living.player.Player.class).orElse(null);
if (player == null) { return; }
var player = event.getCause().first(Player.class).orElse(null);
if (player == null) {
return;
}
var plain = event.getRawMessage().toPlain();
if (plain.startsWith(tellraw.duplicateChar)) {
return;
}
sendChat(player, plain, function() { event.setMessageCancelled(true) });
sendChat(player, plain, function () {
event.setMessageCancelled(true)
});
}
function sendChat(player, plain, callback) {
var chat_format = getChatFormat(player);
if (!chat_format) {
console.debug('未获得用户', player.name, '的 ChatRule 跳过执行...')
console.debug('未获得用户', player.name, '的 ChatRule 跳过执行...');
return;
}
callback();
@ -191,34 +198,34 @@ function sendChat(player, plain, callback) {
chat_format.format_list.forEach(function setStyle(format) {
var style = style_formats[format];
if (style) {
tr.then(replace(player, style.text));
if (style.hover) {
tr.tip(replace(player, style.hover));
}
if (style.click && style.click.type && style.click.command) {
var command = replace(player, style.click.command)
switch (style.click.type) {
case "COMMAND":
tr.command(command);
break;
case "OPENURL":
tr.link(command);
break;
case "SUGGEST":
tr.suggest(command);
break;
default:
}
}
tr.then(replace(player, style.text));
if (style.hover) {
tr.tip(replace(player, style.hover));
}
if (style.click && style.click.type && style.click.command) {
var command = replace(player, style.click.command);
switch (style.click.type) {
case "COMMAND":
tr.command(command);
break;
case "OPENURL":
tr.link(command);
break;
case "SUGGEST":
tr.suggest(command);
break;
default:
}
}
} else {
tr.then(replace(player, format));
}
})
});
tr.then(replace(player, plain)).sendAll();
}
function getChatFormat(player) {
for (var i in chat_formats){
for (var i in chat_formats) {
var format = chat_formats[i];
if (player.hasPermission(format.permission)) {
return format;

View File

@ -1,17 +1,15 @@
'use strict'
/*global Java, base, module, exports, require*/
'use strict';
/*global Java, base, module, exports, require, __dirname, __filename*/
var command = require('api/command');
var manager = require('api/plugin');
var task = require('api/task');
var wrapper = require('api/wrapper')
var command = require('api/command')
var manager = require('api/plugin')
var task = require('api/task')
var http = require('http');
var fs = require('fs');
var http = require('http')
var fs = require('fs')
var pluginCache = []
var packageCache = []
var packageNameCache = []
var pluginCache = [];
var packageCache = [];
var packageNameCache = [];
var description = {
name: 'MiaoScriptPackageManager',
@ -26,7 +24,7 @@ var description = {
config: {
center: 'https://ms.yumc.pw/api/package/list'
}
}
};
var help = [
'§6========= §a' + description.name + ' §6帮助 §aBy §b喵♂呜 §6=========',
@ -35,7 +33,7 @@ var help = [
'§6/mpm §aupdate <插件名称> §6- §3更新插件(无插件名称则更新源)',
'§6/mpm §aupgrade <插件名称> §6- §3及时更新插件(update需要重启生效)',
'§6/mpm §areload <插件名称> §6- §3重载插件(无插件名称则重载自生)',
]
];
function load() {
task.async(function () {
@ -53,19 +51,19 @@ function enable() {
if (args.length > 0) {
switch (args[0]) {
case "list":
console.sender(sender, '§6当前 §bMiaoScriptPackageCenter §6中存在下列插件:')
console.sender(sender, '§6当前 §bMiaoScriptPackageCenter §6中存在下列插件:');
for (var pkgName in packageCache) {
var pkg = packageCache[pkgName]
var pkg = packageCache[pkgName];
console.sender(sender, '§6插件名称: §b%s §6版本: §a%s'.format(pkg.name, pkg.version))
}
break
break;
case "install":
if (args.length > 1) {
download(sender, args[1]);
} else {
console.sender(sender, '§c请输入插件名称!')
}
break
break;
case "update":
if (args.length > 1) {
update(sender, args[1]);
@ -73,19 +71,19 @@ function enable() {
load();
console.sender(sender, "§a仓库缓存刷新成功 共存在 §b" + pluginCache.length + " §a个插件!")
}
break
break;
case "upgrade":
break
break;
case "delete":
if (args.length > 1) {
del(sender, args[1]);
} else {
console.sender(sender, '§c请输入插件名称!')
}
break
break;
case "reload":
if (args.length > 1) {
var pname = args[1]
var pname = args[1];
if (pluginCache.indexOf(pname) !== -1) {
manager.reload(pname)
} else {
@ -95,7 +93,7 @@ function enable() {
self.reloadConfig();
load();
}
break
break;
case "help":
sendHelp(sender);
break;
@ -105,7 +103,7 @@ function enable() {
}
},
tab: function (sender, command, args) {
if (args.length === 1) return ['list', 'install', 'update', 'upgrade', 'reload']
if (args.length === 1) return ['list', 'install', 'update', 'upgrade', 'reload'];
if (args.length > 1) {
switch (args[0]) {
case "install":
@ -120,7 +118,7 @@ function enable() {
})
}
function sendHelp(sender){
function sendHelp(sender) {
help.forEach(function (msg) {
console.sender(sender, msg);
})
@ -159,4 +157,4 @@ module.exports = {
load: load,
enable: enable,
disable: disable
}
};

View File

@ -121,12 +121,13 @@ function newItemFromConfig(config) {
}
function enable() {
// noinspection JSUnusedLocalSymbols
command.on(this, 'l', {
cmd: function (sender, command, args) {
if (!sender.openInventory) {
console.sender(sender, "§4当前用户无法使用该命令!");
}
var inv = bukkit.$.createInventory(null, 54, config.title);
var inv = MServer.createInventory(null, 54, config.title);
inv.setContents(items);
sender.openInventory(inv);
return true;
@ -178,14 +179,14 @@ function enable() {
console.sender(player, '§c抽奖物品和钥匙不匹配!');
return;
}
var resultlist = [];
var resultList = [];
litem.result.forEach(function (t) {
for (var i = 0; i < t.percent; i++) {
resultlist.push(t);
resultList.push(t);
}
});
var ri = ext.random(resultlist.length);
var result = resultlist[ri];
var ri = ext.random(resultList.length);
var result = resultList[ri];
box.amount = box.amount - 1;
key.amount = key.amount - 1;
inv.setItem(10, box);

View File

@ -46,8 +46,8 @@ function load() {
function enable() {
command.on(self, 'mtag', {
cmd: function cmd(sender, command, args) {
var subcommand = args[0];
switch (subcommand) {
var subCommand = args[0];
switch (subCommand) {
case 'reload':
self.reloadConfig();
fakeTag = new FakeTag(config.format);

View File

@ -1,24 +0,0 @@
'use strict';
/**
* PAPI扩展类
*/
/*global Java, base, module, exports, require, __FILE__*/
var PlaceholderAPI;
var bukkit = require('api/server');
if (bukkit.plugin.load("PlaceholderAPI")) {
PlaceholderAPI = ext.getStatic("me.clip.placeholderapi.PlaceholderAPI");
} else {
log.w("PlaceholderAPI 未找到 变量替换功能失效!");
PlaceholderAPI = {
setPlaceholders: function () {
return arguments[1];
}
}
}
exports.$ = function () {
if (arguments.length > 1) {
return PlaceholderAPI.setPlaceholders(arguments[0], arguments[1]);
} else {
return PlaceholderAPI.setPlaceholders(null, arguments[0]);
}
};

View File

@ -1,14 +1,7 @@
package pw.yumc.MiaoScript;
import java.io.FileReader;
import javax.script.ScriptEngineManager;
import org.junit.Test;
import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.engine.MiaoScriptEngine;
/**
* Created with IntelliJ IDEA
*
@ -16,24 +9,7 @@ import pw.yumc.YumCore.engine.MiaoScriptEngine;
* Created on 2017/9/14 10:08.
*/
public class MiaoScriptTest {
private MiaoScriptEngine engine;
@Test
public void testBoot() {
Thread currentThread = Thread.currentThread();
ClassLoader previousClassLoader = currentThread.getContextClassLoader();
currentThread.setContextClassLoader(getClass().getClassLoader());
try {
ScriptEngineManager manager = new ScriptEngineManager();
this.engine = new MiaoScriptEngine(manager);
this.engine.put("base", new Base());
this.engine.eval(new FileReader("src/main/resources/bios.js"));
engine.invokeFunction("boot", null, engine);
} catch (Exception e) {
Log.w("脚本引擎初始化失败! %s:%s", e.getClass().getName(), e.getMessage());
e.printStackTrace();
} finally {
currentThread.setContextClassLoader(previousClassLoader);
}
}
}