techdocs-cli: fix dynamic imports

Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
Patrik Oldsberg
2025-01-16 17:05:07 +01:00
parent 59a8f430c7
commit 69f84ac4f8
2 changed files with 27 additions and 10 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@techdocs/cli': patch
---
Internal update to work with dynamic imports.
+22 -10
View File
@@ -81,7 +81,7 @@ export function registerCommands(program: Command) {
false,
)
.alias('build')
.action(lazy(() => import('./generate/generate').then(m => m.default)));
.action(lazy(() => import('./generate/generate'), 'default'));
program
.command('migrate')
@@ -143,7 +143,7 @@ export function registerCommands(program: Command) {
'25',
)
.option('-v --verbose', 'Enable verbose output.', false)
.action(lazy(() => import('./migrate/migrate').then(m => m.default)));
.action(lazy(() => import('./migrate/migrate'), 'default'));
program
.command('publish')
@@ -225,7 +225,7 @@ export function registerCommands(program: Command) {
'Path of the directory containing generated files to publish',
'./site/',
)
.action(lazy(() => import('./publish/publish').then(m => m.default)));
.action(lazy(() => import('./publish/publish'), 'default'));
program
.command('serve:mkdocs')
@@ -254,7 +254,7 @@ export function registerCommands(program: Command) {
)
.option('-p, --port <PORT>', 'Port to serve documentation locally', '8000')
.option('-v --verbose', 'Enable verbose output.', false)
.action(lazy(() => import('./serve/mkdocs').then(m => m.default)));
.action(lazy(() => import('./serve/mkdocs'), 'default'));
program
.command('serve')
@@ -323,21 +323,33 @@ export function registerCommands(program: Command) {
);
}
})
.action(lazy(() => import('./serve/serve').then(m => m.default)));
.action(lazy(() => import('./serve/serve'), 'default'));
}
// Wraps an action function so that it always exits and handles errors
// Humbly taken from backstage-cli's registerCommands
function lazy(
getActionFunc: () => Promise<(...args: any[]) => Promise<void>>,
type ActionFunc = (...args: any[]) => Promise<void>;
type ActionExports<TModule extends object> = {
[KName in keyof TModule as TModule[KName] extends ActionFunc
? KName
: never]: TModule[KName];
};
// Wraps an action function so that it always exits and handles errors
export function lazy<TModule extends object>(
moduleLoader: () => Promise<TModule>,
exportName: keyof ActionExports<TModule>,
): (...args: any[]) => Promise<never> {
return async (...args: any[]) => {
try {
const actionFunc = await getActionFunc();
const mod = await moduleLoader();
const actualModule = (
mod as unknown as { default: ActionExports<TModule> }
).default;
const actionFunc = actualModule[exportName] as ActionFunc;
await actionFunc(...args);
process.exit(0);
} catch (error) {
// eslint-disable-next-line no-console
console.error(error.message);
process.exit(1);
}