clerc 0.3.4 → 0.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clerc",
3
- "version": "0.3.4",
3
+ "version": "0.4.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.3.4",
42
+ "@clerc/utils": "0.4.0",
43
43
  "is-platform": "^0.2.0",
44
44
  "lite-emit": "^1.4.0",
45
45
  "mri": "^1.2.0",
package/dist/index.cjs DELETED
@@ -1,168 +0,0 @@
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 isPlatform = require('is-platform');
9
- var utils = require('@clerc/utils');
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
- }
17
- class CommandExistsError extends Error {
18
- }
19
- class CommonCommandExistsError extends Error {
20
- }
21
- class NoSuchCommandError extends Error {
22
- }
23
-
24
- const resolveFlagAlias = (_command) => Object.entries((_command == null ? void 0 : _command.flags) || {}).reduce((acc, [name, command]) => {
25
- if (command.alias) {
26
- const item = utils.mustArray(command.alias).map(utils.kebabCase);
27
- acc[utils.kebabCase(name)] = item;
28
- }
29
- return acc;
30
- }, {});
31
- const resolveFlagDefault = (_command) => Object.entries((_command == null ? void 0 : _command.flags) || {}).reduce((acc, [name, command]) => {
32
- const item = command.default;
33
- if (item) {
34
- acc[name] = item;
35
- }
36
- return acc;
37
- }, {});
38
- function resolveCommand(commands, name) {
39
- if (name === SingleCommand) {
40
- return commands[SingleCommand];
41
- }
42
- const possibleCommands = Object.values(commands).filter(
43
- (c) => c.name === name || utils.mustArray(c.alias || []).map(String).includes(name)
44
- );
45
- if (possibleCommands.length > 1) {
46
- throw new Error(`Multiple commands found with name "${name}"`);
47
- }
48
- return possibleCommands[0];
49
- }
50
- const resolveArgv = () => isPlatform.isNode() ? process.argv.slice(2) : isPlatform.isDeno() ? Deno.args : [];
51
- function compose(inspectors) {
52
- return (ctx) => {
53
- return dispatch(0);
54
- function dispatch(i) {
55
- const inspector = inspectors[i];
56
- return inspector(ctx, dispatch.bind(null, i + 1));
57
- }
58
- };
59
- }
60
-
61
- const SingleCommand = Symbol("SingleCommand");
62
- class Clerc {
63
- constructor() {
64
- this._name = "";
65
- this._description = "";
66
- this._version = "";
67
- this._inspectors = [];
68
- this._commands = {};
69
- this.__commandEmitter = new liteEmit.LiteEmit();
70
- }
71
- get __isSingleCommand() {
72
- return this._commands[SingleCommand] !== void 0;
73
- }
74
- get __hasCommands() {
75
- return Object.keys(this._commands).length > 0;
76
- }
77
- static create() {
78
- return new Clerc();
79
- }
80
- name(name) {
81
- this._name = name;
82
- return this;
83
- }
84
- description(description) {
85
- this._description = description;
86
- return this;
87
- }
88
- version(version) {
89
- this._version = version;
90
- return this;
91
- }
92
- command(name, description, options = {}) {
93
- if (this._commands[name]) {
94
- if (name === SingleCommand) {
95
- throw new CommandExistsError("Single command already exists");
96
- }
97
- throw new CommandExistsError(`Command "${name === SingleCommand ? "[SingleCommand]" : name}" already exists`);
98
- }
99
- if (this.__isSingleCommand) {
100
- throw new SingleCommandError("Single command mode enabled");
101
- }
102
- if (name === SingleCommand && this.__hasCommands) {
103
- throw new CommonCommandExistsError("Common command exists");
104
- }
105
- const { alias, flags } = options;
106
- this._commands[name] = { name, description, alias, flags };
107
- return this;
108
- }
109
- on(name, handler) {
110
- this.__commandEmitter.on(name, handler);
111
- return this;
112
- }
113
- use(plugin) {
114
- return plugin.setup(this);
115
- }
116
- inspector(inspector) {
117
- this._inspectors.push(inspector);
118
- return this;
119
- }
120
- parse(argv = resolveArgv()) {
121
- const parsed = mri__default["default"](argv);
122
- const name = String(parsed._[0]);
123
- const command = this.__isSingleCommand ? this._commands[SingleCommand] : resolveCommand(this._commands, name);
124
- const isCommandResolved = !!command;
125
- const parsedWithType = typeFlag.typeFlag((command == null ? void 0 : command.flags) || {}, argv);
126
- const { _: args, flags } = parsedWithType;
127
- const parameters = this.__isSingleCommand || !isCommandResolved ? args : args.slice(1);
128
- const inspectorContext = {
129
- name: command == null ? void 0 : command.name,
130
- resolved: isCommandResolved,
131
- isSingleCommand: this.__isSingleCommand,
132
- raw: parsedWithType,
133
- parameters,
134
- flags,
135
- unknownFlags: parsedWithType.unknownFlags,
136
- cli: this
137
- };
138
- const handlerContext = inspectorContext;
139
- const emitHandler = () => {
140
- if (!command) {
141
- throw new NoSuchCommandError(`No such command: ${name}`);
142
- }
143
- this.__commandEmitter.emit(command.name, handlerContext);
144
- };
145
- const inspectors = [...this._inspectors, emitHandler];
146
- const inspector = compose(inspectors);
147
- inspector(inspectorContext);
148
- }
149
- }
150
-
151
- const definePlugin = (p) => p;
152
- const defineHandler = (_cli, _key, handler) => handler;
153
- const defineInspector = (_cli, inspector) => inspector;
154
-
155
- exports.Clerc = Clerc;
156
- exports.CommandExistsError = CommandExistsError;
157
- exports.CommonCommandExistsError = CommonCommandExistsError;
158
- exports.NoSuchCommandError = NoSuchCommandError;
159
- exports.SingleCommand = SingleCommand;
160
- exports.SingleCommandError = SingleCommandError;
161
- exports.compose = compose;
162
- exports.defineHandler = defineHandler;
163
- exports.defineInspector = defineInspector;
164
- exports.definePlugin = definePlugin;
165
- exports.resolveArgv = resolveArgv;
166
- exports.resolveCommand = resolveCommand;
167
- exports.resolveFlagAlias = resolveFlagAlias;
168
- exports.resolveFlagDefault = resolveFlagDefault;
package/dist/index.d.ts DELETED
@@ -1,271 +0,0 @@
1
- import { MaybeArray, Dict, LiteralUnion } from '@clerc/utils';
2
-
3
- declare const DOUBLE_DASH = "--";
4
- declare type TypeFunction<ReturnType = any> = (value: any) => ReturnType;
5
- declare type TypeFunctionArray<ReturnType> = readonly [TypeFunction<ReturnType>];
6
- declare type FlagType<ReturnType = any> = TypeFunction<ReturnType> | TypeFunctionArray<ReturnType>;
7
- declare type FlagSchemaBase<TF> = {
8
- /**
9
- Type of the flag as a function that parses the argv string and returns the parsed value.
10
-
11
- @example
12
- ```
13
- type: String
14
- ```
15
-
16
- @example Wrap in an array to accept multiple values.
17
- ```
18
- type: [Boolean]
19
- ```
20
-
21
- @example Custom function type that uses moment.js to parse string as date.
22
- ```
23
- type: function CustomDate(value: string) {
24
- return moment(value).toDate();
25
- }
26
- ```
27
- */
28
- type: TF;
29
- /**
30
- A single-character alias for the flag.
31
-
32
- @example
33
- ```
34
- alias: 's'
35
- ```
36
- */
37
- alias?: string;
38
- } & Record<PropertyKey, unknown>;
39
- declare type FlagSchemaDefault<TF, DefaultType = any> = FlagSchemaBase<TF> & {
40
- /**
41
- Default value of the flag. Also accepts a function that returns the default value.
42
- [Default: undefined]
43
-
44
- @example
45
- ```
46
- default: 'hello'
47
- ```
48
-
49
- @example
50
- ```
51
- default: () => [1, 2, 3]
52
- ```
53
- */
54
- default: DefaultType | (() => DefaultType);
55
- };
56
- declare type FlagSchema<TF = FlagType> = (FlagSchemaBase<TF> | FlagSchemaDefault<TF>);
57
- declare type FlagTypeOrSchema<ExtraOptions = Record<string, unknown>> = FlagType | (FlagSchema & ExtraOptions);
58
- declare type Flags<ExtraOptions = Record<string, unknown>> = Record<string, FlagTypeOrSchema<ExtraOptions>>;
59
- declare 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));
60
- interface ParsedFlags<Schemas = Record<string, unknown>> {
61
- flags: Schemas;
62
- unknownFlags: Record<string, (string | boolean)[]>;
63
- _: string[] & {
64
- [DOUBLE_DASH]: string[];
65
- };
66
- }
67
- declare type TypeFlag<Schemas extends Flags> = ParsedFlags<{
68
- [flag in keyof Schemas]: InferFlagType<Schemas[flag]>;
69
- }>;
70
-
71
- declare type FlagOptions = FlagSchema & {
72
- description: string;
73
- required?: boolean;
74
- };
75
- declare type Flag = FlagOptions & {
76
- name: string;
77
- };
78
- interface CommandOptions<A extends MaybeArray<string> = MaybeArray<string>, F extends Dict<FlagOptions> = Dict<FlagOptions>> {
79
- alias?: A;
80
- flags?: F;
81
- }
82
- declare type Command<N extends string | SingleCommandType = string, D extends string = string, Options extends CommandOptions = CommandOptions> = Options & {
83
- name: N;
84
- description: D;
85
- };
86
- declare type CommandRecord = Dict<Command> & {
87
- [SingleCommand]?: Command;
88
- };
89
- declare type MakeEventMap<T extends CommandRecord> = {
90
- [K in keyof T]: [InspectorContext];
91
- };
92
- declare type PossibleInputKind = string | number | boolean | Dict<any>;
93
- declare type NonNullableFlag<T extends Dict<FlagOptions> | undefined> = T extends undefined ? {} : NonNullable<T>;
94
- interface HandlerContext<C extends CommandRecord = CommandRecord, N extends keyof C = keyof C> {
95
- name?: N;
96
- resolved: boolean;
97
- isSingleCommand: boolean;
98
- raw: ParsedFlags;
99
- parameters: PossibleInputKind[];
100
- unknownFlags: ParsedFlags["unknownFlags"];
101
- flags: TypeFlag<NonNullableFlag<C[N]["flags"]>>["flags"];
102
- cli: Clerc<C>;
103
- }
104
- declare type Handler<C extends CommandRecord = CommandRecord, K extends keyof C = keyof C> = (ctx: HandlerContext<C, K>) => void;
105
- declare type FallbackType<T, U> = {} extends T ? U : T;
106
- declare type InspectorContext<C extends CommandRecord = CommandRecord> = HandlerContext<C> & {
107
- flags: FallbackType<TypeFlag<NonNullableFlag<C[keyof C]["flags"]>>["flags"], Dict<any>>;
108
- };
109
- declare type Inspector<C extends CommandRecord = CommandRecord> = (ctx: InspectorContext<C>, next: () => void) => void;
110
- interface Plugin<T extends Clerc = Clerc, U extends Clerc = Clerc> {
111
- setup: (cli: T) => U;
112
- }
113
-
114
- declare const SingleCommand: unique symbol;
115
- declare type SingleCommandType = typeof SingleCommand;
116
- declare class Clerc<C extends CommandRecord = {}> {
117
- _name: string;
118
- _description: string;
119
- _version: string;
120
- _inspectors: Inspector[];
121
- _commands: C;
122
- private __commandEmitter;
123
- private constructor();
124
- private get __isSingleCommand();
125
- private get __hasCommands();
126
- /**
127
- * Create a new cli
128
- * @returns
129
- * @example
130
- * ```ts
131
- * const cli = Clerc.create()
132
- * ```
133
- */
134
- static create(): Clerc<{}>;
135
- /**
136
- * Set the name of the cli
137
- * @param name
138
- * @returns
139
- * @example
140
- * ```ts
141
- * Clerc.create()
142
- * .name("test")
143
- * ```
144
- */
145
- name(name: string): this;
146
- /**
147
- * Set the description of the cli
148
- * @param description
149
- * @returns
150
- * @example
151
- * ```ts
152
- * Clerc.create()
153
- * .description("test cli")
154
- */
155
- description(description: string): this;
156
- /**
157
- * Set the version of the cli
158
- * @param version
159
- * @returns
160
- * @example
161
- * ```ts
162
- * Clerc.create()
163
- * .version("1.0.0")
164
- */
165
- version(version: string): this;
166
- /**
167
- * Register a command
168
- * @param name
169
- * @param description
170
- * @param options
171
- * @returns
172
- * @example
173
- * ```ts
174
- * Clerc.create()
175
- * .command("test", "test command", {
176
- * alias: "t",
177
- * flags: {
178
- * foo: {
179
- * alias: "f",
180
- * description: "foo flag",
181
- * }
182
- * }
183
- * })
184
- * ```
185
- * @example
186
- * ```ts
187
- * Clerc.create()
188
- * .command("", "single command", {
189
- * flags: {
190
- * foo: {
191
- * alias: "f",
192
- * description: "foo flag",
193
- * }
194
- * }
195
- * })
196
- * ```
197
- */
198
- 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>>>;
199
- /**
200
- * Register a handler
201
- * @param name
202
- * @param handler
203
- * @returns
204
- * @example
205
- * ```ts
206
- * Clerc.create()
207
- * .command("test", "test command")
208
- * .on("test", (ctx) => {
209
- * console.log(ctx);
210
- * })
211
- * ```
212
- */
213
- on<K extends keyof CM, CM extends this["_commands"] = this["_commands"]>(name: LiteralUnion<K, string>, handler: Handler<CM, K>): this;
214
- /**
215
- * Use a plugin
216
- * @param plugin
217
- * @returns
218
- * @example
219
- * ```ts
220
- * Clerc.create()
221
- * .use(plugin)
222
- * ```
223
- */
224
- use<T extends Clerc, U extends Clerc>(plugin: Plugin<T, U>): U;
225
- /**
226
- * Register a inspector
227
- * @param inspector
228
- * @returns
229
- * @example
230
- * ```ts
231
- * Clerc.create()
232
- * .inspector((ctx, next) => {
233
- * console.log(ctx);
234
- * next();
235
- * })
236
- * ```
237
- */
238
- inspector(inspector: Inspector): this;
239
- /**
240
- * Parse the command line arguments
241
- * @param args
242
- * @returns
243
- * @example
244
- * ```ts
245
- * Clerc.create()
246
- * .parse(process.argv.slice(2)) // Optional
247
- * ```
248
- */
249
- parse(argv?: string[]): void;
250
- }
251
-
252
- declare const definePlugin: <T extends Clerc<{}>, U extends Clerc<{}>>(p: Plugin<T, U>) => Plugin<T, U>;
253
- declare const defineHandler: <C extends Clerc<{}>, K extends keyof C["_commands"]>(_cli: C, _key: K, handler: Handler<C["_commands"], K>) => Handler<C["_commands"], K>;
254
- declare const defineInspector: <C extends Clerc<{}>>(_cli: C, inspector: Inspector<C["_commands"]>) => Inspector<C["_commands"]>;
255
-
256
- declare class SingleCommandError extends Error {
257
- }
258
- declare class CommandExistsError extends Error {
259
- }
260
- declare class CommonCommandExistsError extends Error {
261
- }
262
- declare class NoSuchCommandError extends Error {
263
- }
264
-
265
- declare const resolveFlagAlias: (_command: Command) => Dict<string[]>;
266
- declare const resolveFlagDefault: (_command: Command) => Dict<any>;
267
- declare function resolveCommand(commands: CommandRecord, name: string | SingleCommandType): Command | undefined;
268
- declare const resolveArgv: () => string[];
269
- declare function compose(inspectors: Inspector[]): (ctx: InspectorContext) => void;
270
-
271
- export { Clerc, Command, CommandExistsError, CommandOptions, CommandRecord, CommonCommandExistsError, FallbackType, Flag, FlagOptions, Handler, HandlerContext, Inspector, InspectorContext, MakeEventMap, NoSuchCommandError, Plugin, PossibleInputKind, SingleCommand, SingleCommandError, SingleCommandType, compose, defineHandler, defineInspector, definePlugin, resolveArgv, resolveCommand, resolveFlagAlias, resolveFlagDefault };
package/dist/index.mjs DELETED
@@ -1,147 +0,0 @@
1
- import { LiteEmit } from 'lite-emit';
2
- import mri from 'mri';
3
- import { typeFlag } from 'type-flag';
4
- import { isNode, isDeno } from 'is-platform';
5
- import { mustArray, kebabCase } from '@clerc/utils';
6
-
7
- class SingleCommandError extends Error {
8
- }
9
- class CommandExistsError extends Error {
10
- }
11
- class CommonCommandExistsError extends Error {
12
- }
13
- class NoSuchCommandError extends Error {
14
- }
15
-
16
- const resolveFlagAlias = (_command) => Object.entries((_command == null ? void 0 : _command.flags) || {}).reduce((acc, [name, command]) => {
17
- if (command.alias) {
18
- const item = mustArray(command.alias).map(kebabCase);
19
- acc[kebabCase(name)] = item;
20
- }
21
- return acc;
22
- }, {});
23
- const resolveFlagDefault = (_command) => Object.entries((_command == null ? void 0 : _command.flags) || {}).reduce((acc, [name, command]) => {
24
- const item = command.default;
25
- if (item) {
26
- acc[name] = item;
27
- }
28
- return acc;
29
- }, {});
30
- function resolveCommand(commands, name) {
31
- if (name === SingleCommand) {
32
- return commands[SingleCommand];
33
- }
34
- const possibleCommands = Object.values(commands).filter(
35
- (c) => c.name === name || mustArray(c.alias || []).map(String).includes(name)
36
- );
37
- if (possibleCommands.length > 1) {
38
- throw new Error(`Multiple commands found with name "${name}"`);
39
- }
40
- return possibleCommands[0];
41
- }
42
- const resolveArgv = () => isNode() ? process.argv.slice(2) : isDeno() ? Deno.args : [];
43
- function compose(inspectors) {
44
- return (ctx) => {
45
- return dispatch(0);
46
- function dispatch(i) {
47
- const inspector = inspectors[i];
48
- return inspector(ctx, dispatch.bind(null, i + 1));
49
- }
50
- };
51
- }
52
-
53
- const SingleCommand = Symbol("SingleCommand");
54
- class Clerc {
55
- constructor() {
56
- this._name = "";
57
- this._description = "";
58
- this._version = "";
59
- this._inspectors = [];
60
- this._commands = {};
61
- this.__commandEmitter = new LiteEmit();
62
- }
63
- get __isSingleCommand() {
64
- return this._commands[SingleCommand] !== void 0;
65
- }
66
- get __hasCommands() {
67
- return Object.keys(this._commands).length > 0;
68
- }
69
- static create() {
70
- return new Clerc();
71
- }
72
- name(name) {
73
- this._name = name;
74
- return this;
75
- }
76
- description(description) {
77
- this._description = description;
78
- return this;
79
- }
80
- version(version) {
81
- this._version = version;
82
- return this;
83
- }
84
- command(name, description, options = {}) {
85
- if (this._commands[name]) {
86
- if (name === SingleCommand) {
87
- throw new CommandExistsError("Single command already exists");
88
- }
89
- throw new CommandExistsError(`Command "${name === SingleCommand ? "[SingleCommand]" : name}" already exists`);
90
- }
91
- if (this.__isSingleCommand) {
92
- throw new SingleCommandError("Single command mode enabled");
93
- }
94
- if (name === SingleCommand && this.__hasCommands) {
95
- throw new CommonCommandExistsError("Common command exists");
96
- }
97
- const { alias, flags } = options;
98
- this._commands[name] = { name, description, alias, flags };
99
- return this;
100
- }
101
- on(name, handler) {
102
- this.__commandEmitter.on(name, handler);
103
- return this;
104
- }
105
- use(plugin) {
106
- return plugin.setup(this);
107
- }
108
- inspector(inspector) {
109
- this._inspectors.push(inspector);
110
- return this;
111
- }
112
- parse(argv = resolveArgv()) {
113
- const parsed = mri(argv);
114
- const name = String(parsed._[0]);
115
- const command = this.__isSingleCommand ? this._commands[SingleCommand] : resolveCommand(this._commands, name);
116
- const isCommandResolved = !!command;
117
- const parsedWithType = typeFlag((command == null ? void 0 : command.flags) || {}, argv);
118
- const { _: args, flags } = parsedWithType;
119
- const parameters = this.__isSingleCommand || !isCommandResolved ? args : args.slice(1);
120
- const inspectorContext = {
121
- name: command == null ? void 0 : command.name,
122
- resolved: isCommandResolved,
123
- isSingleCommand: this.__isSingleCommand,
124
- raw: parsedWithType,
125
- parameters,
126
- flags,
127
- unknownFlags: parsedWithType.unknownFlags,
128
- cli: this
129
- };
130
- const handlerContext = inspectorContext;
131
- const emitHandler = () => {
132
- if (!command) {
133
- throw new NoSuchCommandError(`No such command: ${name}`);
134
- }
135
- this.__commandEmitter.emit(command.name, handlerContext);
136
- };
137
- const inspectors = [...this._inspectors, emitHandler];
138
- const inspector = compose(inspectors);
139
- inspector(inspectorContext);
140
- }
141
- }
142
-
143
- const definePlugin = (p) => p;
144
- const defineHandler = (_cli, _key, handler) => handler;
145
- const defineInspector = (_cli, inspector) => inspector;
146
-
147
- export { Clerc, CommandExistsError, CommonCommandExistsError, NoSuchCommandError, SingleCommand, SingleCommandError, compose, defineHandler, defineInspector, definePlugin, resolveArgv, resolveCommand, resolveFlagAlias, resolveFlagDefault };