(
plugins: PluginRecords,
pluginName: string,
options: LoadPluginOptions | boolean = {},
)
| 49 | } |
| 50 | |
| 51 | export default async function loadPlugin( |
| 52 | plugins: PluginRecords, |
| 53 | pluginName: string, |
| 54 | options: LoadPluginOptions | boolean = {}, |
| 55 | ): Promise<PluginRecords> { |
| 56 | const normalized = normalizeOptions(options); |
| 57 | const { debug = false, searchPaths = [] } = normalized; |
| 58 | |
| 59 | for (const searchPath of searchPaths) { |
| 60 | if (typeof searchPath !== "string" || !path.isAbsolute(searchPath)) { |
| 61 | throw new Error(`Invalid searchPath "${searchPath}": must be an absolute path`); |
| 62 | } |
| 63 | if (!fs.existsSync(searchPath)) { |
| 64 | throw new Error(`Invalid searchPath "${searchPath}": directory does not exist`); |
| 65 | } |
| 66 | if (!fs.statSync(searchPath).isDirectory()) { |
| 67 | throw new Error(`Invalid searchPath "${searchPath}": must be a directory, not a file`); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | const longName = normalizePackageName(pluginName); |
| 72 | const shortName = getShorthandName(longName); |
| 73 | |
| 74 | if (pluginName.match(/\s+/u)) { |
| 75 | throw new WhitespacePluginError(pluginName, { |
| 76 | pluginName: longName, |
| 77 | }); |
| 78 | } |
| 79 | |
| 80 | const pluginKey = longName === pluginName ? shortName : pluginName; |
| 81 | |
| 82 | if (!plugins[pluginKey]) { |
| 83 | let plugin: Plugin | undefined; |
| 84 | let resolvedPath: string | undefined; |
| 85 | |
| 86 | // Try to load from npx cache directories using require.resolve |
| 87 | const npxResolvedPath = resolveFromNpxCache(longName); |
| 88 | if (npxResolvedPath) { |
| 89 | try { |
| 90 | plugin = await dynamicImport<Plugin>(npxResolvedPath); |
| 91 | resolvedPath = npxResolvedPath; |
| 92 | } catch (err) { |
| 93 | if (debug) { |
| 94 | console.debug( |
| 95 | `Failed to load plugin ${longName} from npx cache: ${(err as Error).message}`, |
| 96 | ); |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | // Try to load from additional search paths (extended config's node_modules) |
| 102 | if (!plugin) { |
| 103 | for (const searchPath of searchPaths) { |
| 104 | try { |
| 105 | resolvedPath = require.resolve(longName, { paths: [searchPath] }); |
| 106 | plugin = await dynamicImport<Plugin>(resolvedPath); |
| 107 | break; |
| 108 | } catch (err) { |
no test coverage detected