-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPluginManager.ts
More file actions
128 lines (107 loc) · 3.39 KB
/
PluginManager.ts
File metadata and controls
128 lines (107 loc) · 3.39 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import { Plugin, PluginContext, Logger } from './types';
export class PluginManager {
private plugins: Plugin[] = [];
private context: PluginContext;
constructor(config: unknown, logger?: Logger) {
this.context = this.createContext(config, logger);
}
async loadPlugin(plugin: Plugin | string): Promise<void> {
const pluginInstance = typeof plugin === 'string' ? await this.resolvePlugin(plugin) : plugin;
this.plugins.push(pluginInstance);
if (pluginInstance.initialize) {
await pluginInstance.initialize(this.context);
}
this.context.logger.info(`Loaded plugin: ${pluginInstance.name}`);
}
async runHook<T>(hookName: keyof Plugin, value: T): Promise<T> {
let result = value;
for (const plugin of this.plugins) {
const hook = plugin[hookName] as ((value: T) => unknown) | undefined;
if (typeof hook !== 'function') {
continue;
}
try {
const hookResult = await hook(result);
if (hookResult !== undefined) {
result = hookResult as T;
}
} catch (error) {
this.context.logger.error(
`Error in plugin ${plugin.name} hook ${hookName}: ${String(error)}`
);
}
}
return result;
}
async cleanup(): Promise<void> {
for (const plugin of this.plugins) {
if (!plugin.cleanup) {
continue;
}
try {
await plugin.cleanup();
} catch (error) {
this.context.logger.error(`Error cleaning up plugin ${plugin.name}: ${String(error)}`);
}
}
}
private async resolvePlugin(name: string): Promise<Plugin> {
const packageName = name.startsWith('@') ? name : `@opensyntaxhq/autodocs-plugin-${name}`;
try {
const module = (await import(packageName)) as unknown;
const exported = this.getModuleExport(module);
return this.resolvePluginExport(exported);
} catch (error) {
throw new Error(`Failed to load plugin ${packageName}: ${String(error)}`, { cause: error });
}
}
private resolvePluginExport(exported: unknown): Plugin {
if (typeof exported === 'function') {
const factory = exported as () => Plugin;
return factory();
}
return exported as Plugin;
}
private getModuleExport(module: unknown): unknown {
if (module && typeof module === 'object' && 'default' in module) {
const mod = module as { default?: unknown };
return mod.default ?? module;
}
return module;
}
private createContext(config: unknown, logger?: Logger): PluginContext {
const cache = new Map<string, unknown>();
const eventHandlers = new Map<string, Array<(data: unknown) => void>>();
const defaultLogger: Logger = {
info: (msg) => {
console.log(`[INFO] ${msg}`);
},
warn: (msg) => {
console.warn(`[WARN] ${msg}`);
},
error: (msg) => {
console.error(`[ERROR] ${msg}`);
},
debug: (msg) => {
console.debug(`[DEBUG] ${msg}`);
},
};
return {
config,
logger: logger ?? defaultLogger,
cache,
emitEvent: (name, data) => {
const handlers = eventHandlers.get(name) || [];
handlers.forEach((handler) => {
handler(data);
});
},
addHook: (name, handler) => {
if (!eventHandlers.has(name)) {
eventHandlers.set(name, []);
}
eventHandlers.get(name)?.push(handler);
},
};
}
}