CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-js-fire

Automatically generates command-line interfaces from JavaScript objects and functions

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

js-fire

js-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.

Package Information

  • Package Name: js-fire
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install js-fire

Core Imports

const fire = require('js-fire');

For ES modules:

import fire from 'js-fire';

Basic Usage

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: 8

Architecture

js-fire is built around several key components:

  • Core Fire Function: Main entry point that analyzes input and creates CLI interface
  • Argument Parser: Uses minimist to parse command-line arguments and match them to function parameters
  • Object Navigator: Handles nested object structures for creating hierarchical subcommands
  • Function Introspector: Analyzes function signatures to extract parameter names and default values
  • Help System: Automatically generates help text and usage instructions
  • Interactive Mode: Provides autocomplete and interactive prompts for exploring APIs
  • Error Handling: Clear error messages with suggestions for typos and missing commands

Capabilities

Main Fire Function

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.com

CLI Binary

Standalone 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 -- --help

Automatic Features

Help Generation

Automatically generates comprehensive help text for all commands and functions.

  • --help or -h: Shows detailed help with available commands and parameters
  • Help includes function signatures, default values, and descriptions
  • Nested object commands show hierarchical structure

Command Aliases:

/**
 * Built-in command line flag aliases
 */
const aliases = {
  h: 'help',
  i: 'interactive'
};

Interactive Mode

Provides interactive exploration of APIs with autocomplete and prompts.

  • --interactive or -i: Enables interactive mode
  • Autocomplete for available commands and subcommands
  • Interactive prompts for function parameters with default values
  • Perfect for exploring unfamiliar APIs

Error Handling with Suggestions

Smart error handling with typo detection and command suggestions.

Special Object Properties

/**
 * 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 descriptions

Command Line Features

Flag Parsing

Automatic conversion of function parameters to command-line flags.

  • Parameters become --paramName=value flags
  • Positional arguments supported: command arg1 arg2
  • Boolean flags: --verbose (sets to true)
  • Default values shown in help text

Nested Commands

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=value

Argument Types

Automatic handling of different parameter types and conversions.

  • Strings: Direct usage or quoted strings
  • Numbers: Automatic conversion from string input
  • Booleans: true/false strings or flag presence
  • Objects: JSON string parsing for complex parameters
  • Arrays: Repeated flags or JSON arrays

Types

/**
 * 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';
}

Error Handling

js-fire includes comprehensive error handling with helpful messages and custom error classes (defined in Types):

Error Types and Messages:

  • CommandNotFoundError: Thrown when a subcommand is not found, includes suggestions for typos
  • FlagNotFoundError: Thrown when an unknown flag is used, includes suggestions for similar flags
  • InvariantViolationError: Thrown when input is neither a function nor object
  • NotFunctionError: Thrown when function introspection fails

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 parameters

Advanced Usage Patterns

Module Exploration

Use 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"

Custom CLI Applications

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);
}

Integration with Existing Code

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

docs

index.md

tile.json