refactor: remove old file & update bios.js

Signed-off-by: MiaoWoo <admin@yumc.pw>
merge/3/MERGE
MiaoWoo 2019-09-10 17:15:53 +08:00
parent 96639d0978
commit 7dad0e7abc
65 changed files with 2 additions and 8881 deletions

View File

@ -26,22 +26,15 @@ var global = this;
release(root, '(core|node_modules)+/.*', !global.debug);
// Plugin file decompression to folder when file not exist
release(root, '(plugins)+/.*', false);
load(root + '/core/init.js');
try {
init(root);
} catch (ex) {
ex.printStackTrace();
}
load(root + '/core/ployfill.js')(root, logger);
require('@ms/core');
};
var pluginYml;
function checkClassLoader() {
// noinspection JSUnresolvedVariable
var classLoader = java.lang.Thread.currentThread().contextClassLoader;
pluginYml = classLoader.getResource("plugin.yml");
if (pluginYml === null) {
engineDisable = function engineDisable() { }
throw Error("Error class loader: " + classLoader.class.name + " Please contact the author MiaoWoo!");
} else {
log.info("Class loader compatible: " + classLoader.class.name);
@ -62,11 +55,9 @@ 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

@ -1,12 +0,0 @@
'use strict';
/**
* MiaoScript Chat处理类
*/
/*global Java, base, module, exports, require*/
function ChatHandlerDefault() {
// noinspection JSUnusedGlobalSymbols
this.tellraw = function(sender, raw) {
this.json(sender, JSON.stringify(raw));
}
}
exports = module.exports = Object.assign(new ChatHandlerDefault(), requireInternal('chat'));

View File

@ -1,20 +0,0 @@
'use strict';
/**
* MiaoScript Command处理类
*/
/*global Java, base, module, exports, require*/
function CommandHandlerDefault() {
this.on = function(jsp, name, exec) {
var cmd = this.create(jsp, { name: name });
console.debug('插件 %s 创建命令 %s(%s)...'.format(jsp.description.name, name, cmd))
if (exec.cmd && typeof exec.cmd === "function") {
this.onCommand(jsp, cmd, exec.cmd)
} else {
throw Error("CommandExec Must be a function... Input: " + exec.cmd)
}
if (exec.tab && typeof exec.tab === "function") {
this.onTabComplete(jsp, cmd, exec.tab)
}
}
}
exports = module.exports = Object.assign(new CommandHandlerDefault(), requireInternal('command'));

View File

@ -1,165 +0,0 @@
'use strict';
/**
* MiaoScript Event处理类
*/
/*global Java, base, module, exports, require, __FILE__*/
function EventHandlerDefault() {
var Thread = Java.type("java.lang.Thread");
// noinspection JSUnresolvedVariable
this.plugin = require('api/server').plugin.self;
this.mapEvent = [];
this.listenerMap = [];
this.baseEventDir = '';
/**
* 扫描包 org.bukkit.event 下的所有事件
* 映射简写名称 org.bukkit.event.player.PlayerLoginEvent => playerloginevent
*/
this.mapEventName = function mapEventName() {
if (this.baseEventDir === "") {
throw new Error("事件基础包名为空 无法进行事件映射!");
}
var count = 0;
var dirs = Thread.currentThread().getContextClassLoader().getResources(this.baseEventDir);
while (dirs.hasMoreElements()) {
var url = dirs.nextElement();
var protocol = url.protocol;
if (protocol === "jar") {
// noinspection JSUnresolvedVariable
var jar = url.openConnection().jarFile;
var entries = jar.entries();
while (entries.hasMoreElements()) {
var entry = entries.nextElement();
var name = entry.name;
// 以 org/bukkit/event 开头 并且以 .class 结尾
if (name.startsWith(this.baseEventDir) && name.endsWith(".class")) {
var i = name.replaceAll('/', '.');
try {
var clz = base.getClass(i.substring(0, i.length - 6));
// 继承于 org.bukkit.event.Event 访问符为Public
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++;
}
} catch (ex) {
//ignore already loaded class
}
}
}
}
}
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'];
if (!eventCls) {
try {
eventCls = base.getClass(eventCls);
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)));
return;
}
}
return eventCls;
};
// noinspection JSUnusedLocalSymbols
/**
* 判断是否为一个有效的事件类
* @param clz
* @returns {*|boolean}
*/
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 {
var time = new Date().getTime()
exec(arguments[arguments.length - 1]);
var cost = new Date().getTime() - time;
if (cost > 20) {
console.console('§c注意! §6插件 §b%s §6处理 §d%s §6事件 §c耗时 §4%sms !'.format(name, this.class2Name(eventCls), cost))
}
} catch (ex) {
console.console('§6插件 §b%s §6处理 §d%s §6事件时发生异常 §4%s'.format(name, this.class2Name(eventCls), ex));
console.ex(ex);
}
}.bind(this);
};
/**
* 添加事件监听
* @param jsp
* @param event
* @param exec {function}
* @param priority [LOWEST,LOW,NORMAL,HIGH,HIGHEST,MONITOR]
* @param ignoreCancel
*/
this.listen = function listen(jsp, event, exec, priority, ignoreCancel) {
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 (typeof priority === 'boolean') {
ignoreCancel = priority;
priority = 'NORMAL';
}
priority = priority || 'NORMAL';
ignoreCancel = ignoreCancel || false;
// noinspection JSUnusedGlobalSymbols
var listener = this.register(eventCls, this.execute(name, exec, eventCls), priority, ignoreCancel);
var listenerMap = this.listenerMap;
// 添加到缓存 用于关闭插件的时候关闭事件
if (!listenerMap[name]) listenerMap[name] = [];
var offExec = function() {
this.unregister(eventCls, listener);
console.debug('插件 %s 注销事件 %s'.format(name, this.class2Name(eventCls)));
}.bind(this);
var off = {
event: eventCls,
listener: listener,
off: offExec
};
listenerMap[name].push(off);
// noinspection JSUnresolvedVariable
console.debug('插件 %s 注册事件 %s => %s'.format(name, this.class2Name(eventCls), exec.name || '匿名方法'));
return off;
}
}
var EventHandler = Object.assign(new EventHandlerDefault(), requireInternal('event'));
// 映射事件名称
console.info('%s 事件映射完毕 共计 %s 个事件!'.format(DetectServerType, EventHandler.mapEventName().toFixed(0)));
module.exports = {
on: EventHandler.listen.bind(EventHandler),
disable: function(jsp) {
var eventCache = EventHandler.listenerMap[jsp.description.name];
if (eventCache) {
eventCache.forEach(function(t) { t.off.call(EventHandler) });
delete EventHandler.listenerMap[jsp.description.name];
}
}
};

View File

@ -1,9 +0,0 @@
'use strict';
/**
* MiaoScript Item处理类
*/
/*global Java, base, module, exports, require*/
/*global Java, base, module, exports, require*/
function ItemHandlerDefault() {
}
exports = module.exports = Object.assign(new ItemHandlerDefault(), requireInternal('item', true));;

View File

@ -1,8 +0,0 @@
'use strict';
/**
* MiaoScript Permission处理类
*/
/*global Java, base, module, exports, require*/
function PermissionHandlerDefault() {
}
exports = module.exports = Object.assign(new PermissionHandlerDefault(), requireInternal('permission', true));

View File

@ -1,295 +0,0 @@
'use strict';
/**
* MiaoScript脚本插件加载类
*/
/*global Java, module, exports, require, __FILE__*/
var fs = require('fs');
var yaml = require('yaml');
var event = require('./event');
var server = require('./server');
var command = require('./command');
var permission = require('./permission');
/**
* 载入插件
* @param dir
*/
function loadPlugins(dir) {
var plugin = fs.file(root, dir);
if (!plugin) {
console.info("First Running Create Plugins Floder %s ...".format(plugin));
} else {
console.info("Start Scan %s Plugins ...".format(plugin));
createUpdate(plugin);
var files = [];
fs.list(plugin).forEach(function searchPlugin(file) {
files.push(file.toFile());
});
fs.list(fs.file(plugin, DetectServerType)).forEach(function searchDetectServerPlugin(file) {
files.push(file.toFile());
});
loadZipPlugins(files);
loadJsPlugins(files);
}
}
/**
* 更新插件
* @param path
*/
function createUpdate(path) {
var update = fs.file(path, "update");
if (!update.exists()) {
update.mkdirs();
}
}
/**
* ZIP类型插件预加载
* @param files
*/
function loadZipPlugins(files) {
files.filter(function filterZipPlugin(file) {
return file.name.endsWith(".zip");
}).forEach(function loadZipPlugin(file) {
// console.log(file);
// console.log(fs.file(file,"!package.json"))
// zip.unzip(fs.file(plugins_dir, file));
// var dir = new File(plugins_dir, file.name.split(".")[0]);
// TODO 添加文件夹类型的插件兼容
});
}
/**
* JS类型插件预加载
*/
function loadJsPlugins(files) {
files.filter(function filterJsPlugin(file) {
return file.name.endsWith(".js")
}).forEach(function loadJsPlugin(file) {
try {
loadPlugin(file)
} catch (ex) {
console.console('§6插件 §b%s §6初始化时发生错误 §4%s'.format(file.name, ex.message));
console.ex(ex);
}
})
}
function loadPlugin(file) {
var plugin = readPlugin(file);
initPlugin(plugin);
plugins[plugin.description.name] = plugin;
return plugin
}
function readPlugin(file) {
var update = fs.file(fs.file(file.parentFile, 'update'), file.name);
if (update.exists()) {
console.info('Auto Update Plugin %s'.format(file.name));
fs.move(update, file, true);
}
var plugin = require(file, {
cache: false,
hook: function(origin) {
return beforeLoadHook(origin);
}
});
console.debug("插件编译结果: %s".format(JSON.stringify(plugin)));
plugin.__FILE__ = file;
return plugin;
}
function initPlugin(plugin) {
var desc = plugin.description;
if (!desc || !desc.name) {
throw new Error("文件 %s 不存在 description 描述信息 无法加载插件!".format(plugin.__FILE__));
} else {
internalInitPlugin(plugin);
afterLoadHook(plugin);
console.info('Loading Plugin %s Version %s By %s'.format(desc.name, desc.version || 'Unknown', desc.author || 'Unknown'));
}
return plugin;
}
function beforeLoadHook(origin) {
var result = origin;
// 处理 event 为了不影响 正常逻辑 event 还是手动require吧
// result = result + 'var event = {}; module.exports.event = event;';
// 注入 console 对象 // 给插件注入单独的 console
result += '\nvar console = new Console(); module.exports.console = console;';
// 插件注入 self 对象
result += '\nvar self = {}; module.exports.self = self;';
return result;
}
function afterLoadHook(plugin) {
// plugin.event.on = event.on.bind(plugin);
// 给 console 添加插件名称
plugin.console.name = plugin.description.prefix || plugin.description.name;
// 赋值 self
Object.assign(plugin.self, plugin);
}
/**
* 初始化插件内容(提供config,__DATA__等参数)
*/
function internalInitPlugin(plugin) {
// 初始化 __DATA__
plugin.__DATA__ = plugin.dataFolder = fs.file(plugin.__FILE__.parentFile, plugin.description.name);
// 初始化 getDataFolder()
plugin.getDataFolder = function getDataFolder() {
return plugin.__DATA__;
};
// 初始化 getFile()
plugin.getFile = plugin.file = function getFile(name) {
return fs.file(plugin.getDataFolder(), name);
};
// 初始化插件配置相关方法
initPluginConfig(plugin);
if (command.enable) command.enable(plugin);
if (permission.enable) permission.enable(plugin);
}
/**
* 初始化插件配置
*/
function initPluginConfig(plugin) {
// 初始化 config
plugin.configFile = plugin.getFile('config.yml');
// 判断插件目录是否存在 并且不为文件 否则删除重建
// noinspection JSValidateTypes
if (!plugin.configFile.parentFile.isDirectory()) {
fs.del(plugin.configFile.parentFile);
}
plugin.configFile.parentFile.mkdirs();
/**
* 获取配置文件
* @constructor
* @constructor (file|string)
*/
plugin.getConfig = function() {
switch (arguments.length) {
case 0:
return plugin.config;
case 1:
var file = arguments[0];
if (!file.isFile) {
file = plugin.getFile(file);
}
return yaml.safeLoad(fs.read(file), { json: true });
}
};
/**
* 重载配置文件
* @constructor
* @constructor (file|string)
*/
plugin.reloadConfig = function() {
plugin.config = plugin.getConfig(plugin.configFile);
};
/**
* 保存配置文件
* @constructor
* @constructor (file, content)
*/
plugin.saveConfig = function() {
switch (arguments.length) {
case 0:
fs.save(plugin.configFile, yaml.safeDump(plugin.config));
break;
case 2:
fs.save(fs.file(plugin.__DATA__, arguments[0]), yaml.safeDump(arguments[1]));
break;
}
};
// noinspection JSValidateTypes
if (plugin.configFile.isFile()) {
plugin.config = Object.assign(plugin.description.config, plugin.getConfig('config.yml'));
} else if (plugin.description.config) {
plugin.config = plugin.description.config;
plugin.saveConfig();
}
}
function checkAndGet(args) {
if (args.length === 0) {
return plugins;
}
var name = args[0];
// 如果是插件 则直接返回
if (name && name.description) {
return [name];
}
var plugin = exports.plugins[name];
if (!plugin) {
throw new Error("插件 " + name + " 不存在!", args);
}
return [plugin];
}
function checkAndRun(args, name, ext) {
var pls = checkAndGet(args);
for (var i in pls) {
var jsp = pls[i];
var exec = jsp[name];
try {
// 绑定方法的this到插件自身
if (typeof exec === "function") exec.call(jsp);
if (typeof ext === "function") ext.call(jsp);
} catch (ex) {
console.console('§6插件 §b%s §6执行 §d%s §6方法时发生错误 §4%s'.format(jsp.description.name, name, ex.message));
console.ex(ex);
}
}
}
var plugins = [];
function init(path) {
var plugin = exports.$;
if (plugin !== null) {
// 如果plugin不等于null 则代表是正式环境
console.info("Initialization MiaoScript Plugin System: %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 reloadPlugin(p) {
disable(p);
p = loadPlugin(p.__FILE__);
if (p) {
load(p);
enable(p);
}
}
function reload() {
checkAndGet(arguments).forEach(reloadPlugin);
}
// noinspection JSUnresolvedVariable
exports = module.exports = {
$: server.plugin.self,
plugins: plugins,
init: init,
load: load,
enable: enable,
disable: disable,
reload: reload,
loadPlugin: loadPlugin
};

View File

@ -1,16 +0,0 @@
/*global Java, base, module, exports, require*/
function ServerHandlerDefault() {
/**
* 获取在线玩家
*/
this.players = function() {
switch (arguments.length) {
case 1:
if (toString.call(arguments[0]) !== "[object Function]") { throw TypeError('first argument must be a function!') }
return this.onlinePlayers().forEach(arguments[0]);
default:
return this.onlinePlayers();
}
};
}
exports = module.exports = Object.assign(new ServerHandlerDefault(), requireInternal('server'));

View File

@ -1,9 +0,0 @@
'use strict';
/**
* MiaoScript Task处理类
* @namespace plugin.configFile.parentFile, command.enable, permission.enable
*/
/*global Java, base, module, exports, require*/
function TaskHandlerDefault() {
}
exports = module.exports = Object.assign(new TaskHandlerDefault(), requireInternal('task'));

View File

@ -1,5 +0,0 @@
/*global Java, base, module, exports, require*/
var player = requireInternal('wrapper/player');
module.exports = {
player: player.$
};

View File

@ -1,226 +0,0 @@
/*
* $Id: base64.js,v 2.15 2014/04/05 12:58:57 dankogai Exp dankogai $
*
* Licensed under the BSD 3-Clause License.
* http://opensource.org/licenses/BSD-3-Clause
*
* References:
* http://en.wikipedia.org/wiki/Base64
*/
(function(global) {
'use strict';
// existing version for noConflict()
var _Base64 = global.Base64;
var version = "2.3.2";
// if node.js, we use Buffer
var buffer;
if (typeof module !== 'undefined' && module.exports) {
try {
buffer = require('buffer').Buffer;
} catch (err) {
}
}
// constants
// 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;
return t;
}(b64chars);
var fromCharCode = String.fromCharCode;
// encoder stuff
var cb_utob = function(c) {
if (c.length < 2) {
var cc = c.charCodeAt(0);
return cc < 0x80 ? c
: cc < 0x800 ? (fromCharCode(0xc0 | (cc >>> 6))
+ fromCharCode(0x80 | (cc & 0x3f)))
: (fromCharCode(0xe0 | ((cc >>> 12) & 0x0f))
+ fromCharCode(0x80 | ((cc >>> 6) & 0x3f))
+ fromCharCode(0x80 | (cc & 0x3f)));
} else {
var ccc = 0x10000
+ (c.charCodeAt(0) - 0xD800) * 0x400
+ (c.charCodeAt(1) - 0xDC00);
return (fromCharCode(0xf0 | ((ccc >>> 18) & 0x07))
+ fromCharCode(0x80 | ((ccc >>> 12) & 0x3f))
+ fromCharCode(0x80 | ((ccc >>> 6) & 0x3f))
+ fromCharCode(0x80 | (ccc & 0x3f)));
}
};
var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
var utob = function(u) {
return u.replace(re_utob, cb_utob);
};
var cb_encode = function(ccc) {
var padlen = [0, 2, 1][ccc.length % 3],
ord = ccc.charCodeAt(0) << 16
| ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8)
| ((ccc.length > 2 ? ccc.charCodeAt(2) : 0)),
chars = [
b64chars.charAt(ord >>> 18),
b64chars.charAt((ord >>> 12) & 63),
padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63),
padlen >= 1 ? '=' : b64chars.charAt(ord & 63)
];
return chars.join('');
};
var btoa = global.btoa ? function(b) {
return global.btoa(b);
} : function(b) {
return b.replace(/[\s\S]{1,3}/g, cb_encode);
};
var _encode = buffer ?
buffer.from && buffer.from !== Uint8Array.from ? function(u) {
return (u.constructor === buffer.constructor ? u : buffer.from(u))
.toString('base64')
}
: function(u) {
return (u.constructor === buffer.constructor ? u : new buffer(u))
.toString('base64')
}
: function(u) {
return btoa(utob(u))
}
;
var encode = function(u, urisafe) {
return !urisafe
? _encode(String(u))
: _encode(String(u)).replace(/[+\/]/g, function(m0) {
return m0 === '+' ? '-' : '_';
}).replace(/=/g, '');
};
var encodeURI = function(u) {
return encode(u, true)
};
// decoder stuff
var re_btou = new RegExp([
'[\xC0-\xDF][\x80-\xBF]',
'[\xE0-\xEF][\x80-\xBF]{2}',
'[\xF0-\xF7][\x80-\xBF]{3}'
].join('|'), 'g');
var cb_btou = function(cccc) {
switch (cccc.length) {
case 4:
var cp = ((0x07 & cccc.charCodeAt(0)) << 18)
| ((0x3f & cccc.charCodeAt(1)) << 12)
| ((0x3f & cccc.charCodeAt(2)) << 6)
| (0x3f & cccc.charCodeAt(3)),
offset = cp - 0x10000;
return (fromCharCode((offset >>> 10) + 0xD800)
+ fromCharCode((offset & 0x3FF) + 0xDC00));
case 3:
return fromCharCode(
((0x0f & cccc.charCodeAt(0)) << 12)
| ((0x3f & cccc.charCodeAt(1)) << 6)
| (0x3f & cccc.charCodeAt(2))
);
default:
return fromCharCode(
((0x1f & cccc.charCodeAt(0)) << 6)
| (0x3f & cccc.charCodeAt(1))
);
}
};
var btou = function(b) {
return b.replace(re_btou, cb_btou);
};
var cb_decode = function(cccc) {
var len = cccc.length,
padlen = len % 4,
n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0)
| (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0)
| (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0)
| (len > 3 ? b64tab[cccc.charAt(3)] : 0),
chars = [
fromCharCode(n >>> 16),
fromCharCode((n >>> 8) & 0xff),
fromCharCode(n & 0xff)
];
chars.length -= [0, 0, 2, 1][padlen];
return chars.join('');
};
var atob = global.atob ? function(a) {
return global.atob(a);
} : function(a) {
return a.replace(/[\s\S]{1,4}/g, cb_decode);
};
var _decode = buffer ?
buffer.from && buffer.from !== Uint8Array.from ? function(a) {
return (a.constructor === buffer.constructor
? a : buffer.from(a, 'base64')).toString();
}
: function(a) {
return (a.constructor === buffer.constructor
? a : new buffer(a, 'base64')).toString();
}
: function(a) {
return btou(atob(a))
};
var decode = function(a) {
return _decode(
String(a).replace(/[-_]/g, function(m0) {
return m0 === '-' ? '+' : '/'
})
.replace(/[^A-Za-z0-9+\/]/g, '')
);
};
var noConflict = function() {
var Base64 = global.Base64;
global.Base64 = _Base64;
return Base64;
};
// export Base64
// noinspection JSUnusedGlobalSymbols
global.Base64 = {
VERSION: version,
atob: atob,
btoa: btoa,
fromBase64: decode,
toBase64: encode,
utob: utob,
encode: encode,
encodeURI: encodeURI,
btou: btou,
decode: decode,
noConflict: noConflict
};
// if ES5 is available, make Base64.extendString() available
if (typeof Object.defineProperty === 'function') {
var noEnum = function(v) {
return { value: v, enumerable: false, writable: true, configurable: true };
};
global.Base64.extendString = function() {
Object.defineProperty(
String.prototype, 'fromBase64', noEnum(function() {
return decode(this)
}));
Object.defineProperty(
String.prototype, 'toBase64', noEnum(function(urisafe) {
return encode(this, urisafe)
}));
Object.defineProperty(
String.prototype, 'toBase64URI', noEnum(function() {
return encode(this, true)
}));
};
}
// module.exports and AMD are mutually exclusive.
// module.exports has precedence.
if (typeof module !== 'undefined' && module.exports) {
module.exports = global.Base64;
}
else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], function() {
return global.Base64
});
}
// that's it!
})(typeof self !== 'undefined' ? self
: typeof window !== 'undefined' ? window
: typeof global !== 'undefined' ? global
: this
);

