Automatically generates command-line interfaces from JavaScript objects and functions
npx @tessl/cli install tessl/npm-js-fire@1.0.00
# js-fire
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: js-fire
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install js-fire`
10
11
## Core Imports
12
13
```javascript
14
const fire = require('js-fire');
15
```
16
17
For ES modules:
18
19
```javascript
20
import fire from 'js-fire';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const fire = require('js-fire');
27
28
// Basic function example
29
function greet(name = 'World', greeting = 'Hello') {
30
return `${greeting}, ${name}!`;
31
}
32
33
fire(greet);
34
// Command line: node script.js --name=Alice --greeting=Hi
35
// Output: Hi, Alice!
36
37
// Object with subcommands example
38
const calculator = {
39
__description__: 'A simple calculator',
40
add: (a, b) => Number(a) + Number(b),
41
subtract: (a, b) => Number(a) - Number(b),
42
multiply: (a, b) => Number(a) * Number(b),
43
utils: {
44
double: (n) => Number(n) * 2,
45
square: (n) => Number(n) ** 2
46
}
47
};
48
49
fire(calculator);
50
// Command line: node script.js add --a=5 --b=3
51
// Output: 8
52
// Command line: node script.js utils double --n=4
53
// Output: 8
54
```
55
56
## Architecture
57
58
js-fire is built around several key components:
59
60
- **Core Fire Function**: Main entry point that analyzes input and creates CLI interface
61
- **Argument Parser**: Uses minimist to parse command-line arguments and match them to function parameters
62
- **Object Navigator**: Handles nested object structures for creating hierarchical subcommands
63
- **Function Introspector**: Analyzes function signatures to extract parameter names and default values
64
- **Help System**: Automatically generates help text and usage instructions
65
- **Interactive Mode**: Provides autocomplete and interactive prompts for exploring APIs
66
- **Error Handling**: Clear error messages with suggestions for typos and missing commands
67
68
## Capabilities
69
70
### Main Fire Function
71
72
Creates a command-line interface from JavaScript objects or functions with automatic argument parsing, help generation, and interactive exploration.
73
74
```javascript { .api }
75
/**
76
* Creates a CLI from a JavaScript object or function
77
* @param {object|function} input - The object or function to convert to CLI
78
* @param {object} [argv] - Parsed arguments (defaults to process.argv via minimist)
79
* @returns {Promise<void>} - Resolves when CLI execution completes, exits process on error
80
*/
81
function fire(input, argv);
82
```
83
84
**Usage Examples:**
85
86
```javascript
87
const fire = require('js-fire');
88
89
// Function example
90
const processFile = (filename, format = 'json', verbose = false) => {
91
console.log(`Processing ${filename} as ${format}${verbose ? ' (verbose)' : ''}`);
92
};
93
94
fire(processFile);
95
// Command line: node script.js --filename=data.txt --format=csv --verbose=true
96
97
// Object example with nested commands
98
const api = {
99
__description__: 'API management tools',
100
users: {
101
list: (limit = 10) => `Listing ${limit} users`,
102
create: (name, email) => `Creating user: ${name} (${email})`,
103
delete: (id) => `Deleting user ${id}`
104
},
105
config: {
106
set: (key, value) => `Setting ${key} = ${value}`,
107
get: (key) => `Getting ${key}`
108
}
109
};
110
111
fire(api);
112
// Command line: node script.js users list --limit=20
113
// Command line: node script.js users create --name=John --email=john@example.com
114
```
115
116
### CLI Binary
117
118
Standalone command-line tool for creating CLIs from Node.js modules without modifying the original code.
119
120
```javascript { .api }
121
/**
122
* CLI binary function that loads and fires external modules
123
* @param {string} modulePath - Path to the module to load and fire
124
* @returns {Promise<void>} - Resolves when CLI execution completes
125
*
126
* Usage: js-fire modulePath -- [command] [flags]
127
* Binary command: js-fire
128
*/
129
async function createCLI(modulePath);
130
```
131
132
**Usage Examples:**
133
134
```bash
135
# Use with built-in Node.js modules
136
js-fire fs -- writeFileSync --path=hello.txt --data="Hello World"
137
138
# Use with custom modules
139
js-fire ./my-module.js -- myFunction --param=value
140
141
# Interactive exploration
142
js-fire fs -- --interactive
143
144
# Help for any module
145
js-fire lodash -- --help
146
```
147
148
### Automatic Features
149
150
#### Help Generation
151
152
Automatically generates comprehensive help text for all commands and functions.
153
154
- `--help` or `-h`: Shows detailed help with available commands and parameters
155
- Help includes function signatures, default values, and descriptions
156
- Nested object commands show hierarchical structure
157
158
**Command Aliases:**
159
160
```javascript { .api }
161
/**
162
* Built-in command line flag aliases
163
*/
164
const aliases = {
165
h: 'help',
166
i: 'interactive'
167
};
168
```
169
170
#### Interactive Mode
171
172
Provides interactive exploration of APIs with autocomplete and prompts.
173
174
- `--interactive` or `-i`: Enables interactive mode
175
- Autocomplete for available commands and subcommands
176
- Interactive prompts for function parameters with default values
177
- Perfect for exploring unfamiliar APIs
178
179
#### Error Handling with Suggestions
180
181
Smart error handling with typo detection and command suggestions.
182
183
#### Special Object Properties
184
185
```javascript { .api }
186
/**
187
* Special property for adding descriptions to objects and functions
188
* @type {string}
189
*/
190
__description__: string;
191
```
192
193
**Usage Example:**
194
195
```javascript
196
const tools = {
197
__description__: 'Development utilities',
198
build: () => 'Building project...',
199
test: () => 'Running tests...',
200
deploy: {
201
__description__: 'Deployment commands',
202
staging: () => 'Deploying to staging...',
203
production: () => 'Deploying to production...'
204
}
205
};
206
207
fire(tools);
208
// Help text will include the descriptions
209
```
210
211
### Command Line Features
212
213
#### Flag Parsing
214
215
Automatic conversion of function parameters to command-line flags.
216
217
- Parameters become `--paramName=value` flags
218
- Positional arguments supported: `command arg1 arg2`
219
- Boolean flags: `--verbose` (sets to true)
220
- Default values shown in help text
221
222
#### Nested Commands
223
224
Support for unlimited nesting levels in object hierarchies.
225
226
```javascript
227
const deep = {
228
level1: {
229
level2: {
230
level3: {
231
action: (param) => `Deep action with ${param}`
232
}
233
}
234
}
235
};
236
237
fire(deep);
238
// Command line: node script.js level1 level2 level3 action --param=value
239
```
240
241
#### Argument Types
242
243
Automatic handling of different parameter types and conversions.
244
245
- **Strings**: Direct usage or quoted strings
246
- **Numbers**: Automatic conversion from string input
247
- **Booleans**: `true`/`false` strings or flag presence
248
- **Objects**: JSON string parsing for complex parameters
249
- **Arrays**: Repeated flags or JSON arrays
250
251
## Types
252
253
```javascript { .api }
254
/**
255
* Main fire function signature
256
*/
257
interface FireFunction {
258
(input: object | Function, argv?: ParsedArguments): Promise<void>;
259
}
260
261
/**
262
* Parsed command line arguments (from minimist)
263
*/
264
interface ParsedArguments {
265
_: string[];
266
[key: string]: any;
267
}
268
269
/**
270
* Custom error classes thrown by js-fire
271
*/
272
class CommandNotFoundError extends Error {
273
constructor(message: string);
274
name: 'CommandNotFound';
275
}
276
277
class FlagNotFoundError extends Error {
278
constructor(message: string);
279
name: 'FlagNotFound';
280
}
281
282
class InvariantViolationError extends Error {
283
constructor(message: string);
284
name: 'InvariantViolationError';
285
}
286
287
class NotFunctionError extends Error {
288
constructor(message: string);
289
name: 'NotFunctionError';
290
}
291
```
292
293
## Error Handling
294
295
js-fire includes comprehensive error handling with helpful messages and custom error classes (defined in [Types](#types)):
296
297
**Error Types and Messages:**
298
299
- **CommandNotFoundError**: Thrown when a subcommand is not found, includes suggestions for typos
300
- **FlagNotFoundError**: Thrown when an unknown flag is used, includes suggestions for similar flags
301
- **InvariantViolationError**: Thrown when input is neither a function nor object
302
- **NotFunctionError**: Thrown when function introspection fails
303
304
**Example Error Messages:**
305
306
```javascript
307
// Command not found with suggestions (CommandNotFoundError)
308
// Error: Command 'usr' not found
309
// Did you mean: users ?
310
311
// Flag not found with suggestions (FlagNotFoundError)
312
// Error: Flag 'nam' not found
313
// Did you mean: name ?
314
315
// Invalid input type (InvariantViolationError)
316
// Error: Input must be a function or object
317
318
// Function introspection failure (NotFunctionError)
319
// Error: Unable to parse function parameters
320
```
321
322
## Advanced Usage Patterns
323
324
### Module Exploration
325
326
Use js-fire to explore and interact with existing Node.js modules:
327
328
```javascript
329
// Explore the fs module
330
fire(require('fs'));
331
// Interactive: js-fire fs -- --interactive
332
// Help: js-fire fs -- --help
333
334
// Explore lodash utilities
335
fire(require('lodash'));
336
// Command: js-fire lodash -- map --collection=[1,2,3] --iteratee="n => n * 2"
337
```
338
339
### Custom CLI Applications
340
341
Build complete CLI applications with nested command structures:
342
343
```javascript
344
const cli = {
345
__description__: 'My CLI Application',
346
347
database: {
348
__description__: 'Database operations',
349
migrate: (direction = 'up') => `Running ${direction} migrations`,
350
seed: (file) => `Seeding from ${file}`,
351
backup: (path = './backup') => `Backing up to ${path}`
352
},
353
354
server: {
355
__description__: 'Server management',
356
start: (port = 3000, env = 'development') => {
357
console.log(`Starting server on port ${port} in ${env} mode`);
358
},
359
stop: () => 'Stopping server',
360
restart: () => 'Restarting server'
361
},
362
363
utils: {
364
__description__: 'Utility functions',
365
clean: (target = 'all') => `Cleaning ${target}`,
366
version: () => require('./package.json').version
367
}
368
};
369
370
if (require.main === module) {
371
fire(cli);
372
}
373
```
374
375
### Integration with Existing Code
376
377
Convert existing JavaScript functions into CLI tools without modification:
378
379
```javascript
380
// existing-utils.js
381
exports.processData = (input, format = 'json', validate = true) => {
382
// existing logic
383
return processedData;
384
};
385
386
exports.generateReport = (data, template = 'default') => {
387
// existing logic
388
return report;
389
};
390
391
// cli-wrapper.js
392
const utils = require('./existing-utils');
393
const fire = require('js-fire');
394
395
fire(utils);
396
// Now callable as: node cli-wrapper.js processData --input=data.csv --format=xml
397
```