@storm-stack/plugin-system
Version:
A library used to create and manage a plugin-styled architecture in a TypeScript application.
50 lines (49 loc) • 1.61 kB
JavaScript
import { StormDateTime } from "@storm-stack/date-time";
import { StormError } from "@storm-stack/errors";
import { PluginSystemErrorCode } from "../errors.mjs";
import { createResolver } from "../utilities/create-resolver.mjs";
export class PluginLoader {
constructor(rootPath, tsconfig, autoInstall) {
this.rootPath = rootPath;
this.tsconfig = tsconfig;
this.autoInstall = autoInstall;
this.resolver = createResolver(tsconfig);
}
resolver;
load = async (definition, options = {}) => {
const module = await this.resolve(definition, options);
if (!this.isValid(module)) {
throw new StormError(PluginSystemErrorCode.plugin_loading_failure, {
message: `The plugin module "${definition.provider}" does not contain the required exports.`
});
}
return this.instantiate(definition, module, definition.provider, options);
};
// eslint-disable-next-line class-methods-use-this
isValid = (module) => {
if (!module) {
return false;
}
return true;
};
instantiate = (definition, module, resolvedPath, options = {}) => {
const instance = {
loader: this,
definition,
module,
options,
resolvedPath,
executionDateTime: StormDateTime.minimum()
};
return instance;
};
resolve = async (definition, _ = {}) => {
const resolved = await this.resolver(definition.provider);
if (!resolved) {
throw new StormError(PluginSystemErrorCode.plugin_loading_failure, {
message: `Cannot find plugin ${definition.provider}`
});
}
return await import(resolved);
};
}