174
src/main/resources/node_modules/fs.js generated vendored
View File

@ -1,174 +0,0 @@
'use strict';
/*global Java, base, module, exports, require, __FILE__*/
var File = Java.type("java.io.File");
var Files = Java.type("java.nio.file.Files");
var separatorChar = File.separatorChar;
var StandardCopyOption = Java.type("java.nio.file.StandardCopyOption");
/**
* 用文件分割符合并路径
*/
function concat() {
return Array.prototype.join.call(arguments, separatorChar);
}
/**
* 获得文件
* @constructor(file)
* @constructor(dir,file)
* @returns {*}
*/
function file() {
if (!arguments[0]) {
console.warn("文件名称不得为 undefined 或者 null !");
}
switch (arguments.length) {
case 1:
var f = arguments[0];
if (f instanceof File) {
return f;
}
if (typeof f === "string") {
return new File(f);
}
if (f instanceof java.nio.file.Path) {
return f.toFile();
}
break;
default:
return new File(file(arguments[0]), arguments[1]);
}
}
/**
* 创建目录
* @param path
*/
function mkdirs(path) {
// noinspection JSUnresolvedVariable
fs.file(path).parentFile.mkdirs();
}
/**
* 创建文件
* @param file
*/
function create(file) {
var f = fs.file(path);
if (!f.exists()) {
mkdirs(f);
f.createNewFile();
}
}
/**
* 获得文件规范路径
* @param file
* @returns {*}
*/
function path(file) {
// noinspection JSUnresolvedVariable
return fs.file(file).canonicalPath;
}
/**
* 复制文件
* @param inputStream 输入流
* @param target 目标文件
* @param override 是否覆盖
*/
function copy(inputStream, target, override) {
Files.copy(inputStream, target.toPath(), StandardCopyOption[override ? 'REPLACE_EXISTING' : 'ATOMIC_MOVE']);
}
/**
* 读取文件
* @param path 文件路径
*/
function read(path) {
var file = fs.file(path);
if (!file.exists()) {
console.warn('读取文件', file, '错误 文件不存在!');
return;
}
// noinspection JSPrimitiveTypeWrapperUsage
return new java.lang.String(Files.readAllBytes(file.toPath()), "UTF-8");
}
/**
* 保存内容文件
* @param path 路径
* @param content 内容
* @param override 是否覆盖
*/
function save(path, content, override) {
var file = fs.file(path);
if (file.parentFile) {
file.parentFile.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 原始目录
* @param des 目标目录
* @param override 是否覆盖
*/
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.isDirectory()) {
Files.list(file.toPath()).collect(java.util.stream.Collector.toList()).forEach(function(f) {
del(f);
})
}
Files.delete(file.toPath());
}
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;
// noinspection JSUnusedGlobalSymbols
Object.assign(fs, {
concat: concat,
create: create,
mkdirs: mkdirs,
exists: exists,
file: file,
copy: copy,
read: read
});
exports = module.exports = fs;

View File

@ -1,150 +0,0 @@
'use strict';
/**
* HTTP 网络类
* Created by 蒋天蓓 on 2017/2/9 0009.
*/
/*global Java, base, module, exports, require, __FILE__*/
var URL = Java.type("java.net.URL");
var Files = Java.type("java.nio.file.Files");
var Paths = Java.type("java.nio.file.Paths");
var Str = Java.type("java.lang.String");
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) {
}
})], new java.security.SecureRandom());
return sslContext.getSocketFactory();
}();
var config = {
Charset: 'UTF-8',
ConnectTimeout: 10000,
ReadTimeout: 10000,
Debug: false
};
function open(url, method, header) {
// conn.setRequestProperty
var conn = new URL(url).openConnection();
if (conn instanceof HttpsURLConnection) {
conn.setHostnameVerifier(TrustAnyHostnameVerifier);
conn.setSSLSocketFactory(SSLSocketFactory);
}
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(config.ConnectTimeout);
conn.setReadTimeout(config.ReadTimeout);
if (header) {
for (var key in header) {
// noinspection JSUnfilteredForInLoop
conn.setRequestProperty(key, header[key]);
}
}
return conn;
}
function buildUrl(url, params) {
if (params && Object.keys(params).length > 0) {
var queryStart = url.indexOf('?');
if (queryStart === -1) {
url += '?';
}
return url += object2URLSearchParams(params);
}
return url;
}
function request(config) {
var conn = open(buildUrl(config.url, config.query), config.method, config.header);
try {
conn.connect();
var data = config.data;
if (data) {
var out = conn.getOutputStream();
if (typeof data === "object") {
var type = config.header['Content-Type'];
switch (type) {
case "application/x-www-form-urlencoded":
data = object2URLSearchParams(data);
break;
default:
data = JSON.stringify(data)
}
}
out.write(new Str(data).getBytes(config.Charset));
out.flush();
out.close();
}
return response(conn);
} finally {
conn.disconnect();
}
}
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 Str(Files.readAllBytes(temp), config.Charset);
var tempFile = temp.toFile();
tempFile.delete() || tempFile.deleteOnExit();
return result;
}
function object2URLSearchParams(params) {
var temp = [];
for (var key in params) {
temp.push('%s=%s'.format(encodeURIComponent(key), encodeURIComponent(params[key])))
}
return temp.join('&')
}
var http = {
config: config,
request: request
};
['GET', 'DELETE', 'HEAD', 'OPTIONS'].forEach(function(method) {
http[method.toLowerCase()] = function __likeGet__(url, data, config) {
return this.request(Object.assign(config || {}, {
url: url,
method: method,
query: data
}));
}
});
['POST', 'PUT', 'PATCH'].forEach(function(method) {
http[method.toLowerCase()] = function __likePost__(url, data, config) {
return this.request(Object.assign(config || {}, {
url: url,
method: method,
data: data
}));
}
});
exports = module.exports = http;

View File

@ -1,63 +0,0 @@
/*global Java, base, module, exports, require*/
var bukkit = require('api/server');
var nmsChatSerializerClass;
var packetTypeClass;
var nmsChatMessageTypeClass;
var chatMessageTypes;
var String = Java.type('java.lang.String');
var downgrade = false;
function init() {
nmsChatSerializerClass = bukkit.nmsCls(bukkit.nmsVersion.split("_")[1] > 7 ? "IChatBaseComponent$ChatSerializer" : "ChatSerializer");
packetTypeClass = bukkit.nmsCls("PacketPlayOutChat");
var packetTypeConstructor;
Java.from(packetTypeClass.class.constructors).forEach(function(c) {
if (c.parameterTypes.length === 2) {
packetTypeConstructor = c
}
});
nmsChatMessageTypeClass = packetTypeConstructor.parameterTypes[1];
if (nmsChatMessageTypeClass.isEnum()) {
chatMessageTypes = nmsChatMessageTypeClass.getEnumConstants();
} else {
switch (nmsChatMessageTypeClass.name) {
case "int":
nmsChatMessageTypeClass = java.lang.Integer;
break;
case "byte":
nmsChatMessageTypeClass = java.lang.Byte;
break;
}
}
}
function json(sender, json) {
if (downgrade) {
bukkit.console('/tellraw ' + sender.name + ' ' + json)
} else {
send(sender, json, 0);
}
}
function send(sender, json, type) {
sendPacket(sender, new packetTypeClass(nmsChatSerializerClass.a(json), chatMessageTypes == null ? nmsChatMessageTypeClass.valueOf(String.valueOf(type)) : chatMessageTypes[type]))
}
function sendPacket(player, p) {
player.handle.playerConnection.sendPacket(p);
}
try {
init();
} catch (ex) {
console.console("§6[§bbukkit-chat§6] §cNMS Inject Error §4" + ex + " §6Downgrade to Command Mode...")
downgrade = true;
}
exports = module.exports = {
json: json
};

