-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRunPlugins.mjs
81 lines (69 loc) · 2.41 KB
/
RunPlugins.mjs
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
import { breadcrumbContext } from "./BreadcrumbContext.mjs";
import { validate } from "schema-utils";
import pluginSchema from "./PluginSchema.mjs";
import availableHooksContext from "./AvailableHooksContext.mjs";
export const getHook = (hookSymbol, defaultValue = undefined) => {
// the first element is the latest version of the hook that overrode the others in the array
return availableHooksContext.getStore().get(hookSymbol)?.[ 0 ] ?? defaultValue;
};
/**
* Looks up hookSymbol
* If the hook isn't defined, uses defaultImplementation
*
* Calls that function with args
* Returns the result
*
* @param hookSymbol
* @param defaultImplementation
* @param args
* @returns {*}
*/
export const getHookFnResult = (hookSymbol, defaultImplementation = undefined, args = []) => {
const oldStore = availableHooksContext.getStore();
const existingHookList = oldStore.get(hookSymbol);
// create a new hook list for this call that includes the defaultImplementation
const newHookList = [
...existingHookList ?? [],
defaultImplementation,
];
const newStore = new Map(oldStore);
newStore.set(hookSymbol, newHookList);
const value = newHookList[ 0 ];
return availableHooksContext.run(newStore, () =>
value(...args)
);
}
const runPlugins = async plugins => {
const hooks = availableHooksContext.getStore() ?? new Map();
const breadcrumb = breadcrumbContext.getStore();
const breadcrumbStr = breadcrumb.map(symbol => symbol.description).join("/");
for (const plugin of plugins) {
// validate the shape of the plugin object
validate(pluginSchema, plugin, { name: `${breadcrumbStr}/${plugin.name}` });
// register the plugin's hooks
// keep a list of previous registrations of the same hook so that the one that gets called can call the others if it chooses
plugin.hooks?.forEach(
(callback, key) => hooks.set(key,
// unshifts callback, returning the new array
[ callback, ...(hooks.get(key) || []) ]
)
);
}
console.info("buildConfig validated plugins and registered hooks");
return await availableHooksContext.run(hooks, async () => {
let config;
for (const plugin of plugins) {
if (plugin.main) {
console.info(`${breadcrumbStr} calling plugin ${plugin.name}`);
config = await breadcrumbContext.run([ ...breadcrumb, plugin.crumb ], async () =>
await plugin.main(config)
);
}
else {
// this plugin only registers hooks
}
}
return config;
});
};
export default runPlugins;