diff --git a/.changeset/eight-baboons-press.md b/.changeset/eight-baboons-press.md new file mode 100644 index 0000000..cbae31a --- /dev/null +++ b/.changeset/eight-baboons-press.md @@ -0,0 +1,5 @@ +--- +'@emigrate/plugin-tools': minor +--- + +Add the convenience functions `getOrLoadPlugin` and `getOrLoadPlugins` diff --git a/packages/plugin-tools/src/index.ts b/packages/plugin-tools/src/index.ts index a96e8ac..caae636 100644 --- a/packages/plugin-tools/src/index.ts +++ b/packages/plugin-tools/src/index.ts @@ -1,5 +1,11 @@ import process from 'node:process'; -import { type PluginFromType, type PluginType, type GeneratorPlugin, type StoragePlugin } from './types.js'; +import { + type PluginFromType, + type PluginType, + type GeneratorPlugin, + type StoragePlugin, + type Plugin, +} from './types.js'; export const isGeneratorPlugin = (plugin: any): plugin is GeneratorPlugin => { if (!plugin || typeof plugin !== 'object') { @@ -29,6 +35,47 @@ export const isPluginOfType = (type: T, plugin: any): plug throw new Error(`Unknown plugin type: ${type}`); }; +export const getOrLoadPlugin = async ( + type: T, + plugins: Array, +): Promise | undefined> => { + for await (const plugin of plugins) { + if (isPluginOfType(type, plugin)) { + return plugin; + } + + const loadedPlugin = typeof plugin === 'string' ? await loadPlugin(type, plugin) : undefined; + + if (loadedPlugin) { + return loadedPlugin; + } + } + + return undefined; +}; + +export const getOrLoadPlugins = async ( + type: T, + plugins: Array, +): Promise>> => { + const result: Array> = []; + + for await (const plugin of plugins) { + if (isPluginOfType(type, plugin)) { + result.push(plugin); + continue; + } + + const loadedPlugin = typeof plugin === 'string' ? await loadPlugin(type, plugin) : undefined; + + if (loadedPlugin) { + result.push(loadedPlugin); + } + } + + return result; +}; + export const loadPlugin = async ( type: T, plugin: string,