-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
PluginDriver.ts
390 lines (361 loc) · 12.9 KB
/
PluginDriver.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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import type Chunk from '../Chunk';
import type Graph from '../Graph';
import type Module from '../Module';
import type {
AddonHookFunction,
AsyncPluginHooks,
EmitFile,
FirstPluginHooks,
NormalizedInputOptions,
NormalizedOutputOptions,
OutputBundleWithPlaceholders,
OutputPluginHooks,
ParallelPluginHooks,
Plugin,
PluginContext,
PluginHooks,
PluginValueHooks,
SequentialPluginHooks,
SerializablePluginCache,
SyncPluginHooks
} from '../rollup/types';
import { FileEmitter } from './FileEmitter';
import { getPluginContext } from './PluginContext';
import { errInputHookInOutputPlugin, error } from './error';
import { throwPluginError } from './pluginUtils';
/**
* Get the inner type from a promise
* @example ResolveValue<Promise<string>> -> string
*/
type ResolveValue<T> = T extends Promise<infer K> ? K : T;
/**
* Coerce a promise union to always be a promise.
* @example EnsurePromise<string | Promise<string>> -> Promise<string>
*/
type EnsurePromise<T> = Promise<ResolveValue<T>>;
/**
* Get the type of the first argument in a function.
* @example Arg0<(a: string, b: number) => void> -> string
*/
type Arg0<H extends keyof PluginHooks> = Parameters<PluginHooks[H]>[0];
// This will make sure no input hook is omitted
type Subtract<T, U> = T extends U ? never : T;
const inputHookNames: {
[P in Subtract<keyof PluginHooks, keyof OutputPluginHooks>]: 1;
} = {
buildEnd: 1,
buildStart: 1,
closeBundle: 1,
closeWatcher: 1,
load: 1,
moduleParsed: 1,
options: 1,
resolveDynamicImport: 1,
resolveId: 1,
shouldTransformCachedModule: 1,
transform: 1,
watchChange: 1
};
const inputHooks = Object.keys(inputHookNames);
export type ReplaceContext = (context: PluginContext, plugin: Plugin) => PluginContext;
function throwInvalidHookError(hookName: string, pluginName: string): never {
return error({
code: 'INVALID_PLUGIN_HOOK',
message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.`
});
}
export type HookAction = [plugin: string, hook: string, args: unknown[]];
export class PluginDriver {
public readonly emitFile: EmitFile;
public finaliseAssets: () => void;
public getFileName: (fileReferenceId: string) => string;
public readonly setChunkInformation: (facadeChunkByModule: ReadonlyMap<Module, Chunk>) => void;
public readonly setOutputBundle: (
outputBundle: OutputBundleWithPlaceholders,
outputOptions: NormalizedOutputOptions
) => void;
private readonly fileEmitter: FileEmitter;
private readonly pluginCache: Record<string, SerializablePluginCache> | undefined;
private readonly pluginContexts: ReadonlyMap<Plugin, PluginContext>;
private readonly plugins: readonly Plugin[];
private readonly unfulfilledActions = new Set<HookAction>();
constructor(
private readonly graph: Graph,
private readonly options: NormalizedInputOptions,
userPlugins: readonly Plugin[],
pluginCache: Record<string, SerializablePluginCache> | undefined,
basePluginDriver?: PluginDriver
) {
this.pluginCache = pluginCache;
this.fileEmitter = new FileEmitter(
graph,
options,
basePluginDriver && basePluginDriver.fileEmitter
);
this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
this.plugins = (basePluginDriver ? basePluginDriver.plugins : []).concat(userPlugins);
const existingPluginNames = new Set<string>();
this.pluginContexts = new Map(
this.plugins.map(plugin => [
plugin,
getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
])
);
if (basePluginDriver) {
for (const plugin of userPlugins) {
for (const hook of inputHooks) {
if (hook in plugin) {
options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
}
}
}
}
}
public createOutputPluginDriver(plugins: readonly Plugin[]): PluginDriver {
return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
}
getUnfulfilledHookActions(): Set<HookAction> {
return this.unfulfilledActions;
}
// chains, first non-null result stops and returns
hookFirst<H extends AsyncPluginHooks & FirstPluginHooks>(
hookName: H,
args: Parameters<PluginHooks[H]>,
replaceContext?: ReplaceContext | null,
skipped?: ReadonlySet<Plugin> | null
): EnsurePromise<ReturnType<PluginHooks[H]>> {
let promise: EnsurePromise<ReturnType<PluginHooks[H]>> = Promise.resolve(undefined as any);
for (const plugin of this.plugins) {
if (skipped && skipped.has(plugin)) continue;
promise = promise.then(result => {
if (result != null) return result;
return this.runHook(hookName, args, plugin, false, replaceContext);
});
}
return promise;
}
// chains synchronously, first non-null result stops and returns
hookFirstSync<H extends SyncPluginHooks & FirstPluginHooks>(
hookName: H,
args: Parameters<PluginHooks[H]>,
replaceContext?: ReplaceContext
): ReturnType<PluginHooks[H]> {
for (const plugin of this.plugins) {
const result = this.runHookSync(hookName, args, plugin, replaceContext);
if (result != null) return result;
}
return null as any;
}
// parallel, ignores returns
hookParallel<H extends AsyncPluginHooks & ParallelPluginHooks>(
hookName: H,
args: Parameters<PluginHooks[H]>,
replaceContext?: ReplaceContext
): Promise<void> {
const promises: Promise<void>[] = [];
for (const plugin of this.plugins) {
const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
if (!hookPromise) continue;
promises.push(hookPromise);
}
return Promise.all(promises).then(() => {});
}
// chains, reduces returned value, handling the reduced value as the first hook argument
hookReduceArg0<H extends AsyncPluginHooks & SequentialPluginHooks>(
hookName: H,
[arg0, ...rest]: Parameters<PluginHooks[H]>,
reduce: (
reduction: Arg0<H>,
result: ResolveValue<ReturnType<PluginHooks[H]>>,
plugin: Plugin
) => Arg0<H>,
replaceContext?: ReplaceContext
): Promise<Arg0<H>> {
let promise = Promise.resolve(arg0);
for (const plugin of this.plugins) {
promise = promise.then(arg0 => {
const args = [arg0, ...rest] as Parameters<PluginHooks[H]>;
const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
if (!hookPromise) return arg0;
return hookPromise.then(result =>
reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin)
);
});
}
return promise;
}
// chains synchronously, reduces returned value, handling the reduced value as the first hook argument
hookReduceArg0Sync<H extends SyncPluginHooks & SequentialPluginHooks>(
hookName: H,
[arg0, ...rest]: Parameters<PluginHooks[H]>,
reduce: (reduction: Arg0<H>, result: ReturnType<PluginHooks[H]>, plugin: Plugin) => Arg0<H>,
replaceContext?: ReplaceContext
): Arg0<H> {
for (const plugin of this.plugins) {
const args = [arg0, ...rest] as Parameters<PluginHooks[H]>;
const result = this.runHookSync(hookName, args, plugin, replaceContext);
arg0 = reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin);
}
return arg0;
}
// chains, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
hookReduceValue<H extends PluginValueHooks, T>(
hookName: H,
initialValue: T | Promise<T>,
args: Parameters<AddonHookFunction>,
reduce: (
reduction: T,
result: ResolveValue<ReturnType<AddonHookFunction>>,
plugin: Plugin
) => T,
replaceContext?: ReplaceContext
): Promise<T> {
let promise = Promise.resolve(initialValue);
for (const plugin of this.plugins) {
promise = promise.then(value => {
const hookPromise = this.runHook(hookName, args, plugin, true, replaceContext);
if (!hookPromise) return value;
return hookPromise.then(result =>
reduce.call(this.pluginContexts.get(plugin), value, result, plugin)
);
});
}
return promise;
}
// chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
hookReduceValueSync<H extends SyncPluginHooks & SequentialPluginHooks, T>(
hookName: H,
initialValue: T,
args: Parameters<PluginHooks[H]>,
reduce: (reduction: T, result: ReturnType<PluginHooks[H]>, plugin: Plugin) => T,
replaceContext?: ReplaceContext
): T {
let acc = initialValue;
for (const plugin of this.plugins) {
const result = this.runHookSync(hookName, args, plugin, replaceContext);
acc = reduce.call(this.pluginContexts.get(plugin), acc, result, plugin);
}
return acc;
}
// chains, ignores returns
hookSeq<H extends AsyncPluginHooks & SequentialPluginHooks>(
hookName: H,
args: Parameters<PluginHooks[H]>,
replaceContext?: ReplaceContext
): Promise<void> {
let promise = Promise.resolve();
for (const plugin of this.plugins) {
promise = promise.then(
() => this.runHook(hookName, args, plugin, false, replaceContext) as Promise<void>
);
}
return promise;
}
/**
* Run an async plugin hook and return the result.
* @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.
* @param args Arguments passed to the plugin hook.
* @param plugin The actual pluginObject to run.
* @param permitValues If true, values can be passed instead of functions for the plugin hook.
* @param hookContext When passed, the plugin context can be overridden.
*/
private runHook<H extends PluginValueHooks>(
hookName: H,
args: Parameters<AddonHookFunction>,
plugin: Plugin,
permitValues: true,
hookContext?: ReplaceContext | null
): EnsurePromise<ReturnType<AddonHookFunction>>;
private runHook<H extends AsyncPluginHooks>(
hookName: H,
args: Parameters<PluginHooks[H]>,
plugin: Plugin,
permitValues: false,
hookContext?: ReplaceContext | null
): EnsurePromise<ReturnType<PluginHooks[H]>>;
private runHook<H extends AsyncPluginHooks>(
hookName: H,
args: Parameters<PluginHooks[H]>,
plugin: Plugin,
permitValues: boolean,
hookContext?: ReplaceContext | null
): EnsurePromise<ReturnType<PluginHooks[H]>> {
const hook = plugin[hookName];
if (!hook) return undefined as any;
let context = this.pluginContexts.get(plugin)!;
if (hookContext) {
context = hookContext(context, plugin);
}
let action: [string, string, Parameters<any>] | null = null;
return Promise.resolve()
.then(() => {
// permit values allows values to be returned instead of a functional hook
if (typeof hook !== 'function') {
if (permitValues) return hook;
return throwInvalidHookError(hookName, plugin.name);
}
// eslint-disable-next-line @typescript-eslint/ban-types
const hookResult = (hook as Function).apply(context, args);
if (!hookResult || !hookResult.then) {
// short circuit for non-thenables and non-Promises
return hookResult;
}
// Track pending hook actions to properly error out when
// unfulfilled promises cause rollup to abruptly and confusingly
// exit with a successful 0 return code but without producing any
// output, errors or warnings.
action = [plugin.name, hookName, args];
this.unfulfilledActions.add(action);
// Although it would be more elegant to just return hookResult here
// and put the .then() handler just above the .catch() handler below,
// doing so would subtly change the defacto async event dispatch order
// which at least one test and some plugins in the wild may depend on.
return Promise.resolve(hookResult).then(result => {
// action was fulfilled
this.unfulfilledActions.delete(action!);
return result;
});
})
.catch(err => {
if (action !== null) {
// action considered to be fulfilled since error being handled
this.unfulfilledActions.delete(action);
}
return throwPluginError(err, plugin.name, { hook: hookName });
});
}
/**
* Run a sync plugin hook and return the result.
* @param hookName Name of the plugin hook. Must be in `PluginHooks`.
* @param args Arguments passed to the plugin hook.
* @param plugin The acutal plugin
* @param hookContext When passed, the plugin context can be overridden.
*/
private runHookSync<H extends SyncPluginHooks>(
hookName: H,
args: Parameters<PluginHooks[H]>,
plugin: Plugin,
hookContext?: ReplaceContext
): ReturnType<PluginHooks[H]> {
const hook = plugin[hookName];
if (!hook) return undefined as any;
let context = this.pluginContexts.get(plugin)!;
if (hookContext) {
context = hookContext(context, plugin);
}
try {
// permit values allows values to be returned instead of a functional hook
if (typeof hook !== 'function') {
return throwInvalidHookError(hookName, plugin.name);
}
// eslint-disable-next-line @typescript-eslint/ban-types
return (hook as Function).apply(context, args);
} catch (err: any) {
return throwPluginError(err, plugin.name, { hook: hookName });
}
}
}