clerc 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +262 -0
- package/dist/index.d.ts +283 -0
- package/dist/index.mjs +237 -0
- package/package.json +2 -2
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var liteEmit = require('lite-emit');
|
|
6
|
+
var mri = require('mri');
|
|
7
|
+
var typeFlag = require('type-flag');
|
|
8
|
+
var utils = require('@clerc/utils');
|
|
9
|
+
var isPlatform = require('is-platform');
|
|
10
|
+
|
|
11
|
+
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
|
12
|
+
|
|
13
|
+
var mri__default = /*#__PURE__*/_interopDefaultLegacy(mri);
|
|
14
|
+
|
|
15
|
+
class SingleCommandError extends Error {
|
|
16
|
+
constructor() {
|
|
17
|
+
super("Single command mode enabled.");
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
class CommandExistsError extends Error {
|
|
21
|
+
}
|
|
22
|
+
class CommonCommandExistsError extends Error {
|
|
23
|
+
constructor() {
|
|
24
|
+
super("Common command exists.");
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
class NoSuchCommandError extends Error {
|
|
28
|
+
constructor(name) {
|
|
29
|
+
super(`No such command: ${name}`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
class ParentCommandExistsError extends Error {
|
|
33
|
+
constructor(name) {
|
|
34
|
+
super(`Command "${name}" cannot exist with its parent`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
class SubcommandExistsError extends Error {
|
|
38
|
+
constructor(name) {
|
|
39
|
+
super(`Command "${name}" cannot exist with its subcommand`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const resolveFlagAlias = (_command) => Object.entries((_command == null ? void 0 : _command.flags) || {}).reduce((acc, [name, command]) => {
|
|
44
|
+
if (command.alias) {
|
|
45
|
+
const item = utils.mustArray(command.alias).map(utils.kebabCase);
|
|
46
|
+
acc[utils.kebabCase(name)] = item;
|
|
47
|
+
}
|
|
48
|
+
return acc;
|
|
49
|
+
}, {});
|
|
50
|
+
const resolveFlagDefault = (_command) => Object.entries((_command == null ? void 0 : _command.flags) || {}).reduce((acc, [name, command]) => {
|
|
51
|
+
const item = command.default;
|
|
52
|
+
if (item) {
|
|
53
|
+
acc[name] = item;
|
|
54
|
+
}
|
|
55
|
+
return acc;
|
|
56
|
+
}, {});
|
|
57
|
+
function resolveCommand(commands, name) {
|
|
58
|
+
if (name === SingleCommand) {
|
|
59
|
+
return commands[SingleCommand];
|
|
60
|
+
}
|
|
61
|
+
const nameArr = Array.isArray(name) ? name : name.split(" ");
|
|
62
|
+
const nameString = nameArr.join(" ");
|
|
63
|
+
const possibleCommands = Object.values(commands).filter(
|
|
64
|
+
(c) => utils.arrayStartsWith(nameArr, c.name.split(" ")) || utils.mustArray(c.alias || []).map(String).includes(nameString)
|
|
65
|
+
);
|
|
66
|
+
if (possibleCommands.length > 1) {
|
|
67
|
+
throw new Error(`Multiple commands found with name "${nameString}"`);
|
|
68
|
+
}
|
|
69
|
+
return possibleCommands[0];
|
|
70
|
+
}
|
|
71
|
+
function resolveSubcommandsByParent(commands, parent, depth = Infinity) {
|
|
72
|
+
const parentArr = parent === "" ? [] : Array.isArray(parent) ? parent : parent.split(" ");
|
|
73
|
+
return Object.values(commands).filter((c) => {
|
|
74
|
+
const commandNameArr = c.name.split(" ");
|
|
75
|
+
return utils.arrayStartsWith(commandNameArr, parentArr) && commandNameArr.length - parentArr.length <= depth;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
const resolveRootCommands = (commands) => resolveSubcommandsByParent(commands, "", 1);
|
|
79
|
+
const resolveArgv = () => isPlatform.isNode() ? process.argv.slice(2) : isPlatform.isDeno() ? Deno.args : [];
|
|
80
|
+
function compose(inspectors) {
|
|
81
|
+
return (getCtx) => {
|
|
82
|
+
return dispatch(0);
|
|
83
|
+
function dispatch(i) {
|
|
84
|
+
const inspector = inspectors[i];
|
|
85
|
+
return inspector(getCtx(), dispatch.bind(null, i + 1));
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
var __accessCheck = (obj, member, msg) => {
|
|
91
|
+
if (!member.has(obj))
|
|
92
|
+
throw TypeError("Cannot " + msg);
|
|
93
|
+
};
|
|
94
|
+
var __privateGet = (obj, member, getter) => {
|
|
95
|
+
__accessCheck(obj, member, "read from private field");
|
|
96
|
+
return getter ? getter.call(obj) : member.get(obj);
|
|
97
|
+
};
|
|
98
|
+
var __privateAdd = (obj, member, value) => {
|
|
99
|
+
if (member.has(obj))
|
|
100
|
+
throw TypeError("Cannot add the same private member more than once");
|
|
101
|
+
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
102
|
+
};
|
|
103
|
+
var __privateSet = (obj, member, value, setter) => {
|
|
104
|
+
__accessCheck(obj, member, "write to private field");
|
|
105
|
+
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
106
|
+
return value;
|
|
107
|
+
};
|
|
108
|
+
var _name, _description, _version, _inspectors, _commands, _commandEmitter, _isSingleCommand, isSingleCommand_get, _hasCommands, hasCommands_get;
|
|
109
|
+
const SingleCommand = Symbol("SingleCommand");
|
|
110
|
+
const _Clerc = class {
|
|
111
|
+
constructor() {
|
|
112
|
+
__privateAdd(this, _isSingleCommand);
|
|
113
|
+
__privateAdd(this, _hasCommands);
|
|
114
|
+
__privateAdd(this, _name, "");
|
|
115
|
+
__privateAdd(this, _description, "");
|
|
116
|
+
__privateAdd(this, _version, "");
|
|
117
|
+
__privateAdd(this, _inspectors, []);
|
|
118
|
+
__privateAdd(this, _commands, {});
|
|
119
|
+
__privateAdd(this, _commandEmitter, new liteEmit.LiteEmit());
|
|
120
|
+
}
|
|
121
|
+
get _name() {
|
|
122
|
+
return __privateGet(this, _name);
|
|
123
|
+
}
|
|
124
|
+
get _description() {
|
|
125
|
+
return __privateGet(this, _description);
|
|
126
|
+
}
|
|
127
|
+
get _version() {
|
|
128
|
+
return __privateGet(this, _version);
|
|
129
|
+
}
|
|
130
|
+
get _inspectors() {
|
|
131
|
+
return __privateGet(this, _inspectors);
|
|
132
|
+
}
|
|
133
|
+
get _commands() {
|
|
134
|
+
return __privateGet(this, _commands);
|
|
135
|
+
}
|
|
136
|
+
static create() {
|
|
137
|
+
return new _Clerc();
|
|
138
|
+
}
|
|
139
|
+
name(name) {
|
|
140
|
+
__privateSet(this, _name, name);
|
|
141
|
+
return this;
|
|
142
|
+
}
|
|
143
|
+
description(description) {
|
|
144
|
+
__privateSet(this, _description, description);
|
|
145
|
+
return this;
|
|
146
|
+
}
|
|
147
|
+
version(version) {
|
|
148
|
+
__privateSet(this, _version, version);
|
|
149
|
+
return this;
|
|
150
|
+
}
|
|
151
|
+
command(name, description, options = {}) {
|
|
152
|
+
if (__privateGet(this, _commands)[name]) {
|
|
153
|
+
if (name === SingleCommand) {
|
|
154
|
+
throw new CommandExistsError("Single command already exists");
|
|
155
|
+
}
|
|
156
|
+
throw new CommandExistsError(`Command "${name === SingleCommand ? "[SingleCommand]" : name}" already exists`);
|
|
157
|
+
}
|
|
158
|
+
if (__privateGet(this, _isSingleCommand, isSingleCommand_get)) {
|
|
159
|
+
throw new SingleCommandError();
|
|
160
|
+
}
|
|
161
|
+
if (name === SingleCommand && __privateGet(this, _hasCommands, hasCommands_get)) {
|
|
162
|
+
throw new CommonCommandExistsError();
|
|
163
|
+
}
|
|
164
|
+
if (name !== SingleCommand) {
|
|
165
|
+
const splitedName = name.split(" ");
|
|
166
|
+
const existedCommandNames = Object.keys(__privateGet(this, _commands)).filter((name2) => typeof name2 === "string").map((name2) => name2.split(" "));
|
|
167
|
+
if (existedCommandNames.some((name2) => utils.arrayStartsWith(splitedName, name2))) {
|
|
168
|
+
throw new ParentCommandExistsError(splitedName.join(" "));
|
|
169
|
+
}
|
|
170
|
+
if (existedCommandNames.some((name2) => utils.arrayStartsWith(name2, splitedName))) {
|
|
171
|
+
throw new SubcommandExistsError(splitedName.join(" "));
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
__privateGet(this, _commands)[name] = { name, description, ...options };
|
|
175
|
+
return this;
|
|
176
|
+
}
|
|
177
|
+
on(name, handler) {
|
|
178
|
+
__privateGet(this, _commandEmitter).on(name, handler);
|
|
179
|
+
return this;
|
|
180
|
+
}
|
|
181
|
+
use(plugin) {
|
|
182
|
+
return plugin.setup(this);
|
|
183
|
+
}
|
|
184
|
+
inspector(inspector) {
|
|
185
|
+
__privateGet(this, _inspectors).push(inspector);
|
|
186
|
+
return this;
|
|
187
|
+
}
|
|
188
|
+
parse(argv = resolveArgv()) {
|
|
189
|
+
const parsed = mri__default["default"](argv);
|
|
190
|
+
const name = parsed._.map(String);
|
|
191
|
+
const stringName = name.join(" ");
|
|
192
|
+
const getCommand = () => __privateGet(this, _isSingleCommand, isSingleCommand_get) ? __privateGet(this, _commands)[SingleCommand] : resolveCommand(__privateGet(this, _commands), name);
|
|
193
|
+
const getContext = () => {
|
|
194
|
+
const command = getCommand();
|
|
195
|
+
const isCommandResolved = !!command;
|
|
196
|
+
const parsedWithType = typeFlag.typeFlag((command == null ? void 0 : command.flags) || {}, [...argv]);
|
|
197
|
+
const { _: args, flags } = parsedWithType;
|
|
198
|
+
const parameters = __privateGet(this, _isSingleCommand, isSingleCommand_get) || !isCommandResolved ? args : args.slice(command.name.split(" ").length);
|
|
199
|
+
const context = {
|
|
200
|
+
name: command == null ? void 0 : command.name,
|
|
201
|
+
resolved: isCommandResolved,
|
|
202
|
+
isSingleCommand: __privateGet(this, _isSingleCommand, isSingleCommand_get),
|
|
203
|
+
raw: parsedWithType,
|
|
204
|
+
parameters,
|
|
205
|
+
flags,
|
|
206
|
+
unknownFlags: parsedWithType.unknownFlags,
|
|
207
|
+
cli: this
|
|
208
|
+
};
|
|
209
|
+
return context;
|
|
210
|
+
};
|
|
211
|
+
const emitHandler = () => {
|
|
212
|
+
const command = getCommand();
|
|
213
|
+
const handlerContext = getContext();
|
|
214
|
+
if (!command) {
|
|
215
|
+
throw new NoSuchCommandError(stringName);
|
|
216
|
+
}
|
|
217
|
+
__privateGet(this, _commandEmitter).emit(command.name, handlerContext);
|
|
218
|
+
};
|
|
219
|
+
const inspectors = [...__privateGet(this, _inspectors), emitHandler];
|
|
220
|
+
const inspector = compose(inspectors);
|
|
221
|
+
inspector(getContext);
|
|
222
|
+
return this;
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
let Clerc = _Clerc;
|
|
226
|
+
_name = new WeakMap();
|
|
227
|
+
_description = new WeakMap();
|
|
228
|
+
_version = new WeakMap();
|
|
229
|
+
_inspectors = new WeakMap();
|
|
230
|
+
_commands = new WeakMap();
|
|
231
|
+
_commandEmitter = new WeakMap();
|
|
232
|
+
_isSingleCommand = new WeakSet();
|
|
233
|
+
isSingleCommand_get = function() {
|
|
234
|
+
return __privateGet(this, _commands)[SingleCommand] !== void 0;
|
|
235
|
+
};
|
|
236
|
+
_hasCommands = new WeakSet();
|
|
237
|
+
hasCommands_get = function() {
|
|
238
|
+
return Object.keys(__privateGet(this, _commands)).length > 0;
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
const definePlugin = (p) => p;
|
|
242
|
+
const defineHandler = (_cli, _key, handler) => handler;
|
|
243
|
+
const defineInspector = (_cli, inspector) => inspector;
|
|
244
|
+
|
|
245
|
+
exports.Clerc = Clerc;
|
|
246
|
+
exports.CommandExistsError = CommandExistsError;
|
|
247
|
+
exports.CommonCommandExistsError = CommonCommandExistsError;
|
|
248
|
+
exports.NoSuchCommandError = NoSuchCommandError;
|
|
249
|
+
exports.ParentCommandExistsError = ParentCommandExistsError;
|
|
250
|
+
exports.SingleCommand = SingleCommand;
|
|
251
|
+
exports.SingleCommandError = SingleCommandError;
|
|
252
|
+
exports.SubcommandExistsError = SubcommandExistsError;
|
|
253
|
+
exports.compose = compose;
|
|
254
|
+
exports.defineHandler = defineHandler;
|
|
255
|
+
exports.defineInspector = defineInspector;
|
|
256
|
+
exports.definePlugin = definePlugin;
|
|
257
|
+
exports.resolveArgv = resolveArgv;
|
|
258
|
+
exports.resolveCommand = resolveCommand;
|
|
259
|
+
exports.resolveFlagAlias = resolveFlagAlias;
|
|
260
|
+
exports.resolveFlagDefault = resolveFlagDefault;
|
|
261
|
+
exports.resolveRootCommands = resolveRootCommands;
|
|
262
|
+
exports.resolveSubcommandsByParent = resolveSubcommandsByParent;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import * as _clerc_utils from '@clerc/utils';
|
|
2
|
+
import { MaybeArray, Dict, LiteralUnion } from '@clerc/utils';
|
|
3
|
+
|
|
4
|
+
declare const DOUBLE_DASH = "--";
|
|
5
|
+
type TypeFunction<ReturnType = any> = (value: any) => ReturnType;
|
|
6
|
+
type TypeFunctionArray<ReturnType> = readonly [TypeFunction<ReturnType>];
|
|
7
|
+
type FlagType<ReturnType = any> = TypeFunction<ReturnType> | TypeFunctionArray<ReturnType>;
|
|
8
|
+
type FlagSchemaBase<TF> = {
|
|
9
|
+
/**
|
|
10
|
+
Type of the flag as a function that parses the argv string and returns the parsed value.
|
|
11
|
+
|
|
12
|
+
@example
|
|
13
|
+
```
|
|
14
|
+
type: String
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
@example Wrap in an array to accept multiple values.
|
|
18
|
+
```
|
|
19
|
+
type: [Boolean]
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
@example Custom function type that uses moment.js to parse string as date.
|
|
23
|
+
```
|
|
24
|
+
type: function CustomDate(value: string) {
|
|
25
|
+
return moment(value).toDate();
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
*/
|
|
29
|
+
type: TF;
|
|
30
|
+
/**
|
|
31
|
+
A single-character alias for the flag.
|
|
32
|
+
|
|
33
|
+
@example
|
|
34
|
+
```
|
|
35
|
+
alias: 's'
|
|
36
|
+
```
|
|
37
|
+
*/
|
|
38
|
+
alias?: string;
|
|
39
|
+
} & Record<PropertyKey, unknown>;
|
|
40
|
+
type FlagSchemaDefault<TF, DefaultType = any> = FlagSchemaBase<TF> & {
|
|
41
|
+
/**
|
|
42
|
+
Default value of the flag. Also accepts a function that returns the default value.
|
|
43
|
+
[Default: undefined]
|
|
44
|
+
|
|
45
|
+
@example
|
|
46
|
+
```
|
|
47
|
+
default: 'hello'
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
@example
|
|
51
|
+
```
|
|
52
|
+
default: () => [1, 2, 3]
|
|
53
|
+
```
|
|
54
|
+
*/
|
|
55
|
+
default: DefaultType | (() => DefaultType);
|
|
56
|
+
};
|
|
57
|
+
type FlagSchema<TF = FlagType> = (FlagSchemaBase<TF> | FlagSchemaDefault<TF>);
|
|
58
|
+
type FlagTypeOrSchema<ExtraOptions = Record<string, unknown>> = FlagType | (FlagSchema & ExtraOptions);
|
|
59
|
+
type Flags<ExtraOptions = Record<string, unknown>> = Record<string, FlagTypeOrSchema<ExtraOptions>>;
|
|
60
|
+
type InferFlagType<Flag extends FlagTypeOrSchema> = (Flag extends (TypeFunctionArray<infer T> | FlagSchema<TypeFunctionArray<infer T>>) ? (Flag extends FlagSchemaDefault<TypeFunctionArray<T>, infer D> ? T[] | D : T[]) : (Flag extends TypeFunction<infer T> | FlagSchema<TypeFunction<infer T>> ? (Flag extends FlagSchemaDefault<TypeFunction<T>, infer D> ? T | D : T | undefined) : never));
|
|
61
|
+
interface ParsedFlags<Schemas = Record<string, unknown>> {
|
|
62
|
+
flags: Schemas;
|
|
63
|
+
unknownFlags: Record<string, (string | boolean)[]>;
|
|
64
|
+
_: string[] & {
|
|
65
|
+
[DOUBLE_DASH]: string[];
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
type TypeFlag<Schemas extends Flags> = ParsedFlags<{
|
|
69
|
+
[flag in keyof Schemas]: InferFlagType<Schemas[flag]>;
|
|
70
|
+
}>;
|
|
71
|
+
|
|
72
|
+
type FlagOptions = FlagSchema & {
|
|
73
|
+
description: string;
|
|
74
|
+
required?: boolean;
|
|
75
|
+
};
|
|
76
|
+
type Flag = FlagOptions & {
|
|
77
|
+
name: string;
|
|
78
|
+
};
|
|
79
|
+
interface CommandOptions<A extends MaybeArray<string> = MaybeArray<string>, F extends Dict<FlagOptions> = Dict<FlagOptions>> {
|
|
80
|
+
alias?: A;
|
|
81
|
+
flags?: F;
|
|
82
|
+
examples?: [string, string][];
|
|
83
|
+
notes?: string[];
|
|
84
|
+
}
|
|
85
|
+
type Command<N extends string | SingleCommandType = string, D extends string = string, Options extends CommandOptions = CommandOptions> = Options & {
|
|
86
|
+
name: N;
|
|
87
|
+
description: D;
|
|
88
|
+
};
|
|
89
|
+
type CommandRecord = Dict<Command> & {
|
|
90
|
+
[SingleCommand]?: Command;
|
|
91
|
+
};
|
|
92
|
+
type MakeEventMap<T extends CommandRecord> = {
|
|
93
|
+
[K in keyof T]: [InspectorContext];
|
|
94
|
+
};
|
|
95
|
+
type PossibleInputKind = string | number | boolean | Dict<any>;
|
|
96
|
+
type NonNullableFlag<T extends Dict<FlagOptions> | undefined> = T extends undefined ? {} : NonNullable<T>;
|
|
97
|
+
interface HandlerContext<C extends CommandRecord = CommandRecord, N extends keyof C = keyof C> {
|
|
98
|
+
name?: N;
|
|
99
|
+
resolved: boolean;
|
|
100
|
+
isSingleCommand: boolean;
|
|
101
|
+
raw: ParsedFlags;
|
|
102
|
+
parameters: PossibleInputKind[];
|
|
103
|
+
unknownFlags: ParsedFlags["unknownFlags"];
|
|
104
|
+
flags: TypeFlag<NonNullableFlag<C[N]["flags"]>>["flags"];
|
|
105
|
+
cli: Clerc<C>;
|
|
106
|
+
}
|
|
107
|
+
type Handler<C extends CommandRecord = CommandRecord, K extends keyof C = keyof C> = (ctx: HandlerContext<C, K>) => void;
|
|
108
|
+
type FallbackType<T, U> = {} extends T ? U : T;
|
|
109
|
+
type InspectorContext<C extends CommandRecord = CommandRecord> = HandlerContext<C> & {
|
|
110
|
+
flags: FallbackType<TypeFlag<NonNullableFlag<C[keyof C]["flags"]>>["flags"], Dict<any>>;
|
|
111
|
+
};
|
|
112
|
+
type Inspector<C extends CommandRecord = CommandRecord> = (ctx: InspectorContext<C>, next: () => void) => void;
|
|
113
|
+
interface Plugin<T extends Clerc = Clerc, U extends Clerc = Clerc> {
|
|
114
|
+
setup: (cli: T) => U;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
declare const SingleCommand: unique symbol;
|
|
118
|
+
type SingleCommandType = typeof SingleCommand;
|
|
119
|
+
declare class Clerc<C extends CommandRecord = {}> {
|
|
120
|
+
#private;
|
|
121
|
+
private constructor();
|
|
122
|
+
get _name(): string;
|
|
123
|
+
get _description(): string;
|
|
124
|
+
get _version(): string;
|
|
125
|
+
get _inspectors(): Inspector<CommandRecord>[];
|
|
126
|
+
get _commands(): C;
|
|
127
|
+
/**
|
|
128
|
+
* Create a new cli
|
|
129
|
+
* @returns
|
|
130
|
+
* @example
|
|
131
|
+
* ```ts
|
|
132
|
+
* const cli = Clerc.create()
|
|
133
|
+
* ```
|
|
134
|
+
*/
|
|
135
|
+
static create(): Clerc<{}>;
|
|
136
|
+
/**
|
|
137
|
+
* Set the name of the cli
|
|
138
|
+
* @param name
|
|
139
|
+
* @returns
|
|
140
|
+
* @example
|
|
141
|
+
* ```ts
|
|
142
|
+
* Clerc.create()
|
|
143
|
+
* .name("test")
|
|
144
|
+
* ```
|
|
145
|
+
*/
|
|
146
|
+
name(name: string): this;
|
|
147
|
+
/**
|
|
148
|
+
* Set the description of the cli
|
|
149
|
+
* @param description
|
|
150
|
+
* @returns
|
|
151
|
+
* @example
|
|
152
|
+
* ```ts
|
|
153
|
+
* Clerc.create()
|
|
154
|
+
* .description("test cli")
|
|
155
|
+
*/
|
|
156
|
+
description(description: string): this;
|
|
157
|
+
/**
|
|
158
|
+
* Set the version of the cli
|
|
159
|
+
* @param version
|
|
160
|
+
* @returns
|
|
161
|
+
* @example
|
|
162
|
+
* ```ts
|
|
163
|
+
* Clerc.create()
|
|
164
|
+
* .version("1.0.0")
|
|
165
|
+
*/
|
|
166
|
+
version(version: string): this;
|
|
167
|
+
/**
|
|
168
|
+
* Register a command
|
|
169
|
+
* @param name
|
|
170
|
+
* @param description
|
|
171
|
+
* @param options
|
|
172
|
+
* @returns
|
|
173
|
+
* @example
|
|
174
|
+
* ```ts
|
|
175
|
+
* Clerc.create()
|
|
176
|
+
* .command("test", "test command", {
|
|
177
|
+
* alias: "t",
|
|
178
|
+
* flags: {
|
|
179
|
+
* foo: {
|
|
180
|
+
* alias: "f",
|
|
181
|
+
* description: "foo flag",
|
|
182
|
+
* }
|
|
183
|
+
* }
|
|
184
|
+
* })
|
|
185
|
+
* ```
|
|
186
|
+
* @example
|
|
187
|
+
* ```ts
|
|
188
|
+
* Clerc.create()
|
|
189
|
+
* .command("", "single command", {
|
|
190
|
+
* flags: {
|
|
191
|
+
* foo: {
|
|
192
|
+
* alias: "f",
|
|
193
|
+
* description: "foo flag",
|
|
194
|
+
* }
|
|
195
|
+
* }
|
|
196
|
+
* })
|
|
197
|
+
* ```
|
|
198
|
+
*/
|
|
199
|
+
command<N extends string | SingleCommandType, D extends string, O extends CommandOptions>(name: N, description: D, options?: O): this & Clerc<C & Record<N, Command<N, D, O>>>;
|
|
200
|
+
/**
|
|
201
|
+
* Register a handler
|
|
202
|
+
* @param name
|
|
203
|
+
* @param handler
|
|
204
|
+
* @returns
|
|
205
|
+
* @example
|
|
206
|
+
* ```ts
|
|
207
|
+
* Clerc.create()
|
|
208
|
+
* .command("test", "test command")
|
|
209
|
+
* .on("test", (ctx) => {
|
|
210
|
+
* console.log(ctx);
|
|
211
|
+
* })
|
|
212
|
+
* ```
|
|
213
|
+
*/
|
|
214
|
+
on<K extends keyof CM, CM extends this["_commands"] = this["_commands"]>(name: LiteralUnion<K, string>, handler: Handler<CM, K>): this;
|
|
215
|
+
/**
|
|
216
|
+
* Use a plugin
|
|
217
|
+
* @param plugin
|
|
218
|
+
* @returns
|
|
219
|
+
* @example
|
|
220
|
+
* ```ts
|
|
221
|
+
* Clerc.create()
|
|
222
|
+
* .use(plugin)
|
|
223
|
+
* ```
|
|
224
|
+
*/
|
|
225
|
+
use<T extends Clerc, U extends Clerc>(plugin: Plugin<T, U>): U;
|
|
226
|
+
/**
|
|
227
|
+
* Register a inspector
|
|
228
|
+
* @param inspector
|
|
229
|
+
* @returns
|
|
230
|
+
* @example
|
|
231
|
+
* ```ts
|
|
232
|
+
* Clerc.create()
|
|
233
|
+
* .inspector((ctx, next) => {
|
|
234
|
+
* console.log(ctx);
|
|
235
|
+
* next();
|
|
236
|
+
* })
|
|
237
|
+
* ```
|
|
238
|
+
*/
|
|
239
|
+
inspector(inspector: Inspector): this;
|
|
240
|
+
/**
|
|
241
|
+
* Parse the command line arguments
|
|
242
|
+
* @param args
|
|
243
|
+
* @returns
|
|
244
|
+
* @example
|
|
245
|
+
* ```ts
|
|
246
|
+
* Clerc.create()
|
|
247
|
+
* .parse(process.argv.slice(2)) // Optional
|
|
248
|
+
* ```
|
|
249
|
+
*/
|
|
250
|
+
parse(argv?: string[]): this;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
declare const definePlugin: <T extends Clerc<{}>, U extends Clerc<{}>>(p: Plugin<T, U>) => Plugin<T, U>;
|
|
254
|
+
declare const defineHandler: <C extends Clerc<{}>, K extends keyof C["_commands"]>(_cli: C, _key: K, handler: Handler<C["_commands"], K>) => Handler<C["_commands"], K>;
|
|
255
|
+
declare const defineInspector: <C extends Clerc<{}>>(_cli: C, inspector: Inspector<C["_commands"]>) => Inspector<C["_commands"]>;
|
|
256
|
+
|
|
257
|
+
declare class SingleCommandError extends Error {
|
|
258
|
+
constructor();
|
|
259
|
+
}
|
|
260
|
+
declare class CommandExistsError extends Error {
|
|
261
|
+
}
|
|
262
|
+
declare class CommonCommandExistsError extends Error {
|
|
263
|
+
constructor();
|
|
264
|
+
}
|
|
265
|
+
declare class NoSuchCommandError extends Error {
|
|
266
|
+
constructor(name: string);
|
|
267
|
+
}
|
|
268
|
+
declare class ParentCommandExistsError extends Error {
|
|
269
|
+
constructor(name: string);
|
|
270
|
+
}
|
|
271
|
+
declare class SubcommandExistsError extends Error {
|
|
272
|
+
constructor(name: string);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
declare const resolveFlagAlias: (_command: Command) => Dict<string[]>;
|
|
276
|
+
declare const resolveFlagDefault: (_command: Command) => Dict<any>;
|
|
277
|
+
declare function resolveCommand(commands: CommandRecord, name: string | string[] | SingleCommandType): Command | undefined;
|
|
278
|
+
declare function resolveSubcommandsByParent(commands: CommandRecord, parent: string | string[], depth?: number): Command<string, string, CommandOptions<_clerc_utils.MaybeArray<string>, Dict<FlagOptions>>>[];
|
|
279
|
+
declare const resolveRootCommands: (commands: CommandRecord) => Command<string, string, CommandOptions<_clerc_utils.MaybeArray<string>, Dict<FlagOptions>>>[];
|
|
280
|
+
declare const resolveArgv: () => string[];
|
|
281
|
+
declare function compose(inspectors: Inspector[]): (getCtx: () => InspectorContext) => void;
|
|
282
|
+
|
|
283
|
+
export { Clerc, Command, CommandExistsError, CommandOptions, CommandRecord, CommonCommandExistsError, FallbackType, Flag, FlagOptions, Handler, HandlerContext, Inspector, InspectorContext, MakeEventMap, NoSuchCommandError, ParentCommandExistsError, Plugin, PossibleInputKind, SingleCommand, SingleCommandError, SingleCommandType, SubcommandExistsError, compose, defineHandler, defineInspector, definePlugin, resolveArgv, resolveCommand, resolveFlagAlias, resolveFlagDefault, resolveRootCommands, resolveSubcommandsByParent };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { LiteEmit } from 'lite-emit';
|
|
2
|
+
import mri from 'mri';
|
|
3
|
+
import { typeFlag } from 'type-flag';
|
|
4
|
+
import { mustArray, kebabCase, arrayStartsWith } from '@clerc/utils';
|
|
5
|
+
import { isNode, isDeno } from 'is-platform';
|
|
6
|
+
|
|
7
|
+
class SingleCommandError extends Error {
|
|
8
|
+
constructor() {
|
|
9
|
+
super("Single command mode enabled.");
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
class CommandExistsError extends Error {
|
|
13
|
+
}
|
|
14
|
+
class CommonCommandExistsError extends Error {
|
|
15
|
+
constructor() {
|
|
16
|
+
super("Common command exists.");
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
class NoSuchCommandError extends Error {
|
|
20
|
+
constructor(name) {
|
|
21
|
+
super(`No such command: ${name}`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
class ParentCommandExistsError extends Error {
|
|
25
|
+
constructor(name) {
|
|
26
|
+
super(`Command "${name}" cannot exist with its parent`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
class SubcommandExistsError extends Error {
|
|
30
|
+
constructor(name) {
|
|
31
|
+
super(`Command "${name}" cannot exist with its subcommand`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const resolveFlagAlias = (_command) => Object.entries((_command == null ? void 0 : _command.flags) || {}).reduce((acc, [name, command]) => {
|
|
36
|
+
if (command.alias) {
|
|
37
|
+
const item = mustArray(command.alias).map(kebabCase);
|
|
38
|
+
acc[kebabCase(name)] = item;
|
|
39
|
+
}
|
|
40
|
+
return acc;
|
|
41
|
+
}, {});
|
|
42
|
+
const resolveFlagDefault = (_command) => Object.entries((_command == null ? void 0 : _command.flags) || {}).reduce((acc, [name, command]) => {
|
|
43
|
+
const item = command.default;
|
|
44
|
+
if (item) {
|
|
45
|
+
acc[name] = item;
|
|
46
|
+
}
|
|
47
|
+
return acc;
|
|
48
|
+
}, {});
|
|
49
|
+
function resolveCommand(commands, name) {
|
|
50
|
+
if (name === SingleCommand) {
|
|
51
|
+
return commands[SingleCommand];
|
|
52
|
+
}
|
|
53
|
+
const nameArr = Array.isArray(name) ? name : name.split(" ");
|
|
54
|
+
const nameString = nameArr.join(" ");
|
|
55
|
+
const possibleCommands = Object.values(commands).filter(
|
|
56
|
+
(c) => arrayStartsWith(nameArr, c.name.split(" ")) || mustArray(c.alias || []).map(String).includes(nameString)
|
|
57
|
+
);
|
|
58
|
+
if (possibleCommands.length > 1) {
|
|
59
|
+
throw new Error(`Multiple commands found with name "${nameString}"`);
|
|
60
|
+
}
|
|
61
|
+
return possibleCommands[0];
|
|
62
|
+
}
|
|
63
|
+
function resolveSubcommandsByParent(commands, parent, depth = Infinity) {
|
|
64
|
+
const parentArr = parent === "" ? [] : Array.isArray(parent) ? parent : parent.split(" ");
|
|
65
|
+
return Object.values(commands).filter((c) => {
|
|
66
|
+
const commandNameArr = c.name.split(" ");
|
|
67
|
+
return arrayStartsWith(commandNameArr, parentArr) && commandNameArr.length - parentArr.length <= depth;
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
const resolveRootCommands = (commands) => resolveSubcommandsByParent(commands, "", 1);
|
|
71
|
+
const resolveArgv = () => isNode() ? process.argv.slice(2) : isDeno() ? Deno.args : [];
|
|
72
|
+
function compose(inspectors) {
|
|
73
|
+
return (getCtx) => {
|
|
74
|
+
return dispatch(0);
|
|
75
|
+
function dispatch(i) {
|
|
76
|
+
const inspector = inspectors[i];
|
|
77
|
+
return inspector(getCtx(), dispatch.bind(null, i + 1));
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
var __accessCheck = (obj, member, msg) => {
|
|
83
|
+
if (!member.has(obj))
|
|
84
|
+
throw TypeError("Cannot " + msg);
|
|
85
|
+
};
|
|
86
|
+
var __privateGet = (obj, member, getter) => {
|
|
87
|
+
__accessCheck(obj, member, "read from private field");
|
|
88
|
+
return getter ? getter.call(obj) : member.get(obj);
|
|
89
|
+
};
|
|
90
|
+
var __privateAdd = (obj, member, value) => {
|
|
91
|
+
if (member.has(obj))
|
|
92
|
+
throw TypeError("Cannot add the same private member more than once");
|
|
93
|
+
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
94
|
+
};
|
|
95
|
+
var __privateSet = (obj, member, value, setter) => {
|
|
96
|
+
__accessCheck(obj, member, "write to private field");
|
|
97
|
+
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
98
|
+
return value;
|
|
99
|
+
};
|
|
100
|
+
var _name, _description, _version, _inspectors, _commands, _commandEmitter, _isSingleCommand, isSingleCommand_get, _hasCommands, hasCommands_get;
|
|
101
|
+
const SingleCommand = Symbol("SingleCommand");
|
|
102
|
+
const _Clerc = class {
|
|
103
|
+
constructor() {
|
|
104
|
+
__privateAdd(this, _isSingleCommand);
|
|
105
|
+
__privateAdd(this, _hasCommands);
|
|
106
|
+
__privateAdd(this, _name, "");
|
|
107
|
+
__privateAdd(this, _description, "");
|
|
108
|
+
__privateAdd(this, _version, "");
|
|
109
|
+
__privateAdd(this, _inspectors, []);
|
|
110
|
+
__privateAdd(this, _commands, {});
|
|
111
|
+
__privateAdd(this, _commandEmitter, new LiteEmit());
|
|
112
|
+
}
|
|
113
|
+
get _name() {
|
|
114
|
+
return __privateGet(this, _name);
|
|
115
|
+
}
|
|
116
|
+
get _description() {
|
|
117
|
+
return __privateGet(this, _description);
|
|
118
|
+
}
|
|
119
|
+
get _version() {
|
|
120
|
+
return __privateGet(this, _version);
|
|
121
|
+
}
|
|
122
|
+
get _inspectors() {
|
|
123
|
+
return __privateGet(this, _inspectors);
|
|
124
|
+
}
|
|
125
|
+
get _commands() {
|
|
126
|
+
return __privateGet(this, _commands);
|
|
127
|
+
}
|
|
128
|
+
static create() {
|
|
129
|
+
return new _Clerc();
|
|
130
|
+
}
|
|
131
|
+
name(name) {
|
|
132
|
+
__privateSet(this, _name, name);
|
|
133
|
+
return this;
|
|
134
|
+
}
|
|
135
|
+
description(description) {
|
|
136
|
+
__privateSet(this, _description, description);
|
|
137
|
+
return this;
|
|
138
|
+
}
|
|
139
|
+
version(version) {
|
|
140
|
+
__privateSet(this, _version, version);
|
|
141
|
+
return this;
|
|
142
|
+
}
|
|
143
|
+
command(name, description, options = {}) {
|
|
144
|
+
if (__privateGet(this, _commands)[name]) {
|
|
145
|
+
if (name === SingleCommand) {
|
|
146
|
+
throw new CommandExistsError("Single command already exists");
|
|
147
|
+
}
|
|
148
|
+
throw new CommandExistsError(`Command "${name === SingleCommand ? "[SingleCommand]" : name}" already exists`);
|
|
149
|
+
}
|
|
150
|
+
if (__privateGet(this, _isSingleCommand, isSingleCommand_get)) {
|
|
151
|
+
throw new SingleCommandError();
|
|
152
|
+
}
|
|
153
|
+
if (name === SingleCommand && __privateGet(this, _hasCommands, hasCommands_get)) {
|
|
154
|
+
throw new CommonCommandExistsError();
|
|
155
|
+
}
|
|
156
|
+
if (name !== SingleCommand) {
|
|
157
|
+
const splitedName = name.split(" ");
|
|
158
|
+
const existedCommandNames = Object.keys(__privateGet(this, _commands)).filter((name2) => typeof name2 === "string").map((name2) => name2.split(" "));
|
|
159
|
+
if (existedCommandNames.some((name2) => arrayStartsWith(splitedName, name2))) {
|
|
160
|
+
throw new ParentCommandExistsError(splitedName.join(" "));
|
|
161
|
+
}
|
|
162
|
+
if (existedCommandNames.some((name2) => arrayStartsWith(name2, splitedName))) {
|
|
163
|
+
throw new SubcommandExistsError(splitedName.join(" "));
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
__privateGet(this, _commands)[name] = { name, description, ...options };
|
|
167
|
+
return this;
|
|
168
|
+
}
|
|
169
|
+
on(name, handler) {
|
|
170
|
+
__privateGet(this, _commandEmitter).on(name, handler);
|
|
171
|
+
return this;
|
|
172
|
+
}
|
|
173
|
+
use(plugin) {
|
|
174
|
+
return plugin.setup(this);
|
|
175
|
+
}
|
|
176
|
+
inspector(inspector) {
|
|
177
|
+
__privateGet(this, _inspectors).push(inspector);
|
|
178
|
+
return this;
|
|
179
|
+
}
|
|
180
|
+
parse(argv = resolveArgv()) {
|
|
181
|
+
const parsed = mri(argv);
|
|
182
|
+
const name = parsed._.map(String);
|
|
183
|
+
const stringName = name.join(" ");
|
|
184
|
+
const getCommand = () => __privateGet(this, _isSingleCommand, isSingleCommand_get) ? __privateGet(this, _commands)[SingleCommand] : resolveCommand(__privateGet(this, _commands), name);
|
|
185
|
+
const getContext = () => {
|
|
186
|
+
const command = getCommand();
|
|
187
|
+
const isCommandResolved = !!command;
|
|
188
|
+
const parsedWithType = typeFlag((command == null ? void 0 : command.flags) || {}, [...argv]);
|
|
189
|
+
const { _: args, flags } = parsedWithType;
|
|
190
|
+
const parameters = __privateGet(this, _isSingleCommand, isSingleCommand_get) || !isCommandResolved ? args : args.slice(command.name.split(" ").length);
|
|
191
|
+
const context = {
|
|
192
|
+
name: command == null ? void 0 : command.name,
|
|
193
|
+
resolved: isCommandResolved,
|
|
194
|
+
isSingleCommand: __privateGet(this, _isSingleCommand, isSingleCommand_get),
|
|
195
|
+
raw: parsedWithType,
|
|
196
|
+
parameters,
|
|
197
|
+
flags,
|
|
198
|
+
unknownFlags: parsedWithType.unknownFlags,
|
|
199
|
+
cli: this
|
|
200
|
+
};
|
|
201
|
+
return context;
|
|
202
|
+
};
|
|
203
|
+
const emitHandler = () => {
|
|
204
|
+
const command = getCommand();
|
|
205
|
+
const handlerContext = getContext();
|
|
206
|
+
if (!command) {
|
|
207
|
+
throw new NoSuchCommandError(stringName);
|
|
208
|
+
}
|
|
209
|
+
__privateGet(this, _commandEmitter).emit(command.name, handlerContext);
|
|
210
|
+
};
|
|
211
|
+
const inspectors = [...__privateGet(this, _inspectors), emitHandler];
|
|
212
|
+
const inspector = compose(inspectors);
|
|
213
|
+
inspector(getContext);
|
|
214
|
+
return this;
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
let Clerc = _Clerc;
|
|
218
|
+
_name = new WeakMap();
|
|
219
|
+
_description = new WeakMap();
|
|
220
|
+
_version = new WeakMap();
|
|
221
|
+
_inspectors = new WeakMap();
|
|
222
|
+
_commands = new WeakMap();
|
|
223
|
+
_commandEmitter = new WeakMap();
|
|
224
|
+
_isSingleCommand = new WeakSet();
|
|
225
|
+
isSingleCommand_get = function() {
|
|
226
|
+
return __privateGet(this, _commands)[SingleCommand] !== void 0;
|
|
227
|
+
};
|
|
228
|
+
_hasCommands = new WeakSet();
|
|
229
|
+
hasCommands_get = function() {
|
|
230
|
+
return Object.keys(__privateGet(this, _commands)).length > 0;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
const definePlugin = (p) => p;
|
|
234
|
+
const defineHandler = (_cli, _key, handler) => handler;
|
|
235
|
+
const defineInspector = (_cli, inspector) => inspector;
|
|
236
|
+
|
|
237
|
+
export { Clerc, CommandExistsError, CommonCommandExistsError, NoSuchCommandError, ParentCommandExistsError, SingleCommand, SingleCommandError, SubcommandExistsError, compose, defineHandler, defineInspector, definePlugin, resolveArgv, resolveCommand, resolveFlagAlias, resolveFlagDefault, resolveRootCommands, resolveSubcommandsByParent };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clerc",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"author": "Ray <nn_201312@163.com> (https://github.com/so1ve)",
|
|
5
5
|
"description": "Clerc is a simple and easy-to-use cli framework.",
|
|
6
6
|
"keywords": [
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"access": "public"
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@clerc/utils": "0.
|
|
42
|
+
"@clerc/utils": "0.5.0",
|
|
43
43
|
"is-platform": "^0.2.0",
|
|
44
44
|
"lite-emit": "^1.4.0",
|
|
45
45
|
"mri": "^1.2.0",
|