-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathPluginInterface.ts
More file actions
201 lines (188 loc) · 7.75 KB
/
Copy pathPluginInterface.ts
File metadata and controls
201 lines (188 loc) · 7.75 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import type { Plugin } from './interfaces';
import { LogLevel, createLogger } from './logging';
import type { Logger } from './logging';
/*
* we use `Required` everywhere here because we expect that the methods on plugin objects will
* be optional, and we don't want to deal with `undefined`.
* `extends (...args: any[]) => any` determines whether the thing we're dealing with is a function.
* Returning `never` in the `as` clause of the `[key in object]` step deletes that key from the
* resultant object.
* on the right-hand side of the mapped type we are forced to use a conditional type a second time,
* in order to be able to use the `Parameters` utility type on `Required<T>[K]`. This will always
* be true because of the filtering done by the `[key in object]` clause, but TS requires the duplication.
*
* so put together: we iterate over all of the fields in T, deleting ones which are not (potentially
* optional) functions. For the ones that are, we replace them with their parameters.
*
* this returns the type of an object whose keys are the names of the methods of T and whose values
* are tuples containing the arguments that each method accepts.
*/
export type PluginEventArgs<T> = {
[K in keyof Required<T> as Required<T>[K] extends (...args: any[]) => any ? K : never]:
Required<T>[K] extends (...args: any[]) => any ? Parameters<Required<T>[K]> : never
};
export default class PluginInterface<T extends Plugin = Plugin> {
constructor(
plugins?: Plugin[],
options?: {
logger?: Logger;
suppressErrors?: boolean;
}
) {
this.logger = options?.logger;
this.suppressErrors = (options as any)?.suppressErrors === false ? false : true;
for (const plugin of plugins ?? []) {
this.add(plugin);
}
if (!this.logger) {
this.logger = createLogger();
}
if (!this.logger) {
this.logger = createLogger();
}
}
private plugins: Plugin[] = [];
private logger: Logger;
/**
* Should plugin errors cause the program to fail, or should they be caught and simply logged
*/
private suppressErrors: boolean | undefined;
/**
* Call `event` on plugins
*/
public emit<K extends keyof PluginEventArgs<T> & string>(event: K, ...args: PluginEventArgs<T>[K]) {
this.logger.debug(`Emitting plugin event: ${event}`);
for (let plugin of this.plugins) {
if ((plugin as any)[event]) {
try {
this.logger?.time(LogLevel.debug, [plugin.name, event], () => {
(plugin as any)[event](...args);
});
} catch (err) {
this.logger?.error(`Error when calling plugin ${plugin.name}.${event}:`, (err as Error).stack);
if (!this.suppressErrors) {
throw err;
}
}
}
}
return args[0];
}
/**
* Call `event` on plugins, but allow the plugins to return promises that will be awaited before the next plugin is notified
*/
public async emitAsync<K extends keyof PluginEventArgs<T> & string>(event: K, ...args: PluginEventArgs<T>[K]): Promise<PluginEventArgs<T>[K][0]> {
this.logger.debug(`Emitting async plugin event: ${event}`);
for (let plugin of this.plugins) {
if ((plugin as any)[event]) {
try {
await this.logger?.time(LogLevel.debug, [plugin.name, event], async () => {
await Promise.resolve(
(plugin as any)[event](...args)
);
});
} catch (err) {
this.logger?.error(`Error when calling plugin ${plugin.name}.${event}:`, (err as Error).stack);
if (!this.suppressErrors) {
throw err;
}
}
}
}
return args[0];
}
/**
* Add a plugin to the beginning of the list of plugins
*/
public addFirst<T extends Plugin = Plugin>(plugin: T) {
if (!this.has(plugin)) {
this.plugins.unshift(plugin);
}
return plugin;
}
/**
* Add a plugin to the end of the list of plugins
*/
public add<T extends Plugin = Plugin>(plugin: T) {
if (!this.has(plugin)) {
this.sanitizePlugin(plugin);
this.plugins.push(plugin);
}
return plugin;
}
/**
* Find deprecated or removed historic plugin hooks, and warn about them.
* Some events can be forwards-converted
*/
private sanitizePlugin(plugin: Plugin) {
const removedHooks = [
'beforePrepublish',
'afterPrepublish'
];
for (const removedHook of removedHooks) {
if (plugin[removedHook]) {
this.logger?.error(`Plugin "${plugin.name}": event ${removedHook} is no longer supported and will never be called`);
}
}
const upgradeWithWarn = {
beforePublish: 'beforeSerializeProgram',
afterPublish: 'afterSerializeProgram',
beforeProgramTranspile: 'beforeBuildProgram',
afterProgramTranspile: 'afterBuildProgram',
beforeFileParse: 'beforeProvideFile',
afterFileParse: 'afterProvideFile',
beforeFileTranspile: 'beforePrepareFile',
afterFileTranspile: 'afterPrepareFile',
beforeFileDispose: 'beforeRemoveFile',
afterFileDispose: 'afterRemoveFile',
beforeProgramCreate: 'beforeProvideProgram',
afterProgramCreate: 'afterProvideProgram',
beforeProgramValidate: 'beforeValidateProgram',
onProgramValidate: 'validateProgram',
beforeProgramDispose: 'beforeRemoveProgram',
afterScopeCreate: 'afterProvideScope',
beforeScopeDispose: 'beforeRemoveScope',
onScopeDispose: 'removeScope',
afterScopeDispose: 'afterRemoveScope',
beforeScopeValidate: 'beforeValidateScope',
onScopeValidate: 'validateScope',
afterScopeValidate: 'afterValidateScope',
onGetCodeActions: 'provideCodeActions',
onGetSemanticTokens: 'provideSemanticTokens',
beforeFileAdd: 'beforeAddFile',
afterFileAdd: 'afterAddFile',
beforeFileRemove: 'beforeRemoveFile',
afterFileRemove: 'afterRemoveFile',
beforeFileValidate: 'beforeValidateFile',
onFileValidate: 'validateFile',
afterFileValidate: 'afterValidateFile',
onSerializeProgram: 'serializeProgram',
onGetSourceFixAllCodeActions: 'provideSourceFixAllCodeActions'
};
for (const [oldEvent, newEvent] of Object.entries(upgradeWithWarn)) {
if (plugin[oldEvent]) {
if (!plugin[newEvent]) {
plugin[newEvent] = plugin[oldEvent];
this.logger?.warn(`Plugin '${plugin.name}': event '${oldEvent}' is no longer supported. It has been converted to '${newEvent}' but you may encounter issues as their signatures may not match.`);
} else {
this.logger?.warn(`Plugin "${plugin.name}": event '${oldEvent}' is no longer supported and will never be called`);
}
}
}
}
public has(plugin: Plugin) {
return this.plugins.includes(plugin);
}
public remove<T extends Plugin = Plugin>(plugin: T) {
if (this.has(plugin)) {
this.plugins.splice(this.plugins.indexOf(plugin), 1);
}
return plugin;
}
/**
* Remove all plugins
*/
public clear() {
this.plugins = [];
}
}