0
# MRI
1
2
MRI is a fast and lightweight alternative to minimist and yargs-parser for parsing CLI flags and arguments. It provides core argument parsing functionality with support for boolean flags, string values, numeric values, aliases, defaults, and unknown flag detection. The library is designed for high performance (5x faster than minimist, 40x faster than yargs-parser) with minimal dependencies, making it ideal for CLI tools and command-line applications.
3
4
## Package Information
5
6
- **Package Name**: mri
7
- **Package Type**: npm
8
- **Language**: JavaScript (with TypeScript definitions)
9
- **Installation**: `npm install mri`
10
11
## Core Imports
12
13
CommonJS (primary export format):
14
15
```javascript
16
const mri = require('mri');
17
```
18
19
ES Modules:
20
21
```javascript
22
import mri from 'mri';
23
```
24
25
TypeScript:
26
27
```typescript
28
import mri from 'mri';
29
// or
30
import mri, { Options, Argv } from 'mri';
31
```
32
33
## Basic Usage
34
35
```javascript
36
import mri from 'mri';
37
38
// Parse command line arguments
39
const argv = process.argv.slice(2);
40
41
// Basic parsing
42
const parsed = mri(argv);
43
// Example: ['--foo', '--bar=baz', '-mtv', 'hello', 'world']
44
// Result: { _: ['hello', 'world'], foo: true, bar: 'baz', m: true, t: true, v: true }
45
46
// With configuration options
47
const parsed = mri(argv, {
48
boolean: ['verbose', 'debug'],
49
string: ['name', 'output'],
50
alias: {
51
v: 'verbose',
52
d: 'debug',
53
n: 'name',
54
o: 'output'
55
},
56
default: {
57
verbose: false,
58
output: 'result.txt'
59
}
60
});
61
```
62
63
## Architecture
64
65
MRI is built around a single-pass argument parser with several key design principles:
66
67
- **Minimal Dependencies**: Zero runtime dependencies for maximum compatibility and performance
68
- **Type Coercion Engine**: Automatic detection and conversion of numeric values while respecting type hints
69
- **Alias Resolution System**: Bidirectional alias mapping that maintains consistency across all related option names
70
- **Lazy Evaluation**: Options like `boolean`, `string`, and `default` are processed during parsing for optimal performance
71
- **Strict Mode Support**: Optional unknown flag detection via the `unknown` callback when combined with alias definitions
72
- **Stream Processing**: Single-pass parsing that handles argument termination (`--`) and maintains order for non-option arguments
73
74
The parser uses character-level analysis for flag detection and supports both POSIX-style short options (`-abc`) and GNU-style long options (`--flag=value`).
75
76
## Capabilities
77
78
### Main Parsing Function
79
80
Parses command line arguments with configurable options for type coercion, aliases, and defaults.
81
82
```javascript { .api }
83
/**
84
* Parse command line arguments into an object
85
* @param args - Array of command line arguments to parse
86
* @param options - Configuration options for parsing behavior
87
* @returns Parsed arguments object with _ array for non-option arguments
88
*/
89
function mri(args?: string[], options?: Options): Argv;
90
```
91
92
**Usage Examples:**
93
94
```javascript
95
// Basic flag parsing
96
mri(['--foo', '--bar=value', 'arg1', 'arg2']);
97
// { _: ['arg1', 'arg2'], foo: true, bar: 'value' }
98
99
// Short flag groups
100
mri(['-abc']);
101
// { _: [], a: true, b: true, c: true }
102
103
// Negation flags
104
mri(['--no-cache']);
105
// { _: [], cache: false }
106
107
// Mixed values with type coercion
108
mri(['--port', '3000', '--name', 'server', '--debug']);
109
// { _: [], port: 3000, name: 'server', debug: true }
110
111
// Multiple values create arrays
112
mri(['-v', 'a', '-v', 'b', '-v', 'c']);
113
// { _: [], v: ['a', 'b', 'c'] }
114
115
// Argument termination
116
mri(['--verbose', '--', '--not-a-flag', 'value']);
117
// { _: ['--not-a-flag', 'value'], verbose: true }
118
```
119
120
### Type Configuration
121
122
Control type coercion for specific keys.
123
124
```javascript { .api }
125
// Force boolean parsing for specific keys
126
mri(['--verbose', 'true'], { boolean: ['verbose'] });
127
// { _: [], verbose: true }
128
129
// Force string parsing for specific keys
130
mri(['--port', '3000'], { string: ['port'] });
131
// { _: [], port: '3000' }
132
133
// Multiple keys can be specified as array or single string
134
mri(args, { boolean: ['debug', 'verbose'] });
135
mri(args, { string: 'output' });
136
```
137
138
### Alias Configuration
139
140
Define alternative names for options.
141
142
```javascript { .api }
143
// Single alias
144
mri(['-v'], { alias: { v: 'verbose' } });
145
// { _: [], v: true, verbose: true }
146
147
// Multiple aliases for one key
148
mri(['-h'], { alias: { help: ['h', '?'] } });
149
// { _: [], h: true, help: true, '?': true }
150
151
// Bidirectional alias relationships
152
const options = {
153
alias: {
154
verbose: 'v',
155
output: ['o', 'out']
156
}
157
};
158
```
159
160
### Default Values
161
162
Provide default values and automatic type inference.
163
164
```javascript { .api }
165
const options = {
166
default: {
167
port: 8080, // number default
168
verbose: false, // boolean default
169
output: 'build/', // string default
170
tags: [] // array default
171
}
172
};
173
174
// Defaults are applied when keys are missing
175
mri([], options);
176
// { _: [], port: 8080, verbose: false, output: 'build/', tags: [] }
177
178
// Type of default determines parsing behavior
179
mri(['--port', 'value'], options);
180
// { _: ['value'], port: 8080 } - 'value' becomes non-option since port expects number
181
182
// Boolean defaults with flag values
183
mri(['--verbose', 'false'], { default: { verbose: true } });
184
// { _: [], verbose: false } - 'false' string is coerced to boolean false
185
```
186
187
### Unknown Flag Handling
188
189
Handle unknown flags with custom callback.
190
191
```javascript { .api }
192
/**
193
* Callback function for handling unknown flags
194
* @param flag - The unknown flag that was encountered
195
*/
196
type UnknownHandler = (flag: string) => void;
197
198
const options = {
199
alias: { v: 'verbose' }, // Required for strict mode
200
unknown: (flag) => {
201
console.error(`Unknown flag: ${flag}`);
202
process.exit(1);
203
}
204
};
205
206
// Parsing stops when unknown flag encountered
207
mri(['--verbose', '--invalid'], options);
208
// Calls unknown('--invalid') and parsing terminates
209
```
210
211
## Types
212
213
### Options Interface
214
215
Configuration object for customizing parsing behavior.
216
217
```typescript { .api }
218
interface Options {
219
/** Keys that should be parsed as boolean values */
220
boolean?: string | string[];
221
222
/** Keys that should be parsed as string values */
223
string?: string | string[];
224
225
/** Mapping of aliases - key can map to string or array of strings */
226
alias?: Record<string, string | string[]>;
227
228
/** Default values for keys - type determines parsing behavior */
229
default?: Record<string, any>;
230
231
/** Callback for handling unknown flags (requires alias to be set) */
232
unknown?: (flag: string) => void;
233
}
234
```
235
236
### Argv Result Type
237
238
The result object returned by the mri function.
239
240
```typescript { .api }
241
type Argv<T = Record<string, any>> = T & {
242
/** Array of non-option arguments */
243
_: string[];
244
};
245
```
246
247
### Utility Types
248
249
Helper types used in the TypeScript definitions.
250
251
```typescript { .api }
252
/** Generic dictionary/record type */
253
type Dict<T> = Record<string, T>;
254
255
/** Type that can be a single value or array of values */
256
type Arrayable<T> = T | T[];
257
258
/** Default type for the returned argv object */
259
type Default = Dict<any>;
260
```
261
262
## Parsing Behavior
263
264
### Flag Recognition
265
266
- **Long flags**: `--flag`, `--flag=value`, `--flag value`
267
- **Short flags**: `-f`, `-f=value`, `-f value`
268
- **Short flag groups**: `-abc` becomes `{a: true, b: true, c: true}`
269
- **Negation**: `--no-flag` becomes `{flag: false}`
270
- **Termination**: `--` stops parsing, remaining args go to `_` array
271
272
### Type Coercion
273
274
- **Numbers**: Automatic conversion when valid (`"123"` → `123`, `"0"` → `0`)
275
- **Booleans**: `true` for flags without values, `false` for `--no-` prefixed flags
276
- **Strings**: Default for values that can't be coerced to numbers
277
- **Arrays**: Multiple values for same key create arrays (e.g., `-v a -v b` → `{v: ['a', 'b']}`)
278
279
### Alias Resolution
280
281
- All aliases are bidirectional - setting any alias sets all related names
282
- Alias chains are fully resolved (if `a` aliases to `b` and `b` aliases to `c`, all three are set)
283
- Aliases apply to boolean, string, and default configurations automatically
284
285
### Error Handling
286
287
- **Unknown flags**: Only checked when both `unknown` callback and `alias` object are provided
288
- **Type conflicts**: Default value type takes precedence over inferred type
289
- **Invalid usage**: Parsing continues with best-effort approach, no exceptions thrown