Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert to ES Modules #69

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,8 @@ jobs:
- uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
- uses: pnpm/[email protected]
with:
run_install: true
- run: pnpm build
- run: pnpm test
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ package-lock.json
yarn.lock
npm-debug.log
yarn-error.log
dist/
31 changes: 20 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ npm install arg

## Usage

`arg()` takes either 1 or 2 arguments:
`arg.run()` takes either 1 or 2 arguments:

1. Command line specification object (see below)
2. Parse options (_Optional_, defaults to `{permissive: false, argv: process.argv.slice(2), stopAtPositional: false}`)
Expand All @@ -27,10 +27,19 @@ in which case an empty array is returned).
const arg = require('arg');

// `options` is an optional parameter
const args = arg(
const args = arg.run(
spec,
(options = { permissive: false, argv: process.argv.slice(2) })
);

// It also supports ESM
import * as arg from 'arg'

const args = arg.run(
spec,
(options = { permissive: false, argv: process.argv.slice(2) })
);

```

For example:
Expand All @@ -43,7 +52,7 @@ $ node ./hello.js --verbose -vvv --port=1234 -n 'My name' foo bar --tag qux --ta
// hello.js
const arg = require('arg');

const args = arg({
const args = arg.run({
// Types
'--help': Boolean,
'--version': Boolean,
Expand Down Expand Up @@ -116,7 +125,7 @@ function myHandler(value, argName, previousValue) {
return 'na ' + (previousValue || 'batman!');
}

const args = arg(
const args = arg.run(
{
'--foo': arg.flag(myHandler),
'-f': '--foo'
Expand Down Expand Up @@ -144,7 +153,7 @@ const arg = require('arg');

const argv = ['-AAAA', '-BBBB'];

const args = arg(
const args = arg.run(
{
'-A': arg.COUNT,
'-B': [Boolean]
Expand All @@ -166,7 +175,7 @@ console.log(args);

### Options

If a second parameter is specified and is an object, it specifies parsing options to modify the behavior of `arg()`.
If a second parameter is specified and is an object, it specifies parsing options to modify the behavior of `arg.run()`.

#### `argv`

Expand All @@ -176,7 +185,7 @@ slice them from `process.argv`) you may specify them in the `argv` option.
For example:

```javascript
const args = arg(
const args = arg.run(
{
'--foo': String
},
Expand Down Expand Up @@ -216,7 +225,7 @@ const argv = [
'hello again'
];

const args = arg(
const args = arg.run(
{
'--foo': String,
'--bar': Number
Expand Down Expand Up @@ -250,7 +259,7 @@ const arg = require('arg');

const argv = ['--foo', 'hello', '--bar'];

const args = arg(
const args = arg.run(
{
'--foo': Boolean,
'--bar': Boolean
Expand Down Expand Up @@ -283,7 +292,7 @@ If an unknown option (not defined in the spec object) is passed, an error with c
```js
// cli.js
try {
require('arg')({ '--hi': String });
require('arg').run({ '--hi': String });
} catch (err) {
if (err.code === 'ARG_UNKNOWN_OPTION') {
console.log(err.message);
Expand All @@ -307,7 +316,7 @@ A few questions and answers that have been asked before:
Do the assertion yourself, such as:

```javascript
const args = arg({ '--name': String });
const args = arg.run({ '--name': String });

if (!args['--name']) throw new Error('missing required argument: --name');
```
Expand Down
79 changes: 37 additions & 42 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,39 @@
declare function arg<T extends arg.Spec>(
spec: T,
options?: arg.Options
): arg.Result<T>;

declare namespace arg {
export const flagSymbol: unique symbol;

export function flag<T>(fn: T): T & { [arg.flagSymbol]: true };

export const COUNT: Handler<number> & { [arg.flagSymbol]: true };

export type Handler<T = any> = (
value: string,
name: string,
previousValue?: T
) => T;

export class ArgError extends Error {
constructor(message: string, code: string);

code: string;
}

export interface Spec {
[key: string]: string | Handler | [Handler];
}

export type Result<T extends Spec> = { _: string[] } & {
[K in keyof T]?: T[K] extends Handler
? ReturnType<T[K]>
: T[K] extends [Handler]
? Array<ReturnType<T[K][0]>>
: never;
};

export interface Options {
argv?: string[];
permissive?: boolean;
stopAtPositional?: boolean;
}
// Types
export type Handler<T = any> = (
value: string,
name: string,
previousValue?: T
) => T;

export interface Spec {
[key: string]: string | Handler | [Handler];
}

export = arg;
export type Result<T extends Spec> = { _: string[] } & {
[K in keyof T]?: T[K] extends Handler
? ReturnType<T[K]>
: T[K] extends [Handler]
? Array<ReturnType<T[K][0]>>
: never;
};

export interface Options {
argv?: string[];
permissive?: boolean;
stopAtPositional?: boolean;
}

// Exports
declare const flagSymbol: unique symbol;

export class ArgError extends Error {
constructor(message: string, code: string);

code: string;
}

export function run<T extends Spec>(spec: T, options?: Options): Result<T>;

export function flag<T>(fn: T): T & { [flagSymbol]: true };

export const COUNT: Handler<number> & { [flagSymbol]: true };
15 changes: 5 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const flagSymbol = Symbol('arg flag');

class ArgError extends Error {
export class ArgError extends Error {
constructor(msg, code) {
super(msg);
this.name = 'ArgError';
Expand All @@ -10,7 +10,7 @@ class ArgError extends Error {
}
}

function arg(
export function run(
opts,
{
argv = process.argv.slice(2),
Expand Down Expand Up @@ -181,15 +181,10 @@ function arg(
return result;
}

arg.flag = (fn) => {
export function flag(fn) {
fn[flagSymbol] = true;
return fn;
};
}

// Utility types
arg.COUNT = arg.flag((v, name, existingCount) => (existingCount || 0) + 1);

// Expose error class
arg.ArgError = ArgError;

module.exports = arg;
export const COUNT = flag((v, name, existingCount) => (existingCount || 0) + 1);
25 changes: 19 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,35 @@
"name": "arg",
"version": "5.0.2",
"description": "Unopinionated, no-frills CLI argument parser",
"main": "index.js",
"types": "index.d.ts",
"repository": "vercel/arg",
"author": "Josh Junon <[email protected]>",
"license": "MIT",
"files": [
"index.js",
"dist",
"index.d.ts"
],
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./index.d.ts",
"exports": {
".": {
"require": "./dist/index.js",
"import": "./dist/index.mjs",
"types": "./index.d.ts"
}
},
"packageManager": "[email protected]",
"scripts": {
"build": "tsup index.js --format cjs,esm --clean",
"prepublishOnly": "pnpm build",
"format": "prettier -w .",
"test": "WARN_EXIT=1 jest --coverage -w 2"
},
"devDependencies": {
"chai": "^4.1.1",
"jest": "^27.0.6",
"prettier": "^2.3.2"
"chai": "^4.3.6",
"jest": "^29.2.0",
"prettier": "^2.7.1",
"tsup": "^6.2.3"
},
"prettier": {
"arrowParens": "always",
Expand Down
Loading