Security News
Cloudflare Adds Security.txt Setup Wizard
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
bandersnatch
Advanced tools
[![npm](https://img.shields.io/npm/v/bandersnatch)](https://www.npmjs.com/package/bandersnatch) [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/hongaar/bandersnatch/ci)](https://github.com/hongaar/bandersnatch/actions?query=workf
Super lightweight and friendly CLI framework for Node.js.
🚧 alpha version
yargs
& inquirer
It's built in TypeScript and while it's of course possible to write your app with JavaScript, you're missing out on some very handy type hints.
We don't have a generator, auto-updater and we don't make any decisions for you (apart from using inquirer for prompts). This makes bandersnatch pretty easy and intuitive to work with.
# Add dependency
yarn add bandersnatch
Now create a simple app echo.ts
:
import { program, command } from 'bandersnatch'
const echo = command('echo', 'Echo something in the terminal')
.argument('words', 'Say some kind words', { variadic: true })
.action(args => args.words.map(word => `${word}!`).join(' '))
program()
.default(echo)
.run()
And run with:
$ ts-node echo.ts Hello world
Hello! world!
👆 Assuming you have ts-node
installed.
Let's dive right into some more features. This simple app has a single default command which pretty prints JSON input. When invoked without input, it'll show an interactive prompt:
import { program, command } from 'bandersnatch'
const app = program('JSON pretty printer').default(
command()
.argument('json', 'Raw JSON input as string')
.option('color', 'Enables colorized output', { type: 'boolean' })
.action(async args => {
const json = JSON.parse(args.json)
args.color
? console.dir(json)
: console.log(JSON.stringify(json, undefined, 4))
})
)
process.argv.slice(2).length ? app.run() : app.repl()
And run with:
$ ts-node pretty.ts
> [0,1,1,2,3,5]
[
0,
1,
1,
2,
3,
5
]
Now, try typing [0,1,1,2,3,5] --c
and then hit TAB
. 😊
Bandersnatch can also ask a user for input if arguments were not provided on the command line:
import { program, command } from 'bandersnatch'
const cmd = command()
.argument('name', "What's your name?", {
prompt: true
})
.argument('question', "What's your question?", {
prompt: true
})
.action(args => `Hi ${args.name}, the answer to "${args.question}" is 42.`)
program('Ask me anything')
.default(cmd)
.run()
And run with:
$ ts-node ama.ts --name Joram
? What's your question? What is everything in ASCII?
Hi Joram, the answer to "What is everything in ASCII?" is 42.
When you omit the --name
part, the program will also prompt for it.
ℹ More examples in the examples directory.
All methods are chainable unless the docs mention otherwise.
program(description)
Creates a new program.
program.add(command)
Adds a command to the program.
program().add(command(...))
program.default(command)
Adds a default command to the program. Shorthand for:
program().add(command(...).default())
program.prompt(prompt)
Use this prompt prefix (string, required) when in REPL mode.
program.withHelp()
Adds help
and --help
to program which displays program usage information.
program.withVersion()
Adds version
and --version
to program which displays program version from
package.json.
program.fail(function)
Use custom error handler. Function will be called with 4 arguments:
program.eval(command)
Uses process.argv or passed in command (string, optional) to match and execute command. Returns runner instance.
program()
.add(command(...))
.eval()
program.run(command)
Shorthand for eval().print()
.
program()
.add(command(...))
.run()
program.repl()
Start a read-eval-print loop.
program()
.add(command(...))
.repl()
command(name, description)
Creates a new command.
command.argument(name, description, options)
Adds a positional argument to the command.
optional
(boolean) makes this argument optional.variadic
(boolean) eagerly take all remaining arguments and parse as array.
Only valid for last argument.command.option(name, description, options)
Adds an option to the command.
alias
(string or array of strings) alias(es) for the option key.command.command(command)
Adds a sub-command to the command.
command.default()
Mark command as default. Default commands are executed immediately and don't require a name.
command.action(function)
Function to execute when command is invoked. Is called with one argument: an object containing key/value pairs of parsed arguments and options.
runner
Returned from program().eval()
, can't be invoked directly.
runner.print(printer)
Prints resolved and rejected command executions to the terminal. Uses the built-in printer if invoked without arguments.
const runner = program()
.default(
command().action(() => {
throw new Error('Test customer printer')
})
)
.eval()
runner.print({
write(str: any) {
str && console.log(str)
},
error(error: any) {
console.error(`${red('‼')} ${bgRed(error)}`)
}
})
runner.then(function)
Function is invoked when command handler resolves.
runner.catch(function)
Function is invoked when command handler rejects.
runner.print(printer)
Attaches a printer to the runner. Uses a default printer unless called with a custom printer argument.
printer
Used by runner, can't be invoked directly.
printer.write(string)
Handles output. Prints to stdout by default.
printer.error(Error)
Handles errors. Prints stack trace to stderr by default.
There are many options to bundle your application for distribution. We'll discuss a common pattern.
ℹ An example can be found in the examples/bundle directory.
Init a package.json
if needed:
mkdir echo && cd echo
yarn init
Install dependencies:
yarn add bandersnatch
yarn add typescript pkg --dev
And create an example app in src/cli.ts
:
import { program, command } from 'bandersnatch'
export default program()
.withHelp()
.default(
command('echo', 'Echo something in the terminal')
.argument('words', 'Say some kind words', { variadic: true })
.action(console.log)
)
Building your app with TypeScript is very powerful, but runtime compilation is slow so we compile the code ahead of time.
Add a tsconfig.json
, similar to:
{
"include": ["./src"],
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"lib": ["es2017"],
"declaration": true,
"outDir": "lib",
"rootDir": "src",
"strict": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"moduleResolution": "node"
}
}
Add these scripts to your package.json
:
{
"name": "echo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
+ "scripts": {
+ "prepublishOnly": "yarn build",
+ "build": "tsc",
+ },
"dependencies": {
"bandersnatch": "^1.0.0-alpha.2"
},
"devDependencies": {
"pkg": "^4.4.2",
"typescript": "^3.7.3"
}
}
And compile now by running yarn build
.
Next, we need to create a simple entrypoint echo.js
, which can be run with
node:
#!/usr/bin/env node
require('./lib/cli').default.run()
To run your app, users may want to run yarn global add echo
. For this to
work, we need to make a small adjustment to package.json
:
{
"name": "echo",
"version": "1.0.0",
- "main": "index.js",
+ "bin": "echo.js",
+ "files": [
+ "lib"
+ ],
"license": "MIT",
"scripts": {
"prepublishOnly": "yarn build",
"build": "tsc",
},
"dependencies": {
"bandersnatch": "^1.0.0-alpha.2"
},
"devDependencies": {
"pkg": "^4.4.2",
"typescript": "^3.7.3"
}
}
You can now npm publish
.
To create a binary (your app with Node.js bundled), add this script to
package.json
:
{
"name": "echo",
"version": "1.0.0",
"bin": "echo.js",
"files": [
"lib"
],
"license": "MIT",
"scripts": {
"prepublishOnly": "yarn build",
"build": "tsc",
+ "bundle": "yarn build && pkg -t host ."
},
"dependencies": {
"bandersnatch": "^1.0.0-alpha.2"
},
"devDependencies": {
"pkg": "^4.4.2",
"typescript": "^3.7.3"
}
}
👆 Omit -t host
to create binaries for all platforms.
Run yarn bundle
and then ./echo --help
. 💪
Optionally deploy to GitHub, S3, etc. using your preferred CD method if needed.
Contributions are very welcome. Please note this project is in a very early stage and the roadmap is a bit foggy still...
# Clone and install
git clone git@github.com:hongaar/bandersnatch.git
cd bandersnatch
yarn
# Run an example
yarn start examples/simple.ts
Please use conventional commits.
Copyright (c) 2019 Joram van den Boezem. Licensed under the MIT license.
Inspired by vorpal
FAQs
Simple TypeScript CLI / REPL framework
The npm package bandersnatch receives a total of 316 weekly downloads. As such, bandersnatch popularity was classified as not popular.
We found that bandersnatch demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
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.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.
Security News
ENISA’s 2024 report highlights the EU’s top cybersecurity threats, including rising DDoS attacks, ransomware, supply chain vulnerabilities, and weaponized AI.