View File

@ -1,97 +0,0 @@
'use strict';
/**
* Bukkit 命令相关类
*/
/*global Java, base, module, exports, require, __FILE__*/
var ref = require('reflect');
var bukkit = require('./server');
var plugin = bukkit.plugin.self;
var commandMap = ref.on(bukkit.plugin.manager).get('commandMap').get();
var PluginCommand = Java.type('org.bukkit.command.PluginCommand');
var Arrays = Java.type('java.util.Arrays');
function enable(jsp) {
var commands = jsp.description.commands;
if (commands) {
var pluginCommands = [];
for (var name in commands) {
// noinspection JSUnfilteredForInLoop
var command = commands[name];
if (typeof command !== 'object') continue;
command.name = name;
// noinspection JSUnfilteredForInLoop
var newCmd = create(jsp, command);
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']);
pluginCommands.push(newCmd);
// noinspection JSUnfilteredForInLoop
console.debug('插件 %s 注册命令 %s ...'.format(jsp.description.name, name));
}
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 删除插件命令
}
}
}
function create(jsp, command) {
var cmd = commandMap.getCommand(command.name)
if (cmd && cmd instanceof PluginCommand) { return cmd };
cmd = ref.on(PluginCommand).create(command.name, plugin).get();
commandMap.register(jsp.description.name, cmd);
return cmd;
}
function onCommand(jsp, c, cmd) {
// 必须指定需要实现的接口类型 否则MOD服会报错
// noinspection JSUnusedGlobalSymbols
c.setExecutor(new org.bukkit.command.CommandExecutor({
onCommand: function(sender, _, command, args) {
try {
return cmd(sender, command, Java.from(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));
console.ex(ex);
}
}
}));
}
function onTabComplete(jsp, c, tab) {
// 必须指定需要实现的接口类型 否则MOD服会报错
// noinspection JSUnusedGlobalSymbols
c.setTabCompleter(new org.bukkit.command.TabCompleter({
onTabComplete: function(sender, _, command, args) {
try {
var token = args[args.length - 1];
var complete = tab(sender, command, Java.from(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));
console.ex(ex);
}
}
}));
}
exports = module.exports = {
enable: enable,
create: create,
onCommand: onCommand,
onTabComplete: onTabComplete,
off: noop
};

View File

@ -1,24 +0,0 @@
/*global Java, base, module, exports, require, __FILE__*/
(function(global) {
global.Console = function BukkitConsole() {
ConsoleDefault.call(this);
this.sender = function() {
var sender = arguments[0];
if (!(sender instanceof org.bukkit.command.CommandSender)) {
this.error("第一个参数未实现 org.bukkit.command.CommandSender 无法发送消息!")
return;
}
if (toString.call(arguments[1]) === "[object Array]") {
arguments[1].forEach(function(line) {
sender.sendMessage(this.prefix + line);
}.bind(this))
} else {
var args = Array.prototype.slice.call(arguments, 1);
sender.sendMessage(this.prefix + args.join(' '));
}
}.bind(this);
this.console = function() {
this.sender(MServer.consoleSender, Array.prototype.join.call(arguments, ' '));
}.bind(this);
};
})(global);

View File

@ -1,50 +0,0 @@
'use strict';
/**
* Sponge 事件相关类
*/
/*global Java, base, module, exports, require, __FILE__*/
var ref = require('reflect');
var Event = Java.type("org.bukkit.event.Event");
var Modifier = Java.type("java.lang.reflect.Modifier");
var Listener = Java.type("org.bukkit.event.Listener");
var EventPriority = Java.type("org.bukkit.event.EventPriority");
var EventExecutor = Java.type("org.bukkit.plugin.EventExecutor");
/**
* 判断是否为一个有效的事件类
* @param clz
* @returns {*|boolean}
*/
function isValidEvent(clz) {
// noinspection JSUnresolvedVariable 继承于 org.bukkit.event.Event
return Event.class.isAssignableFrom(clz) &&
// 访问符为Public
Modifier.isPublic(clz.getModifiers()) &&
// 不是抽象类
!Modifier.isAbstract(clz.getModifiers());
}
function register(eventCls, exec, priority, ignoreCancel) {
var listener = new Listener({});
MServer.getPluginManager().registerEvent(
eventCls,
listener,
EventPriority[priority],
new EventExecutor({
execute: exec
}),
this.plugin,
ignoreCancel);
return listener;
}
function unregister(event, listener) {
ref.on(event).call('getHandlerList').get().unregister(listener);
}
exports = module.exports = {
baseEventDir: 'org/bukkit/event',
isValidEvent: isValidEvent,
register: register,
unregister: unregister
};

File diff suppressed because it is too large Load Diff

View File

@ -1,168 +0,0 @@
'use strict';
/**
* 物品快速生成类
* Created by 蒋天蓓 on 2017/2/9 0009.
*/
/*global Java, base, module, exports, require, __FILE__*/
var Bukkit = MServer;
var ItemStack = Java.type("org.bukkit.inventory.ItemStack");
var Material = Java.type('org.bukkit.Material');
var ItemIDMaterial = require('./item-id-material.json')
var ItemIDRegex = /^[0-9]*$/
/**
* 创建一个物品
* @constructor (ID)
* @constructor (ID,数量)
* @constructor (ID,数量,子ID)
*/
function create() {
var idOrType = type(arguments[0]);
if (!idOrType) {
throw Error('无效的物品ID或枚举 ' + arguments[0] + ' => ' + idOrType)
}
switch (arguments.length) {
case 1:
return new ItemStack(idOrType);
case 2:
return new ItemStack(idOrType, arguments[1]);
case 3:
return new ItemStack(idOrType, arguments[1], arguments[2]);
}
};
/**
* 获得物品枚举(兼容的方式)
*/
function type(idOrType) {
if (arguments.length > 1) {
idOrType = Array.prototype.slice.apply(arguments);
}
var argType = toString.call(idOrType)
switch (argType) {
case "[object Number]":
if (Material['LEGACY_PREFIX']) {
idOrType = Material[Material['LEGACY_PREFIX'] + ItemIDMaterial[idOrType]];
}
break;
case "[object String]":
if (ItemIDRegex.test(idOrType)) {
idOrType = ItemIDMaterial[idOrType];
}
// 尝试获取老版本枚举
idOrType = Material[idOrType] || Material[Material['LEGACY_PREFIX'] + idOrType];
break;
case "[object Array]":
idOrType.some(function(type) {
var temp = item.type(type);
if (temp) {
idOrType = temp;
return true;
}
});
case "[object Undefined]":
case "[object Null]":
return idOrType;
default:
throw Error("Unsupport argument type " + argType + " value " + idOrType)
}
return idOrType;
};
/**
* 创建一个头颅
* @constructor (玩家名称)
*/
function head(name) {
var head = create(397, 1, 3);
var skullMeta = head.itemMeta;
skullMeta.setOwner(name);
head.setItemMeta(skullMeta);
return head;
};
/**
* 给玩家添加物品
* @param player 玩家
* @param items 物品数组
* @param drop 满背包是否掉落
*/
function add(player, items, drop) {
var drops = player.inventory.addItem(items).values();
if (drops.size() !== 0 && drop) {
drops.forEach(function(itemStack) {
drop(player.location, itemStack);
});
}
};
/**
* 指定地点掉落物品
* @param loc 地点
* @param item 物品
*/
function drop(loc, item) {
setTimeout(function() {
loc.world.dropItem(loc, item);
}, 1);
};
/**
* 设置物品名称
* @param item 物品
* @param name
* @returns {*}
*/
function setName(item, name) {
if (item.type && item.type.name() !== "AIR") {
var itemMeta = meta(item);
itemMeta.setDisplayName(name);
item.setItemMeta(itemMeta);
}
return item;
};
/**
* 设置物品Lore
* @param item 物品
* @param lores Lore
* @returns {*} 物品
*/
function setLore(item, lores) {
var argType = toString.call(lores);
switch (argType) {
case "[object String]":
lores = lores.split("\n");
break;
case "[object Array]":
var temp = [];
lores.forEach(function(lore) {
temp.push(lore.split("\n"))
});
lores = temp;
default:
throw Error("Unsupport argument type " + argType + " value " + lores)
}
if (item.type && item.type.name() !== "AIR") {
var itemMeta = meta(item);
itemMeta.setLore(lores);
item.setItemMeta(itemMeta);
}
return item;
};
function meta(item) {
return item.hasItemMeta() ? item.itemMeta : Bukkit.itemFactory.getItemMeta(item.type);
}
module.exports = {
create: create,
type: type,
head: head,
add: add,
drop: drop,
meta: meta,
setName: setName,
setLore: setLore,
setLores: setLore
};

View File

@ -1,53 +0,0 @@
'use strict';
/**
* Bukkit 权限相关类
*/
/*global Java, base, module, exports, require, __FILE__*/
var manager = require('./server').plugin.manager;
/**
* Permission(String name, String description)
*/
var Permission = Java.type("org.bukkit.permissions.Permission");
var PermissionDefault = Java.type('org.bukkit.permissions.PermissionDefault');
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));
}
}
}
function disable(plugin) {
var permissions = plugin.description.permissions;
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));
}
}
}
exports.enable = enable;
exports.disable = disable;

View File

@ -1,164 +0,0 @@
'use strict';
/**
* Bukkit基础操作
* Created by 蒋天蓓 on 2017/2/9 0009.
*/
/*global Java, base, module, exports, require, __FILE__*/
var Bukkit = MServer;
/**
* 获取NMS版本
*/
var nmsVersion = Bukkit.server.class.name.split('.')[3];
/**
* 获取NMS类
*/
function nmsCls(name) {
try {
return Java.type(['net.minecraft.server', nmsVersion, name].join('.'));
} catch (e) {
return base.getClass(['net.minecraft.server', nmsVersion, name].join('.'))
}
};
/**
* 获取OBC类
*/
function obcCls(name) {
try {
return Java.type(['org.bukkit.craftbukkit', nmsVersion, name].join('.'));
} catch (e) {
return base.getClass(['org.bukkit.craftbukkit', nmsVersion, name].join('.'))
}
};
/**
* 插件管理
* @type {{manager: *, get: exports.plugin.get, load: exports.plugin.load}}
*/
var PluginManager = Bukkit.pluginManager;
var plugin = {
/**
* 插件管理工具
*/
manager: PluginManager,
/**
* 获得插件实例
* @param name 插件名称
* @returns {*}
*/
get: function(name) {
return PluginManager.getPlugin(name);
},
/**
* 载入插件 并且返回结果
* @param name 插件名称
* @returns {*}
*/
load: function(name) {
var plugin = this.get(name);
if (ext.notNull(plugin) && !plugin.isEnabled()) {
PluginManager.enablePlugin(plugin);
}
return PluginManager.isPluginEnabled(name);
},
self: PluginManager.getPlugin('MiaoScript')
};
/**
* 服务管理
* @type {{manager: *, get: exports.plugin.get, load: exports.plugin.load}}
*/
var ServicesManager = Bukkit.servicesManager;
var service = {
/**
* 服务管理工具
*/
manager: ServicesManager,
/**
* 获得服务实例
* @param name 插件名称
* @returns {*}
*/
get: function(name) {
var reg = ServicesManager.getRegistration(base.getClass(name));
return reg && reg.provider || null;
}
};
/**
* 获取玩家
*/
function player() {
if (!arguments[0]) { throw TypeError("player name can't be null!") }
switch (arguments.length) {
case 1:
return Bukkit.getPlayer(arguments[0]);
default:
return Bukkit.getPlayerExtra(arguments[0]);
}
};
/**
* 获取在线玩家
*/
function onlinePlayers() {
return Bukkit.onlinePlayers;
};
/**
* 公告
* @param message 消息
*/
function broadcast(message) {
Bukkit.broadcastMessage(message);
};
/**
* 执行名称
* @param player 玩家
* @param command 命令
*/
function command(player, command) {
Bukkit.dispatchCommand(player, command);
};
/**
* 执行控制台命令
* @param command 命令
*/
function console(command) {
command(Bukkit.consoleSender, command);
};
/**
* 玩家以OP权限执行命令
* @param player
* @param command
*/
function opcommand(player, command) {
var origin = player.isOp();
player.setOp(true);
try {
command(player, command);
} finally {
player.setOp(origin);
}
};
/**
* 关闭引擎时执行的操作
*/
function shutdown() {
Bukkit.scheduler.cancelTasks(plugin.self);
Bukkit.servicesManager.unregisterAll(plugin.self);
org.bukkit.event.HandlerList.unregisterAll(plugin.self);
Bukkit.messenger.unregisterIncomingPluginChannel(plugin.self);
Bukkit.messenger.unregisterOutgoingPluginChannel(plugin.self);
}
exports = module.exports = {
$: Bukkit,
nmsVersion: nmsVersion,
nmsCls: nmsCls,
obcCls: obcCls,
plugin: plugin,
service: service,
player: player,
onlinePlayers: onlinePlayers,
broadcast: broadcast,
command: command,
console: console,
opcommand: opcommand,
shutdown: shutdown
}

View File

