Automatically generates command-line interfaces from JavaScript objects and functions
npx @tessl/cli install tessl/npm-js-fire@1.0.0js-fire is a JavaScript implementation of Google's Python Fire library for automatically generating command-line interfaces (CLIs) from JavaScript objects and functions. It provides a simple way to create CLIs, explore existing code through command-line interfaces, and bridge the gap between Bash and JavaScript development workflows.
npm install js-fireconst fire = require('js-fire');For ES modules:
import fire from 'js-fire';const fire = require('js-fire');
// Basic function example
function greet(name = 'World', greeting = 'Hello') {
return `${greeting}, ${name}!`;
}
fire(greet);
// Command line: node script.js --name=Alice --greeting=Hi
// Output: Hi, Alice!
// Object with subcommands example
const calculator = {
__description__: 'A simple calculator',
add: (a, b) => Number(a) + Number(b),
subtract: (a, b) => Number(a) - Number(b),
multiply: (a, b) => Number(a) * Number(b),
utils: {
double: (n) => Number(n) * 2,
square: (n) => Number(n) ** 2
}
};
fire(calculator);
// Command line: node script.js add --a=5 --b=3
// Output: 8
// Command line: node script.js utils double --n=4
// Output: 8js-fire is built around several key components:
Creates a command-line interface from JavaScript objects or functions with automatic argument parsing, help generation, and interactive exploration.
/**
* Creates a CLI from a JavaScript object or function
* @param {object|function} input - The object or function to convert to CLI
* @param {object} [argv] - Parsed arguments (defaults to process.argv via minimist)
* @returns {Promise<void>} - Resolves when CLI execution completes, exits process on error
*/
function fire(input, argv);Usage Examples:
const fire = require('js-fire');
// Function example
const processFile = (filename, format = 'json', verbose = false) => {
console.log(`Processing ${filename} as ${format}${verbose ? ' (verbose)' : ''}`);
};
fire(processFile);
// Command line: node script.js --filename=data.txt --format=csv --verbose=true
// Object example with nested commands
const api = {
__description__: 'API management tools',
users: {
list: (limit = 10) => `Listing ${limit} users`,
create: (name, email) => `Creating user: ${name} (${email})`,
delete: (id) => `Deleting user ${id}`
},
config: {
set: (key, value) => `Setting ${key} = ${value}`,
get: (key) => `Getting ${key}`
}
};
fire(api);
// Command line: node script.js users list --limit=20
// Command line: node script.js users create --name=John --email=john@example.comStandalone command-line tool for creating CLIs from Node.js modules without modifying the original code.
/**
* CLI binary function that loads and fires external modules
* @param {string} modulePath - Path to the module to load and fire
* @returns {Promise<void>} - Resolves when CLI execution completes
*
* Usage: js-fire modulePath -- [command] [flags]
* Binary command: js-fire
*/
async function createCLI(modulePath);Usage Examples:
# Use with built-in Node.js modules
js-fire fs -- writeFileSync --path=hello.txt --data="Hello World"
# Use with custom modules
js-fire ./my-module.js -- myFunction --param=value
# Interactive exploration
js-fire fs -- --interactive
# Help for any module
js-fire lodash -- --helpAutomatically generates comprehensive help text for all commands and functions.
--help or -h: Shows detailed help with available commands and parametersCommand Aliases:
/**
* Built-in command line flag aliases
*/
const aliases = {
h: 'help',
i: 'interactive'
};Provides interactive exploration of APIs with autocomplete and prompts.
--interactive or -i: Enables interactive modeSmart error handling with typo detection and command suggestions.
/**
* Special property for adding descriptions to objects and functions
* @type {string}
*/
__description__: string;Usage Example:
const tools = {
__description__: 'Development utilities',
build: () => 'Building project...',
test: () => 'Running tests...',
deploy: {
__description__: 'Deployment commands',
staging: () => 'Deploying to staging...',
production: () => 'Deploying to production...'
}
};
fire(tools);
// Help text will include the descriptionsAutomatic conversion of function parameters to command-line flags.
--paramName=value flagscommand arg1 arg2--verbose (sets to true)Support for unlimited nesting levels in object hierarchies.
const deep = {
level1: {
level2: {
level3: {
action: (param) => `Deep action with ${param}`
}
}
}
};
fire(deep);
// Command line: node script.js level1 level2 level3 action --param=valueAutomatic handling of different parameter types and conversions.
true/false strings or flag presence/**
* Main fire function signature
*/
interface FireFunction {
(input: object | Function, argv?: ParsedArguments): Promise<void>;
}
/**
* Parsed command line arguments (from minimist)
*/
interface ParsedArguments {
_: string[];
[key: string]: any;
}
/**
* Custom error classes thrown by js-fire
*/
class CommandNotFoundError extends Error {
constructor(message: string);
name: 'CommandNotFound';
}
class FlagNotFoundError extends Error {
constructor(message: string);
name: 'FlagNotFound';
}
class InvariantViolationError extends Error {
constructor(message: string);
name: 'InvariantViolationError';
}
class NotFunctionError extends Error {
constructor(message: string);
name: 'NotFunctionError';
}js-fire includes comprehensive error handling with helpful messages and custom error classes (defined in Types):
Error Types and Messages:
Example Error Messages:
// Command not found with suggestions (CommandNotFoundError)
// Error: Command 'usr' not found
// Did you mean: users ?
// Flag not found with suggestions (FlagNotFoundError)
// Error: Flag 'nam' not found
// Did you mean: name ?
// Invalid input type (InvariantViolationError)
// Error: Input must be a function or object
// Function introspection failure (NotFunctionError)
// Error: Unable to parse function parametersUse js-fire to explore and interact with existing Node.js modules:
// Explore the fs module
fire(require('fs'));
// Interactive: js-fire fs -- --interactive
// Help: js-fire fs -- --help
// Explore lodash utilities
fire(require('lodash'));
// Command: js-fire lodash -- map --collection=[1,2,3] --iteratee="n => n * 2"Build complete CLI applications with nested command structures:
const cli = {
__description__: 'My CLI Application',
database: {
__description__: 'Database operations',
migrate: (direction = 'up') => `Running ${direction} migrations`,
seed: (file) => `Seeding from ${file}`,
backup: (path = './backup') => `Backing up to ${path}`
},
server: {
__description__: 'Server management',
start: (port = 3000, env = 'development') => {
console.log(`Starting server on port ${port} in ${env} mode`);
},
stop: () => 'Stopping server',
restart: () => 'Restarting server'
},
utils: {
__description__: 'Utility functions',
clean: (target = 'all') => `Cleaning ${target}`,
version: () => require('./package.json').version
}
};
if (require.main === module) {
fire(cli);
}Convert existing JavaScript functions into CLI tools without modification:
// existing-utils.js
exports.processData = (input, format = 'json', validate = true) => {
// existing logic
return processedData;
};
exports.generateReport = (data, template = 'default') => {
// existing logic
return report;
};
// cli-wrapper.js
const utils = require('./existing-utils');
const fire = require('js-fire');
fire(utils);
// Now callable as: node cli-wrapper.js processData --input=data.csv --format=xml