@sprucelabs/spruce-skill-utils
Version:
Loosely coupled classes and functions to make skill development faster! 🏎
80 lines (79 loc) • 3.26 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const globby_1 = __importDefault(require("@sprucelabs/globby"));
const schema_1 = require("@sprucelabs/schema");
const SpruceError_1 = __importDefault(require("../errors/SpruceError"));
const disk_utility_1 = __importDefault(require("./disk.utility"));
const pluginUtil = {
async import(args, ...path) {
const lookup = path_1.default.join(...path, '**', '*.plugin.[t|j]s');
const results = await (0, globby_1.default)(lookup);
const plugins = [];
const all = results.map(async (path) => {
const plugin = require(path);
if (!plugin || !plugin.default) {
throw new SpruceError_1.default({
code: 'FAILED_TO_LOAD_PLUGIN',
file: path,
friendlyMessage: 'You must export your plugin as the default.',
});
}
const result = await plugin.default(...args);
plugins.push(result);
});
await Promise.all(all);
return plugins;
},
importSync(args, ...path) {
const missing = [];
if (!args) {
missing.push('args');
}
if (path.length === 0) {
missing.push('path');
}
if (missing.length > 0) {
throw new schema_1.SchemaError({
code: 'MISSING_PARAMETERS',
parameters: missing,
friendlyMessage: `You have to pass path as a string to load the plugins and args[] to what will be ...unrolled as the args to the plugin's callback function.`,
});
}
if (!Array.isArray(args)) {
throw new schema_1.SchemaError({
code: 'INVALID_PARAMETERS',
parameters: ['args'],
friendlyMessage: `You have to pass args[] as an array to what will be ...unrolled as the args to the plugin's callback function.`,
});
}
//@ts-ignore
const lookup = disk_utility_1.default.resolvePath(...path);
if (!disk_utility_1.default.isDir(lookup)) {
throw new schema_1.SchemaError({
code: 'INVALID_PARAMETERS',
parameters: ['path'],
friendlyMessage: `I couldn't find the directory at ${lookup}.`,
});
}
const query = path_1.default.join(lookup, '**', '*.plugin.[t|j]s');
const results = globby_1.default.sync(query);
const pluginResults = [];
for (const match of results) {
const imported = require(match).default;
if (typeof imported !== 'function') {
throw new SpruceError_1.default({
code: 'INVALID_PLUGIN',
file: match,
friendlyMessage: `You must export a function as the default export to ${match}.`,
});
}
pluginResults.push(imported());
}
return pluginResults;
},
};
exports.default = pluginUtil;
;