@ -1,92 +0,0 @@
'use strict';
/*global Java, base, module, exports, require, __FILE__*/
/**
* 任务计划
* Created by 蒋天蓓 on 2017/2/9 0009.
*/
var plugin = require('./server').plugin.self;
var BukkitRunnable = Java.type("org.bukkit.scheduler.BukkitRunnable");
/**
* 创建任务对象
* @param func 任务
*/
function create(func) {
if (toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
return new BukkitRunnable(function() {
try {
func();
} catch (ex) {
console.console('§4插件执行任务时发生错误', ex)
console.ex(ex);
}
});
};
/**
* 运行任务
* @param func 任务
*/
function run(func) {
return create(func).runTask(plugin);
};
/**
* 延时运行任务
* @param func 任务
* @param time 延时时间
*/
function later(func, time) {
return create(func).runTaskLater(plugin, time);
};
/**
* 运行循环任务
* @constructor (任务,执行间隔).
* @constructor (任务,首次延时,执行间隔)
*/
function timer() {
switch (arguments.length) {
case 2:
return create(arguments[0]).runTaskTimer(plugin, 0, arguments[1]);
case 3:
return create(arguments[0]).runTaskTimer(plugin, arguments[1], arguments[2]);
default:
throw TypeError('参数错误 task.timer(func, [delay], interval)');
}
};
/**
* 运行异步任务
* @param func function 任务
*/
function _async(func) {
return create(func).runTaskAsynchronously(plugin);
};
/**
* 延时运行异步任务
* @param func 任务
* @param time 延时时间
*/
function laterAsync(func, time) {
return create(func).runTaskLaterAsynchronously(plugin, time);
};
/**
* 运行异步循环任务
* @constructor (任务,执行间隔).
* @constructor (任务,首次延时,执行间隔)
*/
function timerAsync() {
switch (arguments.length) {
case 2:
return create(arguments[0]).runTaskTimerAsynchronously(plugin, 0, arguments[1]);
case 3:
return create(arguments[0]).runTaskTimerAsynchronously(plugin, arguments[1], arguments[2]);
default:
throw TypeError('参数错误 task.timerAsync(func, [delay], interval)');
}
};
exports = module.exports = {
run: run,
later: later,
timer: timer,
async: _async,
laterAsync: laterAsync,
timerAsync: timerAsync
}

View File

@ -1,18 +0,0 @@
/**
* Bukkit 玩家方法代理类
* Created by 蒋天蓓 on 2018/1/5 0009.
*/
/*global Java, base, module, exports, require*/
var ref = require('reflect');
var Player = {
createNew: function createNew(inner) {
var player = {};
player.handler = inner;
player.sendMessage = function (msg) {
this.handler.sendMessage(msg);
};
return Object.assign(ref.mapToObject(inner), player);
}
};
exports.$ = Player.createNew;

View File

@ -1,9 +0,0 @@
/*global Java, base, module, exports, require*/
var TextSerializers = Java.type('org.spongepowered.api.text.serializer.TextSerializers');
function json(sender, json) {
sender.sendMessage(TextSerializers.JSON.deserialize(json));
}
exports = module.exports = {
json: json
};

View File

@ -1,121 +0,0 @@
'use strict';
/**
* Sponge 命令相关类
*/
/*global Java, base, module, exports, require, __FILE__*/
var Sponge = MServer;
var server = require('./server');
var plugin = server.plugin.self;
var CommandCallable = Java.type('org.spongepowered.api.command.CommandCallable');
var CommandResult = Java.type('org.spongepowered.api.command.CommandResult');
var Text = Java.type('org.spongepowered.api.text.Text');
var Optional = Java.type('java.util.Optional');
var ArrayList = Java.type('java.util.ArrayList');
var Arrays = Java.type('java.util.Arrays');
var commandMap = [];
var SimpleCommandCallable = function (command) {
var that = this;
this.name = command.name;
this.cmd = noop;
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) {
return that.cmd(src, that.name, args.length === 0 ? [] : args.split(" ").filter(function (e) { return e; })) ? CommandResult.success() : CommandResult.empty();
},
//List<String> getSuggestions(CommandSource source, String arguments, @Nullable Location<World> targetPosition) throws CommandException;
getSuggestions: function (src, args, target) {
return that.tab(src, that.name, args.length === 0 ? [] : args.split(" ").filter(function (e) { return e; }));
},
//boolean testPermission(CommandSource source);
testPermission: function () {
return true;
},
//Optional<Text> getShortDescription(CommandSource source);
getShortDescription: function () {
return Optional.of(Text.of(command.description || '暂无描述!'));
},
//Optional<Text> getHelp(CommandSource source);
getHelp: function () {
return Optional.of(Text.of(""));
},
//Text getUsage(CommandSource source);
getUsage: function () {
return Text.of('');
}
});
this.setExecutor = function (exec) {
that.cmd = exec;
};
this.setTabCompleter = function (exec) {
that.tab = exec;
}
};
function enable(jsp) {
// noinspection JSUnusedLocalSymbols
var plugin = jsp.description.name;
var commands = jsp.description.commands;
if (commands) {
// noinspection JSUnusedLocalSymbols
var pluginCommands = [];
for (var name in commands) {
var command = commands[name];
if (typeof command !== 'object') continue;
command.name = name;
create(jsp, command);
console.debug('插件 %s 注册命令 %s ...'.format(jsp.description.name, name));
}
}
}
function create(jsp, command) {
var commandKey = jsp.description.name.toLowerCase() + ":" + command.name;
if (!commandMap[commandKey]) {
commandMap[commandKey] = new SimpleCommandCallable(command);
Sponge.getCommandManager().register(plugin, commandMap[commandKey].callable, command.name, commandKey);
}
return commandMap[commandKey];
}
function onCommand(jsp, c, cmd) {
c.setExecutor(function execCmd(sender, command, args) {
try {
return 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(' ')));
console.ex(ex);
}
});
}
function onTabComplete(jsp, c, tab) {
c.setTabCompleter(function execTab(sender, command, args) {
try {
var token = args[args.length - 1];
var complete = 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(' ')));
console.ex(ex);
}
});
}
exports = module.exports = {
enable: enable,
create: create,
onCommand: onCommand,
onTabComplete: onTabComplete,
off: noop
};

View File

@ -1,29 +0,0 @@
/*global Java, base, module, exports, require, __FILE__*/
(function(global) {
global.Console = function SpongeConsole() {
ConsoleDefault.call(this);
this.sender = function() {
var Text = Java.type("org.spongepowered.api.text.Text");
var sender = arguments[0];
if (!(sender instanceof org.spongepowered.api.command.CommandSource)) {
this.error("第一个参数未实现 org.spongepowered.api.command.CommandSource 无法发送消息!")
return
}
if (toString.call(arguments[1]) === "[object Array]") {
arguments[1].forEach(function(line) {
sender.sendMessage(Text.of(this.prefix + line));
}.bind(this))
} else {
var args = Array.prototype.slice.call(arguments, 1);
sender.sendMessage(Text.of(this.prefix + args.join(' ')));
}
};
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, ' '));
};
};
})(global);

View File

@ -1,57 +0,0 @@
'use strict';
/**
* Sponge 事件相关类
*/
/*global Java, base, module, exports, require, __FILE__*/
var Modifier = Java.type("java.lang.reflect.Modifier");
var Order = Java.type("org.spongepowered.api.event.Order");
var Event = Java.type("org.spongepowered.api.event.Event");
var EventListener = Java.type("org.spongepowered.api.event.EventListener");
var priorityMap = {
'LOWEST': 'PRE',
'LOW': 'FIRST',
'NORMAL': 'DEFAULT',
'HIGH': 'LATE',
'HIGHEST': 'LAST',
'MONITOR': 'POST'
};
/**
* 判断是否为一个有效的事件类
* @param clz
* @returns {*|boolean}
*/
function isValidEvent(clz) {
// noinspection JSUnresolvedVariable 继承于 org.spongepowered.api.event.Event
return Event.class.isAssignableFrom(clz) &&
// 访问符为Public
Modifier.isPublic(clz.getModifiers()) &&
// Sponge的事件都是接口
Modifier.isAbstract(clz.getModifiers());
}
function class2Name(clazz) {
return clazz.canonicalName.substring(clazz.name.lastIndexOf(".") + 1);
}
function register(eventCls, exec, priority, ignoreCancel) {
var listener = new EventListener({
handle: exec
});
MServer.getEventManager().registerListener(this.plugin, eventCls, Order[priorityMap[priority]], listener);
return listener;
}
function unregister(event, listener) {
MServer.getEventManager().unregisterListeners(listener);
}
// noinspection JSUnusedGlobalSymbols
exports = module.exports = {
baseEventDir: 'org/spongepowered/api/event',
isValidEvent: isValidEvent,
class2Name: class2Name,
register: register,
unregister: unregister
};

View File

@ -1,131 +0,0 @@
'use strict';
/**
* Sponge基础操作
* Created by 蒋天蓓 on 2017/10/27 0009.
*/
/*global Java, base, module, exports, require, __FILE__*/
var Text = Java.type('org.spongepowered.api.text.Text');
var Sponge = MServer;
var Server = MServer.server;
/**
* 插件管理
* @type {{manager: *, get: exports.plugin.get, load: exports.plugin.load}}
*/
var PluginManager = Sponge.pluginManager;
var plugin = {
/**
* 插件管理工具
*/
manager: PluginManager,
/**
* 获得插件实例
* @param name 插件名称
* @returns {*}
*/
get: function (name) {
return PluginManager.getPlugin(name).orElse(null);
},
/**
* 载入插件 并且返回结果
* @param name 插件名称
* @returns {*}
*/
load: function (name) {
return PluginManager.isLoaded(name);
},
self: PluginManager.getPlugin('miaoscript').orElse(null)
};
/**
* 服务管理
* @type {{manager: *, get: exports.plugin.get, load: exports.plugin.load}}
*/
var ServicesManager = Sponge.serviceManager;
var service = {
/*
* 服务管理工具
*/
manager: ServicesManager,
/**
* 获得服务实例
* @param name 插件名称
* @returns {*}
*/
get: function (name) {
return ServicesManager.provide(base.getClass(name)).orElse(null);
}
};
/**
* 获取玩家
*/
function player() {
if (!arguments[0]) { throw TypeError("player name can't be null!") }
return Server.getPlayer(arguments[0]).orElse(null);
};
/**
* 获取在线玩家
*/
function onlinePlayers() {
return Server.onlinePlayers;
};
/**
* 公告
* @param message 消息
*/
function broadcast(message) {
Server.getBroadcastChannel().send(Text.of(message));
};
/**
* 执行名称
* @param player 玩家
* @param command 命令
*/
function command(player, command) {
Sponge.commandManager.process(player, command)
};
/**
* 执行控制台命令
* @param command 命令
*/
function console(command) {
command(Server.console, command);
};
/**
* 玩家以OP权限执行命令
* @param player
* @param command
*/
function opcommand(player, command) {
var origin = player.isOp();
player.setOp(true);
try {
command(player, command);
} finally {
player.setOp(origin);
}
};
/**
* 关闭引擎时执行的操作
*/
function shutdown() {
Sponge.eventManager.unregisterPluginListeners(plugin.self);
Sponge.scheduler.getScheduledTasks(plugin.self).forEach(function (task) {
task.cancel();
});
Sponge.commandManager.getOwnedBy(plugin.self).forEach(function (commandMapping) {
Sponge.commandManager.removeMapping(commandMapping);
});
}
exports = module.exports = {
$: Sponge,
plugin: plugin,
service: service,
player: player,
onlinePlayers: onlinePlayers,
broadcast: broadcast,
command: command,
console: console,
opcommand: opcommand,
shutdown: shutdown
}

View File

@ -1,93 +0,0 @@
'use strict';
/*global Java, base, module, exports, require, __FILE__*/
/**
* 任务计划
* Created by 蒋天蓓 on 2017/2/9 0009.
*/
var plugin = require('./server').plugin.self;
var Consumer = Java.type('java.util.function.Consumer');
var Task = Java.type("org.spongepowered.api.scheduler.Task");
/**
* 创建任务对象
* @param func 任务
*/
function create(func) {
if (toString.call(func) !== "[object Function]") { throw TypeError('第一个参数 Task 必须为 function !'); };
return Task.builder().execute(new Consumer(function() {
try {
func();
} catch (ex) {
console.console('§4插件执行任务时发生错误', ex)
console.ex(ex);
}
}));
};
/**
* 运行任务
* @param func 任务
*/
function run(func) {
return create(func).submit(plugin);
};
/**
* 延时运行任务
* @param func 任务
* @param time 延时时间
*/
function later(func, time) {
return create(func).delayTicks(time).submit(plugin);
};
/**
* 运行循环任务
* @constructor (任务,执行间隔).
* @constructor (任务,首次延时,执行间隔)
*/
function timer() {
switch (arguments.length) {
case 2:
return create(arguments[0]).intervalTicks(arguments[1]).submit(plugin);
case 3:
return create(arguments[0]).delayTicks(arguments[1]).intervalTicks(arguments[2]).submit(plugin);
default:
throw TypeError('参数错误 task.timer(func, [delay], interval)');
}
};
/**
* 运行异步任务
* @param func function 任务
*/
function _async(func) {
return create(func).async().submit(plugin);
};
/**
* 延时运行异步任务
* @param func 任务
* @param time 延时时间
*/
function laterAsync(func, time) {
return create(func).async().delayTicks(time).submit(plugin);
};
/**
* 运行异步循环任务
* @constructor (任务,执行间隔).
* @constructor (任务,首次延时,执行间隔)
*/
function timerAsync() {
switch (arguments.length) {
case 2:
return create(arguments[0]).async().intervalTicks(arguments[1]).submit(plugin);
case 3:
return create(arguments[0]).async().delayTicks(arguments[1]).intervalTicks(arguments[2]).submit(plugin);
default:
throw TypeError('参数错误 task.timerAsync(func, [delay], interval)');
}
};
exports = module.exports = {
run: run,
later: later,
timer: timer,
async: _async,
laterAsync: laterAsync,
timerAsync: timerAsync
}

View File

@ -1,19 +0,0 @@
/**
* Sponge 玩家方法代理类
* Created by 蒋天蓓 on 2018/1/5 0009.
*/
/*global Java, base, module, exports, require*/
var ref = require('reflect');
var Text = Java.type('org.spongepowered.api.text.Text');
var Player = {
createNew: function createNew(inner) {
var player = {};
player.handler = inner;
player.sendMessage = function (msg) {
this.handler.sendMessage(Text.of(msg));
};
return Object.assign(ref.mapToObject(inner), player);
}
};
exports.$ = Player.createNew;

View File

@ -1,53 +0,0 @@
'use strict';
/**
* PAPI扩展类
*/
/*global Java, base, module, exports, require, __FILE__*/
var PlaceholderAPI;
var server = require('api/server');
PlaceholderAPI = {
setPlaceholders: function() {
return arguments[1].replace(/&([0-9a-fk-orA-FK-OR])/, '§$1');
}
};
// 尝试加载 Bukkit 的 PlaceholderAPI
try {
PlaceholderAPI = base.getClass("me.clip.placeholderapi.PlaceholderAPI").static;
console.log('[PAPI] Found Bukkit PlaceholderAPI Hooking...')
} catch (ex) {
}
// 尝试加载 Sponge 的 PlaceholderAPI
try {
var spongePapi = server.service.get('me.rojo8399.placeholderapi.PlaceholderService');
var TextSerializers = Java.type('org.spongepowered.api.text.serializer.TextSerializers');
var s = TextSerializers.formattingCode('§');
if (spongePapi) {
PlaceholderAPI = {
setPlaceholders: function() {
return s.serialize(spongePapi.replacePlaceholders(arguments[1], arguments[0], arguments[0]));
}
};
console.log('[PAPI] Found Sponge PlaceholderAPI Hooking...')
}
} catch (ex) {
}
function replace() {
var player = arguments[0];
var line = arguments[1];
if (arguments.length === 1) {
player = null;
line = player;
}
if (toString.call(line) === "[object Array]") {
return PlaceholderAPI.setPlaceholders(player, line.join('\n')).split('\n');
}
return PlaceholderAPI.setPlaceholders(player, line);
}
exports = module.exports = {
$: replace
};

View File

