refactor(backend-dynamic-feature-service): allow passing an async module loader in the DynamicPluginsFeatureLoaderOptions.

Signed-off-by: David Festal <dfestal@redhat.com>
This commit is contained in:
David Festal
2024-10-07 13:33:44 +02:00
parent d18d4942f9
commit 4c89e4759d
3 changed files with 16 additions and 8 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/backend-dynamic-feature-service': patch
---
Allow passing an async module loader in the `DynamicPluginsFeatureLoaderOptions`.
@@ -18,7 +18,11 @@ import { LoggerService } from '@backstage/backend-plugin-api';
import path from 'path';
export class CommonJSModuleLoader implements ModuleLoader {
constructor(public readonly logger: LoggerService) {}
private module: any;
constructor(public readonly logger: LoggerService) {
this.module = require('node:module');
}
async bootstrap(
backstageRoot: string,
@@ -28,9 +32,8 @@ export class CommonJSModuleLoader implements ModuleLoader {
const dynamicNodeModulesPaths = [
...dynamicPluginsPaths.map(p => path.resolve(p, 'node_modules')),
];
const Module = require('module');
const oldNodeModulePaths = Module._nodeModulePaths;
Module._nodeModulePaths = (from: string): string[] => {
const oldNodeModulePaths = this.module._nodeModulePaths;
this.module._nodeModulePaths = (from: string): string[] => {
const result: string[] = oldNodeModulePaths(from);
if (!dynamicPluginsPaths.some(p => from.startsWith(p))) {
return result;
@@ -49,6 +52,6 @@ export class CommonJSModuleLoader implements ModuleLoader {
}
async load(packagePath: string): Promise<any> {
return await require(/* webpackIgnore: true */ packagePath);
return await this.module.prototype.require(packagePath);
}
}
@@ -88,7 +88,7 @@ export class DynamicPluginManager implements DynamicPluginProvider {
),
);
moduleLoader.bootstrap(backstageRoot, dynamicPluginsPaths);
await moduleLoader.bootstrap(backstageRoot, dynamicPluginsPaths);
scanner.subscribeToRootDirectoryChange(async () => {
manager._availablePackages = (await scanner.scanRoot()).packages;
@@ -262,7 +262,7 @@ export const dynamicPluginsServiceRef = createServiceRef<DynamicPluginProvider>(
* @public
*/
export interface DynamicPluginsFactoryOptions {
moduleLoader?(logger: LoggerService): ModuleLoader;
moduleLoader?(logger: LoggerService): ModuleLoader | Promise<ModuleLoader>;
}
/**
@@ -283,7 +283,7 @@ export const dynamicPluginsServiceFactoryWithOptions = (
config,
logger,
preferAlpha: true,
moduleLoader: options?.moduleLoader?.(logger),
moduleLoader: await options?.moduleLoader?.(logger),
});
},
});