89 lines
3.1 KiB
JavaScript
89 lines
3.1 KiB
JavaScript
"use strict";
|
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.loadPlugin = loadPlugin;
|
|
const path_1 = __importDefault(require("path"));
|
|
const resolve_1 = __importDefault(require("resolve"));
|
|
const immutable_1 = __importDefault(require("immutable"));
|
|
const promise_1 = __importDefault(require("../utils/promise"));
|
|
const error_1 = __importDefault(require("../utils/error"));
|
|
const timing_1 = __importDefault(require("../utils/timing"));
|
|
const validatePlugin_1 = __importDefault(require("./validatePlugin"));
|
|
const plugin_1 = __importDefault(require("../models/plugin"));
|
|
// Return true if an error is a "module not found"
|
|
// Wait on https://github.com/substack/node-resolve/pull/81 to be merged
|
|
function isModuleNotFound(err) {
|
|
return err.code == "MODULE_NOT_FOUND" || err.message.indexOf("Cannot find module") >= 0;
|
|
}
|
|
/**
|
|
Load a plugin in a book
|
|
|
|
@param {Book} book
|
|
@param {PluginDependency[]} plugin
|
|
@param {string} pkgPath (optional)
|
|
@return {Promise<Plugin>}
|
|
*/
|
|
function loadPlugin(book, plugin) {
|
|
const logger = book.getLogger();
|
|
const name = plugin.getName();
|
|
let pkgPath = plugin.getPath();
|
|
// Try loading plugins from different location
|
|
let p = (0, promise_1.default)()
|
|
.then(() => {
|
|
let packageContent;
|
|
let packageMain;
|
|
let content;
|
|
// Locate plugin and load package.json
|
|
try {
|
|
const res = resolve_1.default.sync("./package.json", { basedir: pkgPath });
|
|
pkgPath = path_1.default.dirname(res);
|
|
packageContent = require(res);
|
|
}
|
|
catch (err) {
|
|
if (!isModuleNotFound(err))
|
|
throw err;
|
|
packageContent = undefined;
|
|
content = undefined;
|
|
return;
|
|
}
|
|
// Locate the main package
|
|
try {
|
|
const indexJs = path_1.default.normalize(packageContent.main || "index.js");
|
|
packageMain = resolve_1.default.sync(`./${indexJs}`, { basedir: pkgPath });
|
|
}
|
|
catch (err) {
|
|
if (!isModuleNotFound(err))
|
|
throw err;
|
|
packageMain = undefined;
|
|
}
|
|
// Load plugin JS content
|
|
if (packageMain) {
|
|
try {
|
|
content = require(packageMain);
|
|
}
|
|
catch (err) {
|
|
throw new error_1.default.PluginError(err, {
|
|
plugin: name
|
|
});
|
|
}
|
|
}
|
|
// Update plugin
|
|
return new plugin_1.default({
|
|
name: name,
|
|
version: packageContent.version || "*",
|
|
path: pkgPath,
|
|
package: immutable_1.default.fromJS(packageContent),
|
|
content: immutable_1.default.fromJS(content || {})
|
|
});
|
|
})
|
|
.then((plugin) => (0, validatePlugin_1.default)(plugin))
|
|
.then((plugin) => {
|
|
logger.info(`plugin "${plugin.get("name")}" is loaded\n`);
|
|
return plugin;
|
|
});
|
|
p = timing_1.default.measure("plugin.load", p);
|
|
return p;
|
|
}
|