@ -1,204 +0,0 @@
'use strict';
/**
* 反射工具类
* Created by 蒋天蓓 on 2017/2/9 0009.
*/
/*global Java, base, module, exports, require, __FILE__*/
var Class = Java.type('java.lang.Class');
var NoSuchFieldException = Java.type('java.lang.NoSuchFieldException');
var methodCache = [];
function Reflect(obj) {
if (obj instanceof Class) {
this.obj = null;
this.class = obj;
} else {
this.obj = obj;
this.class = obj.class;
}
this.method = function(name) {
var name = arguments[0];
var params = Array.prototype.slice.call(arguments, 1);
return declaredMethod(this.class, name, types(params));
}
this.methods = function() {
return Java.from(declaredMethods(this.class));
}
this.field = function(name) {
try {
// Try getting a public field
var field = this.class.field(name);
return on(field.get(this.obj));
} catch (ex) {
// Try again, getting a non-public field
try {
return on(accessible(declaredField(this.class, name)).get(this.obj));
} catch (ex) {
throw new NoSuchFieldException(ex);
}
}
};
this.fields = function(declared) {
return Java.from(declared ? this.class.declaredFields : this.class.fields);
}
this.values = function(declared) {
var cache = {};
var feds = declared ? this.class.declaredFields : this.class.fields;
Java.from(feds).forEach(function(fed) {
cache[fed.name] = this.field(fed.name).get();
}.bind(this))
return cache;
}
this.call = function() {
var name = arguments[0];
var params = Array.prototype.slice.call(arguments, 1);
var method = declaredMethod(this.class, name, types(params));
return on(method.invoke(this.get(), params));
};
this.get = function() {
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;
};
this.create = function() {
var param = Array.prototype.slice.call(arguments);
return on(declaredConstructor(this.class, param).newInstance(param));
};
}
/**
* Get an array of types for an array of objects
*/
function types(values, def) {
if (values === null) {
return [];
}
var result = [];
values.forEach(function(t) {
result.push((t || def) ? Object.class : t instanceof Class ? t : t.class)
});
return result;
}
function accessible(accessible) {
if (accessible === null) {
return null;
}
if (!accessible.isAccessible()) {
accessible.setAccessible(true);
}
return accessible;
}
function declaredConstructor(clazz, param) {
var constructor;
try {
constructor = clazz.getDeclaredConstructor(types(param));
} catch (ex) {
try {
constructor = clazz.getDeclaredConstructor(types(param, true));
} catch (ex) {
constructor = clazz.getDeclaredConstructors()[0];
}
}
return accessible(constructor);
}
function declaredField(clazz, name) {
var field = null;
// noinspection JSUnresolvedVariable
while (clazz !== java.lang.Object.class) {
try {
field = clazz.getDeclaredField(name);
if (field !== null) {
break;
}
} catch (e) {
clazz = clazz.getSuperclass();
}
}
if (field === null) {
throw new NoSuchFieldException(name + " is not found in " + clazz.name);
}
return field;
}
function declaredMethod(clazz, name, clazzs) {
var key = clazz.name + '.' + name + ':' + (clazzs || []).join(':');
if (!methodCache[key]) {
try {
methodCache[key] = clazz.getMethod(name, clazzs);
} catch (ex) {
methodCache[key] = clazz.getDeclaredMethod(name, clazzs);
}
}
return methodCache[key];
}
function declaredMethods(clazz) {
return clazz.declaredMethods;
}
var classMethodsCache = [];
function mapToObject(javaObj) {
if (!javaObj || !javaObj.class) {
throw new TypeError('参数 %s 不是一个Java对象!'.format(javaObj))
}
var target = {};
getJavaObjectMethods(javaObj).forEach(function proxyMethod(t) {
mapMethod(target, javaObj, t)
});
return target;
}
function getJavaObjectMethods(javaObj) {
var className = javaObj.class.name;
if (!classMethodsCache[className]) {
var names = [];
var methods = javaObj.class.methods;
for (var i in methods) {
names.push(methods[i].name);
}
classMethodsCache[className] = names;
}
return classMethodsCache[className];
}
function mapMethod(target, source, name) {
target[name] = function __SimpleDynamicMethod__() {
if (arguments.length > 0) {
return source[name](Array.prototype.slice.call(arguments));
} else {
return source[name]();
}
};
}
function on(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

@ -1,131 +0,0 @@
/*global Java, base, module, exports, require*/
var chat = require('api/chat');
var server = require('api/server');
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 = {};
if (this.text) {
str.text = this.text;
}
if (this.clickEventAction) {
str.clickEvent = {
"action": this.clickEventAction,
"value": this.clickEventValue
}
}
if (this.hoverEventAction) {
str.hoverEvent = {
"action": this.hoverEventAction,
"value": this.hoverEventValue
}
}
if (this.insertion) {
str.insertion = this.insertion;
}
return str;
}
};
var Tellraw = function() {
var parts = [new ChatMessagePart()];
var self = this;
this.then = function(part) {
if (typeof part === "string") {
var newPart = new ChatMessagePart();
newPart.text = part;
this.then(newPart);
return self;
}
var last = this.latest();
if (!last.text) {
last.text = part.text;
} else {
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]") {
str = str.join("\n");
}
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 = '§卐';
exports = module.exports = Tellraw;

View File

@ -1,29 +0,0 @@
function Template(tpl) {
var match;
var code = ['var r=[];'];
var re = /\{\{\s*([a-zA-Z\.\_0-9()]+)\s*\}\}/m;
function addLine(text) {
code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
};
while (match = re.exec(tpl)) {
if (match.index > 0) {
addLine(tpl.slice(0, match.index));
}
code.push('r.push(this.' + match[1] + ');');
tpl = tpl.substring(match.index + match[0].length);
}
addLine(tpl);
code.push('return r.join(\'\');');
// 创建函数:
var fn = new Function(code.join('\n'));
// 用render()调用函数并绑定this参数
this.render = function(model) {
return fn.apply(model);
};
}
exports = module.exports = {
create: function(tpl) {
return new Template(tpl);
}
}

View File

@ -1,35 +0,0 @@
'use strict';
/**
* 常用工具类
* Created by 蒋天蓓 on 2018/5/12 0009.
*/
/*global Java, base, module, exports, require, __FILE__*/
var Arrays = Java.type('java.util.Arrays');
function toStr(obj) {
if (obj.class) {
return Arrays.toString()
}
}
function compare(prop) {
return function(obj1, obj2) {
var val1 = obj1[prop];
var val2 = obj2[prop];
if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
val1 = Number(val1);
val2 = Number(val2);
}
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
}
exports = module.exports = {
compare: compare
};

View File

@ -1,39 +0,0 @@
'use strict';
var loader = require('./js-yaml/loader');
var dumper = require('./js-yaml/dumper');
function deprecated(name) {
return function () {
throw new Error('Function ' + name + ' is deprecated and cannot be used.');
};
}
module.exports.Type = require('./js-yaml/type');
module.exports.Schema = require('./js-yaml/schema');
module.exports.FAILSAFE_SCHEMA = require('./js-yaml/schema/failsafe');
module.exports.JSON_SCHEMA = require('./js-yaml/schema/json');
module.exports.CORE_SCHEMA = require('./js-yaml/schema/core');
module.exports.DEFAULT_SAFE_SCHEMA = require('./js-yaml/schema/default_safe');
module.exports.DEFAULT_FULL_SCHEMA = require('./js-yaml/schema/default_full');
module.exports.load = loader.load;
module.exports.loadAll = loader.loadAll;
module.exports.safeLoad = loader.safeLoad;
module.exports.safeLoadAll = loader.safeLoadAll;
module.exports.dump = dumper.dump;
module.exports.safeDump = dumper.safeDump;
module.exports.YAMLException = require('./js-yaml/exception');
// Deprecated schema names from JS-YAML 2.0.x
module.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/failsafe');
module.exports.SAFE_SCHEMA = require('./js-yaml/schema/default_safe');
module.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default_full');
// Deprecated functions from JS-YAML 1.x.x
module.exports.scan = deprecated('scan');
module.exports.parse = deprecated('parse');
module.exports.compose = deprecated('compose');
module.exports.addConstructor = deprecated('addConstructor');

View File

@ -1,59 +0,0 @@
'use strict';
function isNothing(subject) {
return (typeof subject === 'undefined') || (subject === null);
}
function isObject(subject) {
return (typeof subject === 'object') && (subject !== null);
}
function toArray(sequence) {
if (Array.isArray(sequence)) return sequence;
else if (isNothing(sequence)) return [];
return [ sequence ];
}
function extend(target, source) {
var index, length, key, sourceKeys;
if (source) {
sourceKeys = Object.keys(source);
for (index = 0, length = sourceKeys.length; index < length; index += 1) {
key = sourceKeys[index];
target[key] = source[key];
}
}
return target;
}
function repeat(string, count) {
var result = '', cycle;
for (cycle = 0; cycle < count; cycle += 1) {
result += string;
}
return result;
}
function isNegativeZero(number) {
return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
}
module.exports.isNothing = isNothing;
module.exports.isObject = isObject;
module.exports.toArray = toArray;
module.exports.repeat = repeat;
module.exports.isNegativeZero = isNegativeZero;
module.exports.extend = extend;

View File

@ -1,819 +0,0 @@
'use strict';
/*eslint-disable no-use-before-define*/
var common = require('./common');
var YAMLException = require('./exception');
var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
var _toString = Object.prototype.toString;
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var CHAR_TAB = 0x09; /* Tab */
var CHAR_LINE_FEED = 0x0A; /* LF */
var CHAR_SPACE = 0x20; /* Space */
var CHAR_EXCLAMATION = 0x21; /* ! */
var CHAR_DOUBLE_QUOTE = 0x22; /* " */
var CHAR_SHARP = 0x23; /* # */
var CHAR_PERCENT = 0x25; /* % */
var CHAR_AMPERSAND = 0x26; /* & */
var CHAR_SINGLE_QUOTE = 0x27; /* ' */
var CHAR_ASTERISK = 0x2A; /* * */
var CHAR_COMMA = 0x2C; /* , */
var CHAR_MINUS = 0x2D; /* - */
var CHAR_COLON = 0x3A; /* : */
var CHAR_GREATER_THAN = 0x3E; /* > */
var CHAR_QUESTION = 0x3F; /* ? */
var CHAR_COMMERCIAL_AT = 0x40; /* @ */
var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
var CHAR_GRAVE_ACCENT = 0x60; /* ` */
var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
var CHAR_VERTICAL_LINE = 0x7C; /* | */
var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
var ESCAPE_SEQUENCES = {};
ESCAPE_SEQUENCES[0x00] = '\\0';
ESCAPE_SEQUENCES[0x07] = '\\a';
ESCAPE_SEQUENCES[0x08] = '\\b';
ESCAPE_SEQUENCES[0x09] = '\\t';
ESCAPE_SEQUENCES[0x0A] = '\\n';
ESCAPE_SEQUENCES[0x0B] = '\\v';
ESCAPE_SEQUENCES[0x0C] = '\\f';
ESCAPE_SEQUENCES[0x0D] = '\\r';
ESCAPE_SEQUENCES[0x1B] = '\\e';
ESCAPE_SEQUENCES[0x22] = '\\"';
ESCAPE_SEQUENCES[0x5C] = '\\\\';
ESCAPE_SEQUENCES[0x85] = '\\N';
ESCAPE_SEQUENCES[0xA0] = '\\_';
ESCAPE_SEQUENCES[0x2028] = '\\L';
ESCAPE_SEQUENCES[0x2029] = '\\P';
var DEPRECATED_BOOLEANS_SYNTAX = [
'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
];
function compileStyleMap(schema, map) {
var result, keys, index, length, tag, style, type;
if (map === null) return {};
result = {};
keys = Object.keys(map);
for (index = 0, length = keys.length; index < length; index += 1) {
tag = keys[index];
style = String(map[tag]);
if (tag.slice(0, 2) === '!!') {
tag = 'tag:yaml.org,2002:' + tag.slice(2);
}
type = schema.compiledTypeMap['fallback'][tag];
if (type && _hasOwnProperty.call(type.styleAliases, style)) {
style = type.styleAliases[style];
}
result[tag] = style;
}
return result;
}
function encodeHex(character) {
var string, handle, length;
string = character.toString(16).toUpperCase();
if (character <= 0xFF) {
handle = 'x';
length = 2;
} else if (character <= 0xFFFF) {
handle = 'u';
length = 4;
} else if (character <= 0xFFFFFFFF) {
handle = 'U';
length = 8;
} else {
throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
}
return '\\' + handle + common.repeat('0', length - string.length) + string;
}
function State(options) {
this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
this.indent = Math.max(1, (options['indent'] || 2));
this.skipInvalid = options['skipInvalid'] || false;
this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
this.sortKeys = options['sortKeys'] || false;
this.lineWidth = options['lineWidth'] || 80;
this.noRefs = options['noRefs'] || false;
this.noCompatMode = options['noCompatMode'] || false;
this.condenseFlow = options['condenseFlow'] || false;
this.implicitTypes = this.schema.compiledImplicit;
this.explicitTypes = this.schema.compiledExplicit;
this.tag = null;
this.result = '';
this.duplicates = [];
this.usedDuplicates = null;
}
// Indents every line in a string. Empty lines (\n only) are not indented.
function indentString(string, spaces) {
var ind = common.repeat(' ', spaces),
position = 0,
next = -1,
result = '',
line,
length = string.length;
while (position < length) {
next = string.indexOf('\n', position);
if (next === -1) {
line = string.slice(position);
position = length;
} else {
line = string.slice(position, next + 1);
position = next + 1;
}
if (line.length && line !== '\n') result += ind;
result += line;
}
return result;
}
function generateNextLine(state, level) {
return '\n' + common.repeat(' ', state.indent * level);
}
function testImplicitResolving(state, str) {
var index, length, type;
for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
type = state.implicitTypes[index];
if (type.resolve(str)) {
return true;
}
}
return false;
}
// [33] s-white ::= s-space | s-tab
function isWhitespace(c) {
return c === CHAR_SPACE || c === CHAR_TAB;
}
// Returns true if the character can be printed without escaping.
// From YAML 1.2: "any allowed characters known to be non-printable
// should also be escaped. [However,] This isnt mandatory"
// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
function isPrintable(c) {
return (0x00020 <= c && c <= 0x00007E)
|| ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
|| ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)
|| (0x10000 <= c && c <= 0x10FFFF);
}
// Simplified test for values allowed after the first character in plain style.
function isPlainSafe(c) {
// Uses a subset of nb-char - c-flow-indicator - ":" - "#"
// where nb-char ::= c-printable - b-char - c-byte-order-mark.
return isPrintable(c) && c !== 0xFEFF
// - c-flow-indicator
&& c !== CHAR_COMMA
&& c !== CHAR_LEFT_SQUARE_BRACKET
&& c !== CHAR_RIGHT_SQUARE_BRACKET
&& c !== CHAR_LEFT_CURLY_BRACKET
&& c !== CHAR_RIGHT_CURLY_BRACKET
// - ":" - "#"
&& c !== CHAR_COLON
&& c !== CHAR_SHARP;
}
// Simplified test for values allowed as the first character in plain style.
function isPlainSafeFirst(c) {
// Uses a subset of ns-char - c-indicator
// where ns-char = nb-char - s-white.
return isPrintable(c) && c !== 0xFEFF
&& !isWhitespace(c) // - s-white
// - (c-indicator ::=
// “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
&& c !== CHAR_MINUS
&& c !== CHAR_QUESTION
&& c !== CHAR_COLON
&& c !== CHAR_COMMA
&& c !== CHAR_LEFT_SQUARE_BRACKET
&& c !== CHAR_RIGHT_SQUARE_BRACKET
&& c !== CHAR_LEFT_CURLY_BRACKET
&& c !== CHAR_RIGHT_CURLY_BRACKET
// | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"”
&& c !== CHAR_SHARP
&& c !== CHAR_AMPERSAND
&& c !== CHAR_ASTERISK
&& c !== CHAR_EXCLAMATION
&& c !== CHAR_VERTICAL_LINE
&& c !== CHAR_GREATER_THAN
&& c !== CHAR_SINGLE_QUOTE
&& c !== CHAR_DOUBLE_QUOTE
// | “%” | “@” | “`”)
&& c !== CHAR_PERCENT
&& c !== CHAR_COMMERCIAL_AT
&& c !== CHAR_GRAVE_ACCENT;
}
var STYLE_PLAIN = 1,
STYLE_SINGLE = 2,
STYLE_LITERAL = 3,
STYLE_FOLDED = 4,
STYLE_DOUBLE = 5;
// Determines which scalar styles are possible and returns the preferred style.
// lineWidth = -1 => no limit.
// Pre-conditions: str.length > 0.
// Post-conditions:
// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
var i;
var char;
var hasLineBreak = false;
var hasFoldableLine = false; // only checked if shouldTrackWidth
var shouldTrackWidth = lineWidth !== -1;
var previousLineBreak = -1; // count the first line correctly
var plain = isPlainSafeFirst(string.charCodeAt(0))
&& !isWhitespace(string.charCodeAt(string.length - 1));
if (singleLineOnly) {
// Case: no block styles.
// Check for disallowed characters to rule out plain and single.
for (i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain = plain && isPlainSafe(char);
}
} else {
// Case: block styles permitted.
for (i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (char === CHAR_LINE_FEED) {
hasLineBreak = true;
// Check if any line can be folded.
if (shouldTrackWidth) {
hasFoldableLine = hasFoldableLine ||
// Foldable line = too long, and not more-indented.
(i - previousLineBreak - 1 > lineWidth &&
string[previousLineBreak + 1] !== ' ');
previousLineBreak = i;
}
} else if (!isPrintable(char)) {
return STYLE_DOUBLE;
}
plain = plain && isPlainSafe(char);
}
// in case the end is missing a \n
hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
(i - previousLineBreak - 1 > lineWidth &&
string[previousLineBreak + 1] !== ' '));
}
// Although every style can represent \n without escaping, prefer block styles
// for multiline, since they're more readable and they don't add empty lines.
// Also prefer folding a super-long line.
if (!hasLineBreak && !hasFoldableLine) {
// Strings interpretable as another type have to be quoted;
// e.g. the string 'true' vs. the boolean true.
return plain && !testAmbiguousType(string)
? STYLE_PLAIN : STYLE_SINGLE;
}
// Edge case: block indentation indicator can only have one digit.
if (string[0] === ' ' && indentPerLevel > 9) {
return STYLE_DOUBLE;
}
// At this point we know block styles are valid.
// Prefer literal style unless we want to fold.
return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
}
// Note: line breaking/folding is implemented for only the folded style.
// NB. We drop the last trailing newline (if any) of a returned block scalar
// since the dumper adds its own newline. This always works:
// • No ending newline => unaffected; already using strip "-" chomping.
// • Ending newline => removed then restored.
// Importantly, this keeps the "+" chomp indicator from gaining an extra line.
function writeScalar(state, string, level, iskey) {
state.dump = (function () {
if (string.length === 0) {
return "''";
}
if (!state.noCompatMode &&
DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
return "'" + string + "'";
}
var indent = state.indent * Math.max(1, level); // no 0-indent scalars
// As indentation gets deeper, let the width decrease monotonically
// to the lower bound min(state.lineWidth, 40).
// Note that this implies
// state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
// state.lineWidth > 40 + state.indent: width decreases until the lower bound.
// This behaves better than a constant minimum width which disallows narrower options,
// or an indent threshold which causes the width to suddenly increase.
var lineWidth = state.lineWidth === -1
? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
// Without knowing if keys are implicit/explicit, assume implicit for safety.
var singleLineOnly = iskey
// No block styles in flow mode.
|| (state.flowLevel > -1 && level >= state.flowLevel);
function testAmbiguity(string) {
return testImplicitResolving(state, string);
}
switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
case STYLE_PLAIN:
return string;
case STYLE_SINGLE:
return "'" + string.replace(/'/g, "''") + "'";
case STYLE_LITERAL:
return '|' + blockHeader(string, state.indent)
+ dropEndingNewline(indentString(string, indent));
case STYLE_FOLDED:
return '>' + blockHeader(string, state.indent)
+ dropEndingNewline(indentString(foldString(string, lineWidth), indent));
case STYLE_DOUBLE:
return '"' + escapeString(string, lineWidth) + '"';
default:
throw new YAMLException('impossible error: invalid scalar style');
}
}());
}
// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
function blockHeader(string, indentPerLevel) {
var indentIndicator = (string[0] === ' ') ? String(indentPerLevel) : '';
// note the special case: the string '\n' counts as a "trailing" empty line.
var clip = string[string.length - 1] === '\n';
var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
var chomp = keep ? '+' : (clip ? '' : '-');
return indentIndicator + chomp + '\n';
}
// (See the note for writeScalar.)
function dropEndingNewline(string) {
return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
}
// Note: a long line without a suitable break point will exceed the width limit.
// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
function foldString(string, width) {
// In folded style, $k$ consecutive newlines output as $k+1$ newlines—
// unless they're before or after a more-indented line, or at the very
// beginning or end, in which case $k$ maps to $k$.
// Therefore, parse each chunk as newline(s) followed by a content line.
var lineRe = /(\n+)([^\n]*)/g;
// first line (possibly an empty line)
var result = (function () {
var nextLF = string.indexOf('\n');
nextLF = nextLF !== -1 ? nextLF : string.length;
lineRe.lastIndex = nextLF;
return foldLine(string.slice(0, nextLF), width);
}());
// If we haven't reached the first content line yet, don't add an extra \n.
var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
var moreIndented;
// rest of the lines
var match;
while ((match = lineRe.exec(string))) {
var prefix = match[1], line = match[2];
moreIndented = (line[0] === ' ');
result += prefix
+ (!prevMoreIndented && !moreIndented && line !== ''
? '\n' : '')
+ foldLine(line, width);
prevMoreIndented = moreIndented;
}
return result;
}
// Greedy line breaking.
// Picks the longest line under the limit each time,
// otherwise settles for the shortest line over the limit.
// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
function foldLine(line, width) {
if (line === '' || line[0] === ' ') return line;
// Since a more-indented line adds a \n, breaks can't be followed by a space.
var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
var match;
// start is an inclusive index. end, curr, and next are exclusive.
var start = 0, end, curr = 0, next = 0;
var result = '';
// Invariants: 0 <= start <= length-1.
// 0 <= curr <= next <= max(0, length-2). curr - start <= width.
// Inside the loop:
// A match implies length >= 2, so curr and next are <= length-2.
while ((match = breakRe.exec(line))) {
next = match.index;
// maintain invariant: curr - start <= width
if (next - start > width) {
end = (curr > start) ? curr : next; // derive end <= length-2
result += '\n' + line.slice(start, end);
// skip the space that was output as \n
start = end + 1; // derive start <= length-1
}
curr = next;
}
// By the invariants, start <= length-1, so there is something left over.
// It is either the whole string or a part starting from non-whitespace.
result += '\n';
// Insert a break if the remainder is too long and there is a break available.
if (line.length - start > width && curr > start) {
result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
} else {
result += line.slice(start);
}
return result.slice(1); // drop extra \n joiner
}
// Escapes a double-quoted string.
function escapeString(string) {
var result = '';
var char, nextChar;
var escapeSeq;
for (var i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
// Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {
nextChar = string.charCodeAt(i + 1);
if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {
// Combine the surrogate pair and store it escaped.
result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);
// Advance index one extra since we already used that char here.
i++; continue;
}
}
escapeSeq = ESCAPE_SEQUENCES[char];
result += !escapeSeq && isPrintable(char)
? string[i]
: escapeSeq || encodeHex(char);
}
return result;
}
function writeFlowSequence(state, level, object) {
var _result = '',
_tag = state.tag,
index,
length;
for (index = 0, length = object.length; index < length; index += 1) {
// Write only valid elements.
if (writeNode(state, level, object[index], false, false)) {
if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
_result += state.dump;
}
}
state.tag = _tag;
state.dump = '[' + _result + ']';
}
function writeBlockSequence(state, level, object, compact) {
var _result = '',
_tag = state.tag,
index,
length;
for (index = 0, length = object.length; index < length; index += 1) {
// Write only valid elements.
if (writeNode(state, level + 1, object[index], true, true)) {
if (!compact || index !== 0) {
_result += generateNextLine(state, level);
}
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
_result += '-';
} else {
_result += '- ';
}
_result += state.dump;
}
}
state.tag = _tag;
state.dump = _result || '[]'; // Empty sequence if no valid values.
}
function writeFlowMapping(state, level, object) {
var _result = '',
_tag = state.tag,
objectKeyList = Object.keys(object),
index,
length,
objectKey,
objectValue,
pairBuffer;
for (index = 0, length = objectKeyList.length; index < length; index += 1) {
pairBuffer = state.condenseFlow ? '"' : '';
if (index !== 0) pairBuffer += ', ';
objectKey = objectKeyList[index];
objectValue = object[objectKey];
if (!writeNode(state, level, objectKey, false, false)) {
continue; // Skip this pair because of invalid key;
}
if (state.dump.length > 1024) pairBuffer += '? ';
pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
if (!writeNode(state, level, objectValue, false, false)) {
continue; // Skip this pair because of invalid value.
}
pairBuffer += state.dump;
// Both key and value are valid.
_result += pairBuffer;
}
state.tag = _tag;
state.dump = '{' + _result + '}';
}
function writeBlockMapping(state, level, object, compact) {
var _result = '',
_tag = state.tag,
objectKeyList = Object.keys(object),
index,
length,
objectKey,
objectValue,
explicitPair,
pairBuffer;
// Allow sorting keys so that the output file is deterministic
if (state.sortKeys === true) {
// Default sorting
objectKeyList.sort();
} else if (typeof state.sortKeys === 'function') {
// Custom sort function
objectKeyList.sort(state.sortKeys);
} else if (state.sortKeys) {
// Something is wrong
throw new YAMLException('sortKeys must be a boolean or a function');
}
for (index = 0, length = objectKeyList.length; index < length; index += 1) {
pairBuffer = '';
if (!compact || index !== 0) {
pairBuffer += generateNextLine(state, level);
}
objectKey = objectKeyList[index];
objectValue = object[objectKey];
if (!writeNode(state, level + 1, objectKey, true, true, true)) {
continue; // Skip this pair because of invalid key.
}
explicitPair = (state.tag !== null && state.tag !== '?') ||
(state.dump && state.dump.length > 1024);
if (explicitPair) {
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
pairBuffer += '?';
} else {
pairBuffer += '? ';
}
}
pairBuffer += state.dump;
if (explicitPair) {
pairBuffer += generateNextLine(state, level);
}
if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
continue; // Skip this pair because of invalid value.
}
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
pairBuffer += ':';
} else {
pairBuffer += ': ';
}
pairBuffer += state.dump;
// Both key and value are valid.
_result += pairBuffer;
}
state.tag = _tag;
state.dump = _result || '{}'; // Empty mapping if no valid pairs.
}
function detectType(state, object, explicit) {
var _result, typeList, index, length, type, style;
typeList = explicit ? state.explicitTypes : state.implicitTypes;
for (index = 0, length = typeList.length; index < length; index += 1) {
type = typeList[index];
if ((type.instanceOf || type.predicate) &&
(!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
(!type.predicate || type.predicate(object))) {
state.tag = explicit ? type.tag : '?';
if (type.represent) {
style = state.styleMap[type.tag] || type.defaultStyle;
if (_toString.call(type.represent) === '[object Function]') {
_result = type.represent(object, style);
} else if (_hasOwnProperty.call(type.represent, style)) {
_result = type.represent[style](object, style);
} else {
throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
}
state.dump = _result;
}
return true;
}
}
return false;
}
// Serializes `object` and writes it to global `result`.
// Returns true on success, or false on invalid object.
//
function writeNode(state, level, object, block, compact, iskey) {
state.tag = null;
state.dump = object;
if (!detectType(state, object, false)) {
detectType(state, object, true);
}
var type = _toString.call(state.dump);
if (block) {
block = (state.flowLevel < 0 || state.flowLevel > level);
}
var objectOrArray = type === '[object Object]' || type === '[object Array]',
duplicateIndex,
duplicate;
if (objectOrArray) {
duplicateIndex = state.duplicates.indexOf(object);
duplicate = duplicateIndex !== -1;
}
if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
compact = false;
}
if (duplicate && state.usedDuplicates[duplicateIndex]) {
state.dump = '*ref_' + duplicateIndex;
} else {
if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
state.usedDuplicates[duplicateIndex] = true;
}
if (type === '[object Object]') {
if (block && (Object.keys(state.dump).length !== 0)) {
writeBlockMapping(state, level, state.dump, compact);
if (duplicate) {
state.dump = '&ref_' + duplicateIndex + state.dump;
}
} else {
writeFlowMapping(state, level, state.dump);
if (duplicate) {
state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
}
}
} else if (type === '[object Array]') {
if (block && (state.dump.length !== 0)) {
writeBlockSequence(state, level, state.dump, compact);
if (duplicate) {
state.dump = '&ref_' + duplicateIndex + state.dump;
}
} else {
writeFlowSequence(state, level, state.dump);
if (duplicate) {
state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
}
}
} else if (type === '[object String]') {
if (state.tag !== '?') {
writeScalar(state, state.dump, level, iskey);
}
} else {
if (state.skipInvalid) return false;
throw new YAMLException('unacceptable kind of an object to dump ' + type);
}
if (state.tag !== null && state.tag !== '?') {
state.dump = '!<' + state.tag + '> ' + state.dump;
}
}
return true;
}
function getDuplicateReferences(object, state) {
var objects = [],
duplicatesIndexes = [],
index,
length;
inspectNode(object, objects, duplicatesIndexes);
for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
state.duplicates.push(objects[duplicatesIndexes[index]]);
}
state.usedDuplicates = new Array(length);
}
function inspectNode(object, objects, duplicatesIndexes) {
var objectKeyList,
index,
length;
if (object !== null && typeof object === 'object') {
index = objects.indexOf(object);
if (index !== -1) {
if (duplicatesIndexes.indexOf(index) === -1) {
duplicatesIndexes.push(index);
}
} else {
objects.push(object);
if (Array.isArray(object)) {
for (index = 0, length = object.length; index < length; index += 1) {
inspectNode(object[index], objects, duplicatesIndexes);
}
} else {
objectKeyList = Object.keys(object);
for (index = 0, length = objectKeyList.length; index < length; index += 1) {
inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
}
}
}
}
}
function dump(input, options) {
options = options || {};
var state = new State(options);
if (!state.noRefs) getDuplicateReferences(input, state);
if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
return '';
}
function safeDump(input, options) {
return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}
module.exports.dump = dump;
module.exports.safeDump = safeDump;

