npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@hediet/cli

v0.6.3

Published

A CLI library for TypeScript and NodeJS.

Downloads

1,639

Readme

A CLI Library for NodeJS/TypeScript

Not production ready, but working towards it. Until then, it can safely be used for hobby projects. Uses semantic versioning.

Features

  • Unopinionated - Does not enforce some folder structure or other architecture decisions.
  • Works with ts-node or plain compiled files using tsc.
  • Lightweight - Only has a small API surface and no feature bloat.
  • Fully typed - Every parameter has a static type arguments are validated against.
  • Fully reflective - A help text is generated automatically.
  • Embedded GUI - Use --cli::gui to launch an html based GUI which assists with specifying arguments.

Installation

Use the following command to install the library using yarn:

yarn add @hediet/cli

Usage

This example demonstrates most of the API:

import {
	types,
	runDefaultCli,
	cliInfoFromPackageJson,
	namedParam,
	positionalParam,
	createDefaultCli,
} from "@hediet/cli";
import { join } from "path";

// An arbitrary type.
interface CmdData {
	run(): Promise<void>;
}

const cli = createDefaultCli<CmdData>()
	// Defines a command with name `print`
	.addCmd({
		name: "print",
		description: "Prints selected files.",
		// In `open --mode=read-only foo.txt`, `foo.txt` would be a positional argument.
		positionalParams: [
			positionalParam("files", types.arrayOf(types.string), {
				description: "The files to print.",
			}),
		],
		// In `open --mode read-only`, `read-only` would be a named argument,
		// if `mode` is a parameter that accepts at least one argument.
		// Otherwise, `read-only` would be a positional argument.
		namedParams: {
			onlyFileNames: namedParam(types.booleanFlag, {
				// use either `--onlyFileNames` or `-n`
				shortName: "n",
				description: "Only print filenames",
			}),
			count: namedParam(types.int, {
				description: "The count",
			}),
		},
		// `args` is fully typed.
		getData: args => ({
			// Synchronously return an instance of `CmdData` here.
			async run() {
				for (const f of args.files) {
					if (args.onlyFileNames) {
						console.log(f);
					} else {
						console.log(f + " content");
					}
				}
			},
		}),
	});

// Processes command line arguments
// and invokes the handler with data obtained from `getData` of the selected command.
// Also processes `--help`, `--version` and other global flags.
runDefaultCli({
	info: cliInfoFromPackageJson(join(__dirname, "./package.json")),
	cli,
	// Asynchronously process an instance of `CmdData` here as you like.
	dataHandler: data => data.run(),
});

CLI Syntax

The parser accepts the following EBNF for a single part (PART):

PART ::= ("--"|"/") PARAM_NAME ("=" VALUE)?
			| "-" SHORT_PARAM_NAME ("=" VALUE)?
			| "-" SHORT_PARAM_NAME+
			| POSITIONAL_SEPERATOR
			| VALUE

POSITIONAL_SEPERATOR ::= "--"
SHORT_PARAM_NAME ::= [a-zA-Z_:]
PARAM_NAME ::= SHORT_PARAM_NAME [a-zA-Z_:0-9-]*
VALUE ::= .*

Parts are splitted by the underlying shell.

A single POSITIONAL_SEPERATOR is used to treat all following parts as value.

-abc is the same as -a -b -c. To avoid confusion, grouped parameters must not accept values.

GUI

This library uses my highly experimental libraries @hediet/semantic-json and @hediet/semantic-json-react which should not be used on their own right now. They have an incredible potential though, as this application demonstrates.

For the example above, the generated UI looks like this:

The UI can be launched with ts-node ./demo --cli::gui.

Architecture

Primary goal of this library is to process the command line arguments passed to the current process.

The user writes the command line arguments as a single string in a shell of his choice:

foo bar --baz qux quux /x=y

This string is splitted by his shell and then passed as an array of strings to the launched process (foo):

["bar", "--baz", "qux", "quux", "/x=y"]

The original process cannot reconstruct the original command line argument string as whitespaces are lost.

Parser

This string array is parsed by the Parser class. Each array item is classified as value or as parameter that might have a value:

[
	Value("bar"),
	Param("baz"),
	Value("qux"),
	Value("quux"),
	ParamWithValue("x", "y"),
];

This information is stored in ParsedCmd instances.

Assembler

ParsedCmds are transformed into an AssembledCmd by the CmdAssembler class. The assembler needs to know how many arguments a parameter can accept (NoValue, SingleValue or MultiValue). Depending on that, parts are assembled together into positional and named arguments.

If baz and x are SingleValue-parameters, the result would be:

[
	PositionalArg("bar"),
	NamedArg("baz", ["qux"]),
	PositionalArg("quux"),
	NamedArg("x", ["y"]),
];

Cmd

A Cmd defines typed parameters and can transform a ParsedCmd into user defined data by using the Assembler and type parsers.

Cli

These commands are organized in instances of the Cli class. Given a string array, it detects the specified command and asks the command to get the user defined data.

runDefaultCli

This function takes a Cli instance and executes a data handler, prints a help, the version or launches a GUI, depending on the current command line args.

TODOs

See open issues on github. Feel free to contribute and ask questions! ;)