Skip to content

Commit

Permalink
feat(plugin-tools): add convenience functions getOrLoadPlugin and get…
Browse files Browse the repository at this point in the history
…OrLoadPlugins
  • Loading branch information
joakimbeng committed Nov 15, 2023
1 parent 81fde2e commit 23a323c
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/eight-baboons-press.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@emigrate/plugin-tools': minor
---

Add the convenience functions `getOrLoadPlugin` and `getOrLoadPlugins`
49 changes: 48 additions & 1 deletion packages/plugin-tools/src/index.ts
Original file line number Diff line number Diff line change
@@ -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') {
Expand Down Expand Up @@ -29,6 +35,47 @@ export const isPluginOfType = <T extends PluginType>(type: T, plugin: any): plug
throw new Error(`Unknown plugin type: ${type}`);
};

export const getOrLoadPlugin = async <T extends PluginType>(
type: T,
plugins: Array<Plugin | string>,
): Promise<PluginFromType<T> | 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 <T extends PluginType>(
type: T,
plugins: Array<Plugin | string>,
): Promise<Array<PluginFromType<T>>> => {
const result: Array<PluginFromType<T>> = [];

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 <T extends PluginType>(
type: T,
plugin: string,
Expand Down

0 comments on commit 23a323c

Please sign in to comment.