View File

@ -1,43 +0,0 @@
// YAML error class. http://stackoverflow.com/questions/8458984
//
'use strict';
function YAMLException(reason, mark) {
// Super constructor
Error.call(this);
this.name = 'YAMLException';
this.reason = reason;
this.mark = mark;
this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');
// Include stack trace in error object
if (Error.captureStackTrace) {
// Chrome and NodeJS
Error.captureStackTrace(this, this.constructor);
} else {
// FF, IE 10+ and Safari 6+. Fallback for others
this.stack = (new Error()).stack || '';
}
}
// Inherit from Error
YAMLException.prototype = Object.create(Error.prototype);
YAMLException.prototype.constructor = YAMLException;
YAMLException.prototype.toString = function toString(compact) {
var result = this.name + ': ';
result += this.reason || '(unknown reason)';
if (!compact && this.mark) {
result += ' ' + this.mark.toString();
}
return result;
};
module.exports = YAMLException;

File diff suppressed because it is too large Load Diff

View File

@ -1,76 +0,0 @@
'use strict';
var common = require('./common');
function Mark(name, buffer, position, line, column) {
this.name = name;
this.buffer = buffer;
this.position = position;
this.line = line;
this.column = column;
}
Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
var head, start, tail, end, snippet;
if (!this.buffer) return null;
indent = indent || 4;
maxLength = maxLength || 75;
head = '';
start = this.position;
while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {
start -= 1;
if (this.position - start > (maxLength / 2 - 1)) {
head = ' ... ';
start += 5;
break;
}
}
tail = '';
end = this.position;
while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {
end += 1;
if (end - this.position > (maxLength / 2 - 1)) {
tail = ' ... ';
end -= 5;
break;
}
}
snippet = this.buffer.slice(start, end);
return common.repeat(' ', indent) + head + snippet + tail + '\n' +
common.repeat(' ', indent + this.position - start + head.length) + '^';
};
Mark.prototype.toString = function toString(compact) {
var snippet, where = '';
if (this.name) {
where += 'in "' + this.name + '" ';
}
where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);
if (!compact) {
snippet = this.getSnippet();
if (snippet) {
where += ':\n' + snippet;
}
}
return where;
};
module.exports = Mark;

View File

@ -1,108 +0,0 @@
'use strict';
/*eslint-disable max-len*/
var common = require('./common');
var YAMLException = require('./exception');
var Type = require('./type');
function compileList(schema, name, result) {
var exclude = [];
schema.include.forEach(function (includedSchema) {
result = compileList(includedSchema, name, result);
});
schema[name].forEach(function (currentType) {
result.forEach(function (previousType, previousIndex) {
if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
exclude.push(previousIndex);
}
});
result.push(currentType);
});
return result.filter(function (type, index) {
return exclude.indexOf(index) === -1;
});
}
function compileMap(/* lists... */) {
var result = {
scalar: {},
sequence: {},
mapping: {},
fallback: {}
}, index, length;
function collectType(type) {
result[type.kind][type.tag] = result['fallback'][type.tag] = type;
}
for (index = 0, length = arguments.length; index < length; index += 1) {
arguments[index].forEach(collectType);
}
return result;
}
function Schema(definition) {
this.include = definition.include || [];
this.implicit = definition.implicit || [];
this.explicit = definition.explicit || [];
this.implicit.forEach(function (type) {
if (type.loadKind && type.loadKind !== 'scalar') {
throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
}
});
this.compiledImplicit = compileList(this, 'implicit', []);
this.compiledExplicit = compileList(this, 'explicit', []);
this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
}
Schema.DEFAULT = null;
Schema.create = function createSchema() {
var schemas, types;
switch (arguments.length) {
case 1:
schemas = Schema.DEFAULT;
types = arguments[0];
break;
case 2:
schemas = arguments[0];
types = arguments[1];
break;
default:
throw new YAMLException('Wrong number of arguments for Schema.create function');
}
schemas = common.toArray(schemas);
types = common.toArray(types);
if (!schemas.every(function (schema) { return schema instanceof Schema; })) {
throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
}
if (!types.every(function (type) { return type instanceof Type; })) {
throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');
}
return new Schema({
include: schemas,
explicit: types
});
};
module.exports = Schema;

View File

@ -1,18 +0,0 @@
// Standard YAML's Core schema.
// http://www.yaml.org/spec/1.2/spec.html#id2804923
//
// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
// So, Core schema has no distinctions from JSON schema is JS-YAML.
'use strict';
var Schema = require('../schema');
module.exports = new Schema({
include: [
require('./json')
]
});

View File

@ -1,25 +0,0 @@
// JS-YAML's default schema for `load` function.
// It is not described in the YAML specification.
//
// This schema is based on JS-YAML's default safe schema and includes
// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function.
//
// Also this schema is used as default base schema at `Schema.create` function.
'use strict';
var Schema = require('../schema');
module.exports = Schema.DEFAULT = new Schema({
include: [
require('./default_safe')
],
explicit: [
require('../type/js/undefined'),
require('../type/js/regexp'),
require('../type/js/function')
]
});

View File

@ -1,28 +0,0 @@
// JS-YAML's default schema for `safeLoad` function.
// It is not described in the YAML specification.
//
// This schema is based on standard YAML's Core schema and includes most of
// extra types described at YAML tag repository. (http://yaml.org/type/)
'use strict';
var Schema = require('../schema');
module.exports = new Schema({
include: [
require('./core')
],
implicit: [
require('../type/timestamp'),
require('../type/merge')
],
explicit: [
require('../type/binary'),
require('../type/omap'),
require('../type/pairs'),
require('../type/set')
]
});

View File

@ -1,17 +0,0 @@
// Standard YAML's Failsafe schema.
// http://www.yaml.org/spec/1.2/spec.html#id2802346
'use strict';
var Schema = require('../schema');
module.exports = new Schema({
explicit: [
require('../type/str'),
require('../type/seq'),
require('../type/map')
]
});

View File

@ -1,25 +0,0 @@
// Standard YAML's JSON schema.
// http://www.yaml.org/spec/1.2/spec.html#id2803231
//
// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
// So, this schema is not such strict as defined in the YAML specification.
// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.
'use strict';
var Schema = require('../schema');
module.exports = new Schema({
include: [
require('./failsafe')
],
implicit: [
require('../type/null'),
require('../type/bool'),
require('../type/int'),
require('../type/float')
]
});

View File

@ -1,61 +0,0 @@
'use strict';
var YAMLException = require('./exception');
var TYPE_CONSTRUCTOR_OPTIONS = [
'kind',
'resolve',
'construct',
'instanceOf',
'predicate',
'represent',
'defaultStyle',
'styleAliases'
];
var YAML_NODE_KINDS = [
'scalar',
'sequence',
'mapping'
];
function compileStyleAliases(map) {
var result = {};
if (map !== null) {
Object.keys(map).forEach(function (style) {
map[style].forEach(function (alias) {
result[String(alias)] = style;
});
});
}
return result;
}
function Type(tag, options) {
options = options || {};
Object.keys(options).forEach(function (name) {
if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
}
});
// TODO: Add tag format check.
this.tag = tag;
this.kind = options['kind'] || null;
this.resolve = options['resolve'] || function () { return true; };
this.construct = options['construct'] || function (data) { return data; };
this.instanceOf = options['instanceOf'] || null;
this.predicate = options['predicate'] || null;
this.represent = options['represent'] || null;
this.defaultStyle = options['defaultStyle'] || null;
this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
}
}
module.exports = Type;

View File

@ -1,138 +0,0 @@
'use strict';
/*eslint-disable no-bitwise*/
var NodeBuffer;
// try {
// // A trick for browserified version, to not include `Buffer` shim
// var _require = require;
// NodeBuffer = _require('buffer').Buffer;
// } catch (__) {}
var Type = require('../type');
// [ 64, 65, 66 ] -> [ padding, CR, LF ]
var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
function resolveYamlBinary(data) {
if (data === null) return false;
var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
// Convert one by one.
for (idx = 0; idx < max; idx++) {
code = map.indexOf(data.charAt(idx));
// Skip CR/LF
if (code > 64) continue;
// Fail on illegal characters
if (code < 0) return false;
bitlen += 6;
}
// If there are any bits left, source was corrupted
return (bitlen % 8) === 0;
}
function constructYamlBinary(data) {
var idx, tailbits,
input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
max = input.length,
map = BASE64_MAP,
bits = 0,
result = [];
// Collect by 6*4 bits (3 bytes)
for (idx = 0; idx < max; idx++) {
if ((idx % 4 === 0) && idx) {
result.push((bits >> 16) & 0xFF);
result.push((bits >> 8) & 0xFF);
result.push(bits & 0xFF);
}
bits = (bits << 6) | map.indexOf(input.charAt(idx));
}
// Dump tail
tailbits = (max % 4) * 6;
if (tailbits === 0) {
result.push((bits >> 16) & 0xFF);
result.push((bits >> 8) & 0xFF);
result.push(bits & 0xFF);
} else if (tailbits === 18) {
result.push((bits >> 10) & 0xFF);
result.push((bits >> 2) & 0xFF);
} else if (tailbits === 12) {
result.push((bits >> 4) & 0xFF);
}
// Wrap into Buffer for NodeJS and leave Array for browser
if (NodeBuffer) {
// Support node 6.+ Buffer API when available
return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
}
return result;
}
function representYamlBinary(object /*, style*/) {
var result = '', bits = 0, idx, tail,
max = object.length,
map = BASE64_MAP;
// Convert every three bytes to 4 ASCII characters.
for (idx = 0; idx < max; idx++) {
if ((idx % 3 === 0) && idx) {
result += map[(bits >> 18) & 0x3F];
result += map[(bits >> 12) & 0x3F];
result += map[(bits >> 6) & 0x3F];
result += map[bits & 0x3F];
}
bits = (bits << 8) + object[idx];
}
// Dump tail
tail = max % 3;
if (tail === 0) {
result += map[(bits >> 18) & 0x3F];
result += map[(bits >> 12) & 0x3F];
result += map[(bits >> 6) & 0x3F];
result += map[bits & 0x3F];
} else if (tail === 2) {
result += map[(bits >> 10) & 0x3F];
result += map[(bits >> 4) & 0x3F];
result += map[(bits << 2) & 0x3F];
result += map[64];
} else if (tail === 1) {
result += map[(bits >> 2) & 0x3F];
result += map[(bits << 4) & 0x3F];
result += map[64];
result += map[64];
}
return result;
}
function isBinary(object) {
return NodeBuffer && NodeBuffer.isBuffer(object);
}
module.exports = new Type('tag:yaml.org,2002:binary', {
kind: 'scalar',
resolve: resolveYamlBinary,
construct: constructYamlBinary,
predicate: isBinary,
represent: representYamlBinary
});

View File

