forked from w3gh/ghost.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlugin.ts
74 lines (57 loc) · 1.81 KB
/
Plugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import {Config} from './Config';
import {resolve} from 'path';
import {createLoggerFor} from './Logger';
const {debug, info, error} = createLoggerFor('Plugin');
export interface IPlugin {
new (config: any);
}
interface LoadedPlugins {
[name: string]: Plugin;
}
export interface PluginDefinition {
}
export class Plugin {
static EVENT_ON_INIT = 'onInit';
static EVENT_ON_BNET_INIT = 'onBNetInit';
static loaded: LoadedPlugins = {};
constructor(protected config: any) {
}
static load(name, config: Config) {
if (!name) return;
const requirePath = resolve(`${__dirname}/plugins/${name}`);
let ExportedClass;
try {
ExportedClass = require(requirePath)(Plugin);
} catch (e) {
error(`failed to load plugin '${name}' by path '${requirePath}'`);
error(e);
return;
}
if (typeof ExportedClass !== 'function') {
error(`plugin '${name}' must export class or function`);
return;
}
try {
let instance = new ExportedClass(config);
if (instance instanceof Plugin) {
info(`load "${instance.constructor.name}"`);
Plugin.loaded[name] = instance;
} else {
error(`plugin '${name}' must be an instance of class "Plugin"`);
instance = null;
}
} catch (e) {
error(`${name}: `, e);
return;
}
}
static emit(eventName: string, data: any) {
Object.keys(Plugin.loaded).forEach((plugName) => {
let instance = Plugin.loaded[plugName];
if (typeof instance[eventName] === 'function') {
instance[eventName](data);
debug(`emit ${eventName}`);
}
})
}
}