Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@tsed/cli-core

Package Overview
Dependencies
Maintainers
0
Versions
335
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@tsed/cli-core

Build your CLI with TypeScript and Decorators

  • 5.4.3
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
0
Created
Source

@tsed/cli-core

Ts.ED logo

Build & Release TypeScript Package Quality npm version Dependencies img img Known Vulnerabilities

Create your CLI with TypeScript and decorators

Goals

This package help TypeScript developers to build your own CLI with class and decorators. To doing that, @tsed/cli-core use the Ts.ED DI and his utils to declare a new Command via decorators.

@tsed/cli-core provide also a plugin ready architecture. You and your community will be able to develop your official cli-plugin and deploy it on npm registry.

Features

  • DI Framework (injection, configuration, etc...),
  • Decorators,
  • Extensible with plugins architecture.

Please refer to the documentation for more details.

Installation

npm install @tsed/core @tsed/di @tsed/cli-core

Getting started

Create CLI require some steps like create a package.json with the right information and create a structure directory aligned with TypeScript to be compiled correctly for a npm deployment.

Here a structure directory example:

.
├── lib -- Transpiled code
├── src -- TypeScript source
│   ├── bin -- binary
│   ├── commands
│   └── index.ts
├── templates -- Template files
├── package.json
├── tsconfig.json 
└── tsconfig.compile.json 

Create package.json and tsconfig

The first step is to create the package.json with the following lines:

{
  "name": "{{name}}",
  "version": "1.0.0",
  "main": "./lib/index.js",
  "typings": "./lib/index.d.ts",
  "bin": {
    "tsed": "lib/bin/{{name}}.js"
  },
  "files": [
    "lib/bin/{{name}}.js",
    "lib/bin",
    "lib",
    "templates"
  ],
  "description": "An awesome CLI build on top of @tsed/cli-core",
  "dependencies": {
    "@tsed/cli-core": "1.3.1",
    "tslib": "1.11.1"
  },
  "devDependencies": {
    "@tsed/cli-testing": "1.3.1",
    "ts-node": "latest",
    "typescript": "latest"
  },
  "scripts": {
    "build": "tsc --build tsconfig.compile.json",
    "start:cmd:add": "cross-env NODE_ENV=development ts-node -r src/bin/{{name}}.ts add -r ./.tmp"
  },
  "engines": {
    "node": ">=8.9"
  },
  "peerDependencies": {}
}

Then create tsconfig files one for the IDE (tsconfig.json):

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2016",
    "sourceMap": true,
    "declaration": false,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": "node",
    "isolatedModules": false,
    "suppressImplicitAnyIndexErrors": false,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "allowSyntheticDefaultImports": true,
    "importHelpers": true,
    "newLine": "LF",
    "noEmit": true,
    "lib": [
      "es7",
      "dom",
      "esnext.asynciterable"
    ],
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
  "linterOptions": {
    "exclude": [
    ]
  },
  "exclude": [
  ]
}

And another one to compile source (tsconfig.compile.json):

{
  "extends": "./tsconfig.compile.json",
  "compilerOptions": {
    "rootDir": "src",
    "outDir": "lib",
    "moduleResolution": "node",
    "declaration": true,
    "noResolve": false,
    "preserveConstEnums": true,
    "sourceMap": true,
    "noEmit": false,
    "inlineSources": true
  },
  "exclude": [
    "node_modules",
    "test",
    "lib",
    "**/*.spec.ts"
  ]
}

Create the bin file

The bin file is used by npm to create your node.js executable program when you install the node_module globally.

Create a new file according to your project name (example: name.ts) and add this code:

#!/usr/bin/env node
import {AddCmd, CliCore} from "@tsed/cli-core";
import {resolve} from "path";

const pkg = require("../../package.json");
const TEMPLATE_DIR = resolve(__dirname, "..", "..", "templates");

CliCore
  .bootstrap({
    commands: [
      AddCmd, // CommandProvider to install a plugin
      // then add you commands
    ],
    
    // optionals
    name: "name", // replace by the cli name. This property will be used by Plugins command
    pkg,
    templateDir: TEMPLATE_DIR
  })
  .catch(console.error)

Create your first command

import {
  Command,
  CommandProvider,
  ClassNamePipe,
  OutputFilePathPipe,
  Inject,
  RoutePipe,
  SrcRendererService
} from "@tsed/cli-core";

export interface GenerateCmdContext {
  type: string;
  name: string;
}

@Command({
  name: "generate",
  description: "Generate a new provider class",
  args: {
    type: {
      description: "Type of the provider (Injectable, Controller, Pipe, etc...)",
      type: String
    },
    name: {
      description: "Name of the class",
      type: String
    }
  }
})
export class GenerateCmd implements CommandProvider {
  @Inject()
  classNamePipe: ClassNamePipe;

  @Inject()
  outputFilePathPipe: OutputFilePathPipe;

  @Inject()
  routePipe: RoutePipe;

  @Inject()
  srcRenderService: SrcRendererService;

  /**
   * Prompt use Inquirer.js to print questions (see Inquirer.js for more details)
   */
  $prompt(initialOptions: Partial<GenerateCmdContext>) {
    return [
      {
        type: "list",
        name: "type",
        message: "Which type of provider ?",
        default: initialOptions.type,
        when: !initialOptions.type,
        choices: ["injectable", "decorator"]
      },
      {
        type: "input",
        name: "name",
        message: "Which name ?",
        when: !initialOptions.name
      }
    ];
  }

  /**
   * Map context is called before $exec and map use answers.
   * This context will be given for your $exec method and will be forwarded to other plugins
   */
  $mapContext(ctx: Partial<GenerateCmdContext>): GenerateCmdContext {
    const {name = "", type = ""} = ctx;

    return {
      ...ctx,
      symbolName: this.classNamePipe.transform({name, type}),
      outputFile: `${this.outputFilePathPipe.transform({name, type})}.ts`
    } as IGenerateCmdContext;
  }

  /**
   * Perform action like generate files. The tasks returned by $exec method is based on Listr configuration (see Listr documentation on npm)
   */
  async $exec(options: GenerateCmdContext) {
    const {outputFile, ...data} = options;

    const template = `generate/${options.type}.hbs`;

    return [
      {
        title: `Generate ${options.type} file to '${outputFile}'`,
        task: () =>
          this.srcRenderService.render(template, data, {
            output: outputFile
          })
      }
    ];
  }
}

Finally, create a handlebars template in templates directory:

import {Injectable} from "@tsed/di";

@Injectable()
export class {{symbolName}} {

}

Run command in dev mode

In your package.json add the following line in scripts property:

{
  "start:cmd:generate": "cross-env NODE_ENV=development ts-node -r src/bin/{{name}}.ts generate -r ./.tmp"
}

Note: replace {{name}} by the name of you bin file located in src/bin.

Note 2: The option -r ./.tmp create a temporary directory to generate files with your command.

More examples

Here other commands examples:

Contributors

Please read contributing guidelines here

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

The MIT License (MIT)

Copyright (c) 2016 - 2023 Romain Lenzotti

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Keywords

FAQs

Package last updated on 24 Sep 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc