enigma-bbs/core/asset.js

114 lines
2.0 KiB
JavaScript
Raw Normal View History

/* jslint node: true */
'use strict';
2016-06-26 04:36:40 +00:00
// ENiGMA½
const Config = require('./config.js').config;
2016-06-26 04:36:40 +00:00
// deps
const _ = require('lodash');
const assert = require('assert');
exports.parseAsset = parseAsset;
exports.getAssetWithShorthand = getAssetWithShorthand;
exports.getArtAsset = getArtAsset;
exports.getModuleAsset = getModuleAsset;
exports.resolveConfigAsset = resolveConfigAsset;
exports.getViewPropertyAsset = getViewPropertyAsset;
const ALL_ASSETS = [
'art',
'menu',
'method',
2016-06-26 04:36:40 +00:00
'module',
2015-04-21 05:24:15 +00:00
'systemMethod',
'systemModule',
'prompt',
'config',
];
2016-06-26 04:36:40 +00:00
const ASSET_RE = new RegExp('\\@(' + ALL_ASSETS.join('|') + ')\\:([\\w\\d\\.]*)(?:\\/([\\w\\d\\_]+))*');
function parseAsset(s) {
2016-06-26 04:36:40 +00:00
const m = ASSET_RE.exec(s);
if(m) {
2016-06-26 04:36:40 +00:00
let result = { type : m[1] };
if(m[3]) {
result.location = m[2];
result.asset = m[3];
} else {
result.asset = m[2];
}
return result;
}
}
function getAssetWithShorthand(spec, defaultType) {
if(!_.isString(spec)) {
return null;
}
if('@' === spec[0]) {
2016-06-26 04:36:40 +00:00
const asset = parseAsset(spec);
assert(_.isString(asset.type));
return asset;
} else {
return {
type : defaultType,
asset : spec,
2016-06-26 04:36:40 +00:00
};
}
}
2016-06-26 04:36:40 +00:00
function getArtAsset(spec) {
const asset = getAssetWithShorthand(spec, 'art');
if(!asset) {
return null;
}
2016-06-26 04:36:40 +00:00
assert( ['art', 'method' ].indexOf(asset.type) > -1);
return asset;
}
2016-06-26 04:36:40 +00:00
function getModuleAsset(spec) {
const asset = getAssetWithShorthand(spec, 'module');
if(!asset) {
return null;
}
2016-06-26 04:36:40 +00:00
assert( ['module', 'systemModule' ].indexOf(asset.type) > -1);
return asset;
}
2016-06-26 04:36:40 +00:00
function resolveConfigAsset(spec) {
const asset = parseAsset(spec);
if(asset) {
assert('config' === asset.type);
2016-06-26 04:36:40 +00:00
const path = asset.asset.split('.');
let conf = Config;
for(let i = 0; i < path.length; ++i) {
if(_.isUndefined(conf[path[i]])) {
2016-06-26 04:36:40 +00:00
return spec;
}
conf = conf[path[i]];
}
return conf;
} else {
2016-06-26 04:36:40 +00:00
return spec;
}
}
function getViewPropertyAsset(src) {
if(!_.isString(src) || '@' !== src.charAt(0)) {
return null;
}
return parseAsset(src);
2016-06-26 04:36:40 +00:00
}