@ -1,35 +0,0 @@
'use strict';
var Type = require('../type');
function resolveYamlBoolean(data) {
if (data === null) return false;
var max = data.length;
return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
(max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
}
function constructYamlBoolean(data) {
return data === 'true' ||
data === 'True' ||
data === 'TRUE';
}
function isBoolean(object) {
return Object.prototype.toString.call(object) === '[object Boolean]';
}
module.exports = new Type('tag:yaml.org,2002:bool', {
kind: 'scalar',
resolve: resolveYamlBoolean,
construct: constructYamlBoolean,
predicate: isBoolean,
represent: {
lowercase: function (object) { return object ? 'true' : 'false'; },
uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
camelcase: function (object) { return object ? 'True' : 'False'; }
},
defaultStyle: 'lowercase'
});

View File

@ -1,116 +0,0 @@
'use strict';
var common = require('../common');
var Type = require('../type');
var YAML_FLOAT_PATTERN = new RegExp(
// 2.5e4, 2.5 and integers
'^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
// .2e4, .2
// special case, seems not from spec
'|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
// 20:59
'|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' +
// .inf
'|[-+]?\\.(?:inf|Inf|INF)' +
// .nan
'|\\.(?:nan|NaN|NAN))$');
function resolveYamlFloat(data) {
if (data === null) return false;
if (!YAML_FLOAT_PATTERN.test(data) ||
// Quick hack to not allow integers end with `_`
// Probably should update regexp & check speed
data[data.length - 1] === '_') {
return false;
}
return true;
}
function constructYamlFloat(data) {
var value, sign, base, digits;
value = data.replace(/_/g, '').toLowerCase();
sign = value[0] === '-' ? -1 : 1;
digits = [];
if ('+-'.indexOf(value[0]) >= 0) {
value = value.slice(1);
}
if (value === '.inf') {
return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
} else if (value === '.nan') {
return NaN;
} else if (value.indexOf(':') >= 0) {
value.split(':').forEach(function (v) {
digits.unshift(parseFloat(v, 10));
});
value = 0.0;
base = 1;
digits.forEach(function (d) {
value += d * base;
base *= 60;
});
return sign * value;
}
return sign * parseFloat(value, 10);
}
var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
function representYamlFloat(object, style) {
var res;
if (isNaN(object)) {
switch (style) {
case 'lowercase': return '.nan';
case 'uppercase': return '.NAN';
case 'camelcase': return '.NaN';
}
} else if (Number.POSITIVE_INFINITY === object) {
switch (style) {
case 'lowercase': return '.inf';
case 'uppercase': return '.INF';
case 'camelcase': return '.Inf';
}
} else if (Number.NEGATIVE_INFINITY === object) {
switch (style) {
case 'lowercase': return '-.inf';
case 'uppercase': return '-.INF';
case 'camelcase': return '-.Inf';
}
} else if (common.isNegativeZero(object)) {
return '-0.0';
}
res = object.toString(10);
// JS stringifier can build scientific format without dots: 5e-100,
// while YAML requres dot: 5.e-100. Fix it with simple hack
return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
}
function isFloat(object) {
return (Object.prototype.toString.call(object) === '[object Number]') &&
(object % 1 !== 0 || common.isNegativeZero(object));
}
module.exports = new Type('tag:yaml.org,2002:float', {
kind: 'scalar',
resolve: resolveYamlFloat,
construct: constructYamlFloat,
predicate: isFloat,
represent: representYamlFloat,
defaultStyle: 'lowercase'
});

View File

@ -1,172 +0,0 @@
'use strict';
var common = require('../common');
var Type = require('../type');
function isHexCode(c) {
return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
((0x61/* a */ <= c) && (c <= 0x66/* f */));
}
function isOctCode(c) {
return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
}
function isDecCode(c) {
return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
}
function resolveYamlInteger(data) {
if (data === null) return false;
var max = data.length,
index = 0,
hasDigits = false,
ch;
if (!max) return false;
ch = data[index];
// sign
if (ch === '-' || ch === '+') {
ch = data[++index];
}
if (ch === '0') {
// 0
if (index + 1 === max) return true;
ch = data[++index];
// base 2, base 8, base 16
if (ch === 'b') {
// base 2
index++;
for (; index < max; index++) {
ch = data[index];
if (ch === '_') continue;
if (ch !== '0' && ch !== '1') return false;
hasDigits = true;
}
return hasDigits && ch !== '_';
}
if (ch === 'x') {
// base 16
index++;
for (; index < max; index++) {
ch = data[index];
if (ch === '_') continue;
if (!isHexCode(data.charCodeAt(index))) return false;
hasDigits = true;
}
return hasDigits && ch !== '_';
}
// base 8
for (; index < max; index++) {
ch = data[index];
if (ch === '_') continue;
if (!isOctCode(data.charCodeAt(index))) return false;
hasDigits = true;
}
return hasDigits && ch !== '_';
}
// base 10 (except 0) or base 60
// value should not start with `_`;
if (ch === '_') return false;
for (; index < max; index++) {
ch = data[index];
if (ch === '_') continue;
if (ch === ':') break;
if (!isDecCode(data.charCodeAt(index))) {
return false;
}
hasDigits = true;
}
// Should have digits and should not end with `_`
if (!hasDigits || ch === '_') return false;
// if !base60 - done;
if (ch !== ':') return true;
// base60 almost not used, no needs to optimize
return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
}
function constructYamlInteger(data) {
var value = data, sign = 1, ch, base, digits = [];
if (value.indexOf('_') !== -1) {
value = value.replace(/_/g, '');
}
ch = value[0];
if (ch === '-' || ch === '+') {
if (ch === '-') sign = -1;
value = value.slice(1);
ch = value[0];
}
if (value === '0') return 0;
if (ch === '0') {
if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
if (value[1] === 'x') return sign * parseInt(value, 16);
return sign * parseInt(value, 8);
}
if (value.indexOf(':') !== -1) {
value.split(':').forEach(function (v) {
digits.unshift(parseInt(v, 10));
});
value = 0;
base = 1;
digits.forEach(function (d) {
value += (d * base);
base *= 60;
});
return sign * value;
}
return sign * parseInt(value, 10);
}
function isInteger(object) {
return (Object.prototype.toString.call(object)) === '[object Number]' &&
(object % 1 === 0 && !common.isNegativeZero(object));
}
module.exports = new Type('tag:yaml.org,2002:int', {
kind: 'scalar',
resolve: resolveYamlInteger,
construct: constructYamlInteger,
predicate: isInteger,
represent: {
binary: function (object) { return '0b' + object.toString(2); },
octal: function (object) { return '0' + object.toString(8); },
decimal: function (object) { return object.toString(10); },
hexadecimal: function (object) { return '0x' + object.toString(16).toUpperCase(); }
},
defaultStyle: 'decimal',
styleAliases: {
binary: [ 2, 'bin' ],
octal: [ 8, 'oct' ],
decimal: [ 10, 'dec' ],
hexadecimal: [ 16, 'hex' ]
}
});

View File

@ -1,84 +0,0 @@
'use strict';
var esprima;
// Browserified version does not have esprima
//
// 1. For node.js just require module as deps
// 2. For browser try to require mudule via external AMD system.
// If not found - try to fallback to window.esprima. If not
// found too - then fail to parse.
//
// try {
// // workaround to exclude package from browserify list.
// var _require = require;
// esprima = _require('esprima');
// } catch (_) {
// /*global window */
// if (typeof window !== 'undefined') esprima = window.esprima;
// }
var Type = require('../../type');
function resolveJavascriptFunction(data) {
if (data === null) return false;
try {
var source = '(' + data + ')',
ast = esprima.parse(source, { range: true });
if (ast.type !== 'Program' ||
ast.body.length !== 1 ||
ast.body[0].type !== 'ExpressionStatement' ||
ast.body[0].expression.type !== 'FunctionExpression') {
return false;
}
return true;
} catch (err) {
return false;
}
}
function constructJavascriptFunction(data) {
/*jslint evil:true*/
var source = '(' + data + ')',
ast = esprima.parse(source, { range: true }),
params = [],
body;
if (ast.type !== 'Program' ||
ast.body.length !== 1 ||
ast.body[0].type !== 'ExpressionStatement' ||
ast.body[0].expression.type !== 'FunctionExpression') {
throw new Error('Failed to resolve function');
}
ast.body[0].expression.params.forEach(function (param) {
params.push(param.name);
});
body = ast.body[0].expression.body.range;
// Esprima's ranges include the first '{' and the last '}' characters on
// function expressions. So cut them out.
/*eslint-disable no-new-func*/
return new Function(params, source.slice(body[0] + 1, body[1] - 1));
}
function representJavascriptFunction(object /*, style*/) {
return object.toString();
}
function isFunction(object) {
return Object.prototype.toString.call(object) === '[object Function]';
}
module.exports = new Type('tag:yaml.org,2002:js/function', {
kind: 'scalar',
resolve: resolveJavascriptFunction,
construct: constructJavascriptFunction,
predicate: isFunction,
represent: representJavascriptFunction
});

View File

@ -1,60 +0,0 @@
'use strict';
var Type = require('../../type');
function resolveJavascriptRegExp(data) {
if (data === null) return false;
if (data.length === 0) return false;
var regexp = data,
tail = /\/([gim]*)$/.exec(data),
modifiers = '';
// if regexp starts with '/' it can have modifiers and must be properly closed
// `/foo/gim` - modifiers tail can be maximum 3 chars
if (regexp[0] === '/') {
if (tail) modifiers = tail[1];
if (modifiers.length > 3) return false;
// if expression starts with /, is should be properly terminated
if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;
}
return true;
}
function constructJavascriptRegExp(data) {
var regexp = data,
tail = /\/([gim]*)$/.exec(data),
modifiers = '';
// `/foo/gim` - tail can be maximum 4 chars
if (regexp[0] === '/') {
if (tail) modifiers = tail[1];
regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
}
return new RegExp(regexp, modifiers);
}
function representJavascriptRegExp(object /*, style*/) {
var result = '/' + object.source + '/';
if (object.global) result += 'g';
if (object.multiline) result += 'm';
if (object.ignoreCase) result += 'i';
return result;
}
function isRegExp(object) {
return Object.prototype.toString.call(object) === '[object RegExp]';
}
module.exports = new Type('tag:yaml.org,2002:js/regexp', {
kind: 'scalar',
resolve: resolveJavascriptRegExp,
construct: constructJavascriptRegExp,
predicate: isRegExp,
represent: representJavascriptRegExp
});

View File

@ -1,28 +0,0 @@
'use strict';
var Type = require('../../type');
function resolveJavascriptUndefined() {
return true;
}
function constructJavascriptUndefined() {
/*eslint-disable no-undefined*/
return undefined;
}
function representJavascriptUndefined() {
return '';
}
function isUndefined(object) {
return typeof object === 'undefined';
}
module.exports = new Type('tag:yaml.org,2002:js/undefined', {
kind: 'scalar',
resolve: resolveJavascriptUndefined,
construct: constructJavascriptUndefined,
predicate: isUndefined,
represent: representJavascriptUndefined
});

View File

@ -1,8 +0,0 @@
'use strict';
var Type = require('../type');
module.exports = new Type('tag:yaml.org,2002:map', {
kind: 'mapping',
construct: function (data) { return data !== null ? data : {}; }
});

View File

@ -1,12 +0,0 @@
'use strict';
var Type = require('../type');
function resolveYamlMerge(data) {
return data === '<<' || data === null;
}
module.exports = new Type('tag:yaml.org,2002:merge', {
kind: 'scalar',
resolve: resolveYamlMerge
});

View File

@ -1,34 +0,0 @@
'use strict';
var Type = require('../type');
function resolveYamlNull(data) {
if (data === null) return true;
var max = data.length;
return (max === 1 && data === '~') ||
(max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
}
function constructYamlNull() {
return null;
}
function isNull(object) {
return object === null;
}
module.exports = new Type('tag:yaml.org,2002:null', {
kind: 'scalar',
resolve: resolveYamlNull,
construct: constructYamlNull,
predicate: isNull,
represent: {
canonical: function () { return '~'; },
lowercase: function () { return 'null'; },
uppercase: function () { return 'NULL'; },
camelcase: function () { return 'Null'; }
},
defaultStyle: 'lowercase'
});

View File

@ -1,44 +0,0 @@
'use strict';
var Type = require('../type');
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var _toString = Object.prototype.toString;
function resolveYamlOmap(data) {
if (data === null) return true;
var objectKeys = [], index, length, pair, pairKey, pairHasKey,
object = data;
for (index = 0, length = object.length; index < length; index += 1) {
pair = object[index];
pairHasKey = false;
if (_toString.call(pair) !== '[object Object]') return false;
for (pairKey in pair) {
if (_hasOwnProperty.call(pair, pairKey)) {
if (!pairHasKey) pairHasKey = true;
else return false;
}
}
if (!pairHasKey) return false;
if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
else return false;
}
return true;
}
function constructYamlOmap(data) {
return data !== null ? data : [];
}
module.exports = new Type('tag:yaml.org,2002:omap', {
kind: 'sequence',
resolve: resolveYamlOmap,
construct: constructYamlOmap
});

View File

@ -1,53 +0,0 @@
'use strict';
var Type = require('../type');
var _toString = Object.prototype.toString;
function resolveYamlPairs(data) {
if (data === null) return true;
var index, length, pair, keys, result,
object = data;
result = new Array(object.length);
for (index = 0, length = object.length; index < length; index += 1) {
pair = object[index];
if (_toString.call(pair) !== '[object Object]') return false;
keys = Object.keys(pair);
if (keys.length !== 1) return false;
result[index] = [ keys[0], pair[keys[0]] ];
}
return true;
}
function constructYamlPairs(data) {
if (data === null) return [];
var index, length, pair, keys, result,
object = data;
result = new Array(object.length);
for (index = 0, length = object.length; index < length; index += 1) {
pair = object[index];
keys = Object.keys(pair);
result[index] = [ keys[0], pair[keys[0]] ];
}
return result;
}
module.exports = new Type('tag:yaml.org,2002:pairs', {
kind: 'sequence',
resolve: resolveYamlPairs,
construct: constructYamlPairs
});

View File

@ -1,8 +0,0 @@
'use strict';
var Type = require('../type');
module.exports = new Type('tag:yaml.org,2002:seq', {
kind: 'sequence',
construct: function (data) { return data !== null ? data : []; }
});

View File

@ -1,29 +0,0 @@
'use strict';
var Type = require('../type');
var _hasOwnProperty = Object.prototype.hasOwnProperty;
function resolveYamlSet(data) {
if (data === null) return true;
var key, object = data;
for (key in object) {
if (_hasOwnProperty.call(object, key)) {
if (object[key] !== null) return false;
}
}
return true;
}
function constructYamlSet(data) {
return data !== null ? data : {};
}
module.exports = new Type('tag:yaml.org,2002:set', {
kind: 'mapping',
resolve: resolveYamlSet,
construct: constructYamlSet
});

View File

@ -1,8 +0,0 @@
'use strict';
var Type = require('../type');
module.exports = new Type('tag:yaml.org,2002:str', {
kind: 'scalar',
construct: function (data) { return data !== null ? data : ''; }
});

View File

@ -1,88 +0,0 @@
'use strict';
var Type = require('../type');
var YAML_DATE_REGEXP = new RegExp(
'^([0-9][0-9][0-9][0-9])' + // [1] year
'-([0-9][0-9])' + // [2] month
'-([0-9][0-9])$'); // [3] day
var YAML_TIMESTAMP_REGEXP = new RegExp(
'^([0-9][0-9][0-9][0-9])' + // [1] year
'-([0-9][0-9]?)' + // [2] month
'-([0-9][0-9]?)' + // [3] day
'(?:[Tt]|[ \\t]+)' + // ...
'([0-9][0-9]?)' + // [4] hour
':([0-9][0-9])' + // [5] minute
':([0-9][0-9])' + // [6] second
'(?:\\.([0-9]*))?' + // [7] fraction
'(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
'(?::([0-9][0-9]))?))?$'); // [11] tz_minute
function resolveYamlTimestamp(data) {
if (data === null) return false;
if (YAML_DATE_REGEXP.exec(data) !== null) return true;
if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
return false;
}
function constructYamlTimestamp(data) {
var match, year, month, day, hour, minute, second, fraction = 0,
delta = null, tz_hour, tz_minute, date;
match = YAML_DATE_REGEXP.exec(data);
if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
if (match === null) throw new Error('Date resolve error');
// match: [1] year [2] month [3] day
year = +(match[1]);
month = +(match[2]) - 1; // JS month starts with 0
day = +(match[3]);
if (!match[4]) { // no hour
return new Date(Date.UTC(year, month, day));
}
// match: [4] hour [5] minute [6] second [7] fraction
hour = +(match[4]);
minute = +(match[5]);
second = +(match[6]);
if (match[7]) {
fraction = match[7].slice(0, 3);
while (fraction.length < 3) { // milli-seconds
fraction += '0';
}
fraction = +fraction;
}
// match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
if (match[9]) {
tz_hour = +(match[10]);
tz_minute = +(match[11] || 0);
delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
if (match[9] === '-') delta = -delta;
}
date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
if (delta) date.setTime(date.getTime() - delta);
return date;
}
function representYamlTimestamp(object /*, style*/) {
return object.toISOString();
}
module.exports = new Type('tag:yaml.org,2002:timestamp', {
kind: 'scalar',
resolve: resolveYamlTimestamp,
construct: constructYamlTimestamp,
instanceOf: Date,
represent: representYamlTimestamp
});

View File

@ -1,38 +0,0 @@
'use strict';
/*global Java, base, module, exports, require, __FILE__*/
var ZipFile = Java.type("java.util.zip.ZipFile");
var fs = require('fs');
/**
* 解压文件
* @param zipFile 压缩文件
* @param target 目标目录(不传则为zip文件同级目录)
*/
function unzip(zipFile, target) {
if (!zipFile.exists()) {
console.warn("解压文件 %s 错误 文件不存在!".format(zipFile));
return;
}
if (target === undefined) {
var fileName = zipFile.name;
// noinspection JSUnresolvedVariable
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);
var e = zipObj.entries();
while (e.hasMoreElements()) {
var entry = e.nextElement();
if (entry.isDirectory()) {
continue;
}
var destinationFilePath = fs.file(target, entry.name);
destinationFilePath.parentFile.mkdirs();
fs.copy(zipObj.getInputStream(entry), destinationFilePath, true);
}
zipObj.close();
}
exports.unzip = unzip;