@tsed/cli-core
Version:
Build your CLI with TypeScript and Decorators
50 lines (49 loc) • 2.05 kB
JavaScript
import { constant, inject, injectable } from "@tsed/di";
import { $asyncEmit } from "@tsed/hooks";
import chalk from "chalk";
import { PackageManagersModule } from "../packageManagers/PackageManagersModule.js";
import { loadPlugins } from "../utils/loadPlugins.js";
import { NpmRegistryClient } from "./NpmRegistryClient.js";
import { ProjectPackageJson } from "./ProjectPackageJson.js";
function mapPlugins({ package: { name, description = "", ...otherProps } }) {
return {
name: `${name} ${description}`.trim(),
value: name,
...otherProps
};
}
export class CliPlugins {
constructor() {
this.name = constant("name", "");
this.loadPlugins = loadPlugins;
this.npmRegistryClient = inject(NpmRegistryClient);
this.packageJson = inject(ProjectPackageJson);
this.packageManagers = inject(PackageManagersModule);
}
async searchPlugins(keyword = "", options = {}) {
const result = await this.npmRegistryClient.search(this.getKeyword(keyword), options);
return result.filter(({ package: { name } }) => this.isPlugin(name)).map(mapPlugins);
}
addPluginsDependencies(ctx) {
const plugins = Object.keys(this.packageJson.devDependencies).filter((name) => this.isPlugin(name));
const tasks = plugins.map((plugin) => {
return {
title: `Run plugin '${chalk.cyan(plugin)}'`,
task: () => {
return $asyncEmit("$onAddPlugin", [plugin, ctx]);
}
};
});
return [...tasks, this.packageManagers.task("Install dependencies", ctx)];
}
getKeyword(keyword) {
return `@${this.name}/cli-plugin-${this.cleanKeyword(keyword)}`;
}
cleanKeyword(keyword) {
return keyword.replace(this.name, "").replace("@", "").replace("/", "").replace("cli-plugin-", "");
}
isPlugin(name) {
return name.startsWith(`@${this.name}/cli-plugin`) || name.includes(`${this.name}-cli-plugin`);
}
}
injectable(CliPlugins);