@clerc/core 0.44.0 → 1.0.0-beta.2

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.
Files changed (3) hide show
  1. package/dist/index.d.ts +240 -479
  2. package/dist/index.js +310 -813
  3. package/package.json +12 -15
package/dist/index.d.ts CHANGED
@@ -1,498 +1,259 @@
1
- import { Equals, Dict, CamelCase, MaybeArray as MaybeArray$1 } from '@clerc/utils';
2
- import { OmitIndexSignature, LiteralUnion, Simplify } from 'type-fest';
1
+ import { ErrorHandler as ErrorHandler$1 } from "lite-emit";
3
2
 
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
11
- * parsed value.
12
- *
13
- * @example
14
- *
15
- * ```
16
- * type: String;
17
- * ```
18
- *
19
- * @example Wrap in an array to accept multiple values. `type: [Boolean]`
20
- *
21
- * @example Custom function type that uses moment.js to parse string as date.
22
- * `type: function CustomDate(value: string) { return moment(value).toDate();
23
- * }`
24
- */
25
- type: TF;
26
- /**
27
- * A single-character alias for the flag.
28
- *
29
- * @example
30
- *
31
- * ```
32
- * alias: "s";
33
- * ```
34
- */
35
- alias?: string;
36
- } & Record<PropertyKey, unknown>;
37
- type FlagSchemaDefault<TF, DefaultType = any> = FlagSchemaBase<TF> & {
38
- /**
39
- * Default value of the flag. Also accepts a function that returns the default
40
- * value. [Default: undefined]
41
- *
42
- * @example
43
- *
44
- * ```
45
- * default: 'hello'
46
- * ```
47
- *
48
- * @example
49
- *
50
- * ```
51
- * default: () => [1, 2, 3]
52
- * ```
53
- */
54
- default: DefaultType | (() => DefaultType);
55
- };
56
- type FlagSchema<TF = FlagType> = FlagSchemaBase<TF> | FlagSchemaDefault<TF>;
57
- type FlagTypeOrSchema<ExtraOptions = Record<string, unknown>> = FlagType | (FlagSchema & ExtraOptions);
58
- type Flags$1<ExtraOptions = Record<string, unknown>> = Record<string, FlagTypeOrSchema<ExtraOptions>>;
59
- 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
- };
3
+ //#region ../utils/src/types/type-fest.d.ts
4
+ type LiteralUnion<LiteralType, BaseType> = LiteralType | (BaseType & Record<never, never>);
5
+ type Prettify<T> = { [K in keyof T]: T[K] } & {};
6
+ type Primitive = null | undefined | string | number | boolean | symbol | bigint;
7
+ type BuiltIns = Primitive | void | Date | RegExp;
8
+ type NonRecursiveType = BuiltIns | Function | (new (...arguments_: any[]) => unknown) | Promise<unknown>;
9
+ type UnknownArray = readonly unknown[];
10
+ type MapsSetsOrArrays = ReadonlyMap<unknown, unknown> | WeakMap<WeakKey, unknown> | ReadonlySet<unknown> | WeakSet<WeakKey> | UnknownArray;
11
+ type ConditionalDeepPrettify<T, E = never, I$1 = unknown> = T extends E ? T : T extends I$1 ? { [TypeKey in keyof T]: ConditionalDeepPrettify<T[TypeKey], E, I$1> } : T;
12
+ type DeepPrettify<T, E = never> = ConditionalDeepPrettify<T, E | NonRecursiveType | MapsSetsOrArrays, object>;
13
+ type IsAny<T> = 0 extends 1 & T ? true : false;
14
+ //#endregion
15
+ //#region ../utils/src/types/index.d.ts
16
+ type MaybeArray<T> = T | T[];
17
+ type PartialRequired<T, K$1 extends keyof T> = T & { [P in K$1]-?: T[P] };
18
+ type UnionToIntersection<U$1> = (U$1 extends any ? (k: U$1) => void : never) extends ((k: infer I) => void) ? I : never;
19
+ type CamelCase<S extends string> = S extends `${infer Head} ${infer Tail}` ? `${Head}${Capitalize<CamelCase<Tail>>}` : S extends `${infer Head}-${infer Tail}` ? `${Head}${Capitalize<CamelCase<Tail>>}` : S;
20
+ //#endregion
21
+ //#region ../parser/src/types.d.ts
22
+ type FlagDefaultValue<T = unknown> = T | (() => T);
23
+ /**
24
+ * Defines how a string input is converted to the target type T.
25
+ *
26
+ * @template T The target type.
27
+ */
28
+ type FlagTypeFunction<T = unknown> = (value: string) => T;
29
+ /**
30
+ * A callback function to conditionally stop parsing.
31
+ * When it returns true, parsing stops and remaining arguments are preserved in `ignored`.
32
+ *
33
+ * @param type - The type of the current argument: 'known-flag' or 'unknown-flag' for flags, 'parameter' for positional arguments
34
+ * @param arg - The current argument being processed
35
+ * @returns true to stop parsing, false to continue
36
+ */
37
+ type IgnoreFunction = (type: typeof KNOWN_FLAG | typeof UNKNOWN_FLAG | typeof PARAMETER, arg: string) => boolean;
38
+ type FlagType<T = unknown> = FlagTypeFunction<T> | readonly [FlagTypeFunction<T>];
39
+ interface BaseFlagOptions<T extends FlagType = FlagType> {
40
+ /**
41
+ * The type constructor or a function to convert the string value.
42
+ * To support multiple occurrences of a flag (e.g., --file a --file b), wrap the type in an array: [String], [Number].
43
+ * e.g., String, Number, [String], (val) => val.split(',')
44
+ */
45
+ type: T;
46
+ /** Aliases for the flag. */
47
+ alias?: MaybeArray<string>;
48
+ /** The default value of the flag. */
49
+ default?: unknown;
66
50
  }
67
- type TypeFlag<Schemas extends Flags$1> = ParsedFlags<{
68
- [flag in keyof Schemas]: InferFlagType<Schemas[flag]>;
69
- }>;
70
-
71
- type StripBrackets<Parameter extends string> = Parameter extends `<${infer ParameterName}>` | `[${infer ParameterName}]` ? ParameterName extends `${infer SpreadName}...` ? SpreadName : ParameterName : never;
72
- type ParameterType<Parameter extends string> = Parameter extends `<${infer _ParameterName}...>` | `[${infer _ParameterName}...]` ? string[] : Parameter extends `<${infer _ParameterName}>` ? string : Parameter extends `[${infer _ParameterName}]` ? string | undefined : never;
73
- type NonNullableParameters<T extends string[] | undefined> = T extends undefined ? [] : NonNullable<T>;
74
- type TransformParameters<C extends Command> = {
75
- [Parameter in NonNullableParameters<C["parameters"]>[number] as CamelCase<StripBrackets<Parameter>>]: ParameterType<Parameter>;
76
- };
77
- type MakeEventMap<T extends Commands> = {
78
- [K in keyof T]: [InterceptorContext];
79
- };
80
- type FallbackFlags<F extends Flags | undefined> = Equals<NonNullableFlag<F>["flags"], {}> extends true ? Dict<any> : NonNullableFlag<F>["flags"];
81
- type NonNullableFlag<F extends Flags | undefined> = TypeFlag<NonNullable<F>>;
82
- type ParseFlag<C extends Commands, N extends keyof C, GF extends GlobalFlagOptions = {}> = N extends keyof C ? OmitIndexSignature<NonNullableFlag<C[N]["flags"] & GF>["flags"]> : FallbackFlags<C[N]["flags"] & GF>["flags"];
83
- type ParseRaw<C extends Command, GF extends GlobalFlagOptions = {}> = NonNullableFlag<C["flags"] & GF> & {
84
- flags: FallbackFlags<C["flags"] & GF>;
85
- parameters: string[];
86
- mergedFlags: FallbackFlags<C["flags"] & GF> & NonNullableFlag<C["flags"] & GF>["unknownFlags"];
87
- };
88
- type ParseParameters<C extends Commands = Commands, N extends keyof C = keyof C> = Equals<TransformParameters<C[N]>, {}> extends true ? N extends keyof C ? TransformParameters<C[N]> : Dict<string | string[] | undefined> : TransformParameters<C[N]>;
89
-
90
- type Locales = Dict<Dict<string>>;
91
- type TranslateFn = (name: string, ...args: string[]) => string | undefined;
92
- interface I18N {
93
- add: (locales: Locales) => void;
94
- t: TranslateFn;
51
+ type FlagOptions = (BaseFlagOptions<BooleanConstructor> & {
52
+ /**
53
+ * Whether to enable the `--no-<flag>` syntax to set the value to false.
54
+ * Only useful for boolean flags.
55
+ * When set on a non-boolean flag, a type error will be shown.
56
+ *
57
+ * @default true
58
+ */
59
+ negatable?: boolean;
60
+ }) | (BaseFlagOptions & {
61
+ negatable?: never;
62
+ });
63
+ type FlagDefinitionValue = FlagOptions | FlagType;
64
+ type FlagsDefinition = Record<string, FlagDefinitionValue>;
65
+ type RawInputType = string | boolean;
66
+ interface ObjectInputType {
67
+ [key: string]: RawInputType | ObjectInputType;
95
68
  }
96
-
97
- interface Plugin<T extends Clerc = Clerc, U extends Clerc = Clerc> {
98
- setup: (cli: T) => U;
69
+ /**
70
+ * The parsed result.
71
+ * @template TFlags The specific flags type inferred from ParserOptions.
72
+ */
73
+ interface ParsedResult<TFlags extends Record<string, any>> {
74
+ /** Positional arguments or commands. */
75
+ parameters: string[];
76
+ /** Arguments after the `--` delimiter. */
77
+ doubleDash: string[];
78
+ /**
79
+ * The parsed flags.
80
+ * This is a strongly-typed object whose structure is inferred from the `flags` configuration in ParserOptions.
81
+ */
82
+ flags: TFlags;
83
+ /** The raw command-line arguments. */
84
+ raw: string[];
85
+ /** Unknown flags encountered during parsing. */
86
+ unknown: Record<string, RawInputType>;
87
+ /** Arguments that were not parsed due to ignore callback. */
88
+ ignored: string[];
99
89
  }
100
-
101
- type CommandType = RootType | string;
102
- type FlagOptions = FlagSchema & {
103
- description: string;
104
- };
105
- type Flag = FlagOptions & {
106
- name: string;
90
+ type InferFlagDefault<T extends FlagDefinitionValue, Fallback> = T extends {
91
+ default: FlagDefaultValue<infer DefaultType>;
92
+ } ? DefaultType : Fallback;
93
+ type IsTypeAny<T extends FlagDefinitionValue> = IsAny<T> extends true ? true : T extends {
94
+ type: infer Type;
95
+ } ? IsAny<Type> extends true ? true : false : false;
96
+ type _InferFlags<T extends FlagsDefinition> = { [K in keyof T]: IsTypeAny<T[K]> extends true ? any : T[K] extends readonly [BooleanConstructor] | {
97
+ type: readonly [BooleanConstructor];
98
+ } ? number : T[K] extends ObjectConstructor | {
99
+ type: ObjectConstructor;
100
+ } ? ObjectInputType : T[K] extends readonly [FlagType<infer U>] | {
101
+ type: readonly [FlagType<infer U>];
102
+ } ? U[] | InferFlagDefault<T[K], never> : T[K] extends FlagType<infer U> | {
103
+ type: FlagType<infer U>;
104
+ } ? U | InferFlagDefault<T[K], [U] extends [boolean] ? never : undefined> : never };
105
+ /**
106
+ * An advanced utility type that infers the exact type of the `flags` object in the parsed result,
107
+ * based on the provided `flags` configuration object T.
108
+ *
109
+ * @template T The type of the flags configuration object.
110
+ */
111
+ type InferFlags<T extends FlagsDefinition> = Prettify<_InferFlags<T>>;
112
+ //#endregion
113
+ //#region ../parser/src/iterator.d.ts
114
+ declare const KNOWN_FLAG = "known-flag";
115
+ declare const UNKNOWN_FLAG = "unknown-flag";
116
+ declare const PARAMETER = "parameter";
117
+ //#endregion
118
+ //#region ../parser/src/parse.d.ts
119
+ declare const DOUBLE_DASH = "--";
120
+ //#endregion
121
+ //#region src/types/clerc.d.ts
122
+ type ErrorHandler = (error: unknown) => void;
123
+ //#endregion
124
+ //#region src/types/flag.d.ts
125
+ type ClercFlagOptions = FlagOptions & {
126
+ description: string;
107
127
  };
108
- type GlobalFlagOption = FlagSchema;
109
- type Flags = Dict<FlagOptions>;
110
- type GlobalFlagOptions = Dict<GlobalFlagOption>;
111
- declare interface CommandCustomProperties {
128
+ type ClercFlagsDefinition = Record<string, ClercFlagOptions>;
129
+ //#endregion
130
+ //#region src/types/parameters.d.ts
131
+ type InferParameter<T extends string> = T extends `<${infer Name extends string}...>` | `[${infer Name extends string}...]` ? Record<CamelCase<Name>, string[]> : T extends `<${infer Name extends string}>` ? Record<CamelCase<Name>, string> : T extends `[${infer Name extends string}]` ? Record<CamelCase<Name>, string | undefined> : never;
132
+ type InferParameters<T extends string[]> = T extends (infer U extends string)[] ? Prettify<UnionToIntersection<InferParameter<U>>> : never;
133
+ //#endregion
134
+ //#region src/types/context.d.ts
135
+ type AddStringIndex<T> = T & Record<string, any>;
136
+ type InferFlagsWithGlobal<C extends Command, GF extends ClercFlagsDefinition> = AddStringIndex<InferFlags<NonNullable<C["flags"]> & Omit<GF, keyof NonNullable<C["flags"]>>>>;
137
+ interface BaseContext<C extends Command = Command, GF extends ClercFlagsDefinition = {}> {
138
+ resolved: boolean;
139
+ command?: C;
140
+ calledAs?: string;
141
+ parameters: InferParameters<NonNullable<C["parameters"]>>;
142
+ flags: InferFlagsWithGlobal<C, GF>;
143
+ ignored: string[];
144
+ rawParsed: ParsedResult<InferFlagsWithGlobal<C, GF>>;
145
+ missingParameters: boolean;
112
146
  }
113
- interface CommandOptions<P extends string[] = string[], A extends MaybeArray$1<string | RootType> = MaybeArray$1<string | RootType>, F extends Flags = Flags> extends CommandCustomProperties {
114
- alias?: A;
115
- parameters?: P;
116
- flags?: F;
147
+ //#endregion
148
+ //#region src/types/command.d.ts
149
+ interface CommandCustomOptions {}
150
+ interface CommandOptions<Parameters extends string[] = string[], Flags extends ClercFlagsDefinition = ClercFlagsDefinition> extends CommandCustomOptions {
151
+ alias?: MaybeArray<string>;
152
+ parameters?: Parameters;
153
+ flags?: Flags;
154
+ /**
155
+ * A callback function to conditionally stop parsing. When it returns true, parsing stops and remaining arguments are preserved in ignored.
156
+ */
157
+ ignore?: IgnoreFunction;
117
158
  }
118
- type Command<N extends string | RootType = string, O extends CommandOptions = CommandOptions> = O & {
119
- name: N;
120
- description: string;
121
- };
122
- type CommandAlias<N extends string | RootType = string, O extends CommandOptions = CommandOptions> = Command<N, O> & {
123
- __isAlias?: true;
124
- };
125
- type CommandWithHandler<N extends string | RootType = string, O extends CommandOptions = CommandOptions> = Command<N, O> & {
126
- handler?: HandlerInCommand<HandlerContext<Record<N, Command<N, O>> & Record<never, never>, N>>;
127
- };
128
- type Commands = Dict<Command> & {
129
- [Root]?: Command;
130
- };
131
- interface ParseOptions {
132
- argv?: string[];
133
- run?: boolean;
134
- }
135
- interface HandlerContext<C extends Commands = Commands, N extends keyof C = keyof C, GF extends GlobalFlagOptions = {}> {
136
- name?: LiteralUnion<N, string>;
137
- called?: string | RootType;
138
- resolved: boolean;
139
- hasRootOrAlias: boolean;
140
- hasRoot: boolean;
141
- raw: Simplify<ParseRaw<C[N], GF>>;
142
- parameters: Simplify<ParseParameters<C, N>>;
143
- unknownFlags: ParsedFlags["unknownFlags"];
144
- flags: Simplify<ParseFlag<C, N, GF> & Record<string, any>>;
145
- cli: Clerc<C, GF>;
159
+ interface Command<Name$1 extends string = string, Parameters extends string[] = string[], Flags extends ClercFlagsDefinition = ClercFlagsDefinition> extends CommandOptions<Parameters, Flags> {
160
+ name: Name$1;
161
+ description: string;
146
162
  }
147
- type Handler<C extends Commands = Commands, K extends keyof C = keyof C, GF extends GlobalFlagOptions = {}> = (ctx: HandlerContext<C, K, GF>) => void;
148
- type HandlerInCommand<C extends HandlerContext> = (ctx: {
149
- [K in keyof C]: C[K];
150
- }) => void;
151
- type FallbackType<T, U> = {} extends T ? U : T;
152
- /**
153
- * @deprecated This is a typo. Use `InterceptorContext` instead.
154
- */
155
- type InspectorContext<C extends Commands = Commands> = InterceptorContext<C>;
156
- /**
157
- * @deprecated This is a typo. Use `Interceptor` instead.
158
- */
159
- type Inspector<C extends Commands = Commands> = Interceptor<C>;
160
- /**
161
- * @deprecated This is a typo. Use `InspectorFn` instead.
162
- */
163
- type InspectorFn<C extends Commands = Commands> = InterceptorFn<C>;
164
- /**
165
- * @deprecated This is a typo. Use `InspectorObject` instead.
166
- */
167
- type InspectorObject<C extends Commands = Commands> = InterceptorObject<C>;
168
- type InterceptorContext<C extends Commands = Commands> = HandlerContext<C> & {
169
- flags: FallbackType<TypeFlag<NonNullable<C[keyof C]["flags"]>>["flags"], Dict<any>>;
163
+ type CommandWithHandler<Name$1 extends string = string, Parameters extends string[] = string[], Flags extends ClercFlagsDefinition = ClercFlagsDefinition> = Command<Name$1, Parameters, Flags> & {
164
+ handler?: CommandHandler<Command<Name$1, Parameters, Flags>>;
170
165
  };
171
- type Interceptor<C extends Commands = Commands> = InterceptorFn<C> | InterceptorObject<C>;
172
- type InterceptorFn<C extends Commands = Commands> = (ctx: InterceptorContext<C>, next: () => void) => void;
173
- interface InterceptorObject<C extends Commands = Commands> {
174
- enforce?: "pre" | "post";
175
- fn: InterceptorFn<C>;
176
- }
177
-
178
- declare const Root: unique symbol;
179
- type RootType = typeof Root;
180
- declare class Clerc<C extends Commands = {}, GF extends GlobalFlagOptions = {}> {
181
- #private;
182
- get i18n(): I18N;
183
- private constructor();
184
- get _name(): string;
185
- get _scriptName(): string;
186
- get _description(): string;
187
- get _version(): string;
188
- /**
189
- * @deprecated This is a typo. Use `_interceptor` instead.
190
- */
191
- get _inspectors(): Interceptor[];
192
- get _interceptors(): Interceptor[];
193
- get _commands(): C;
194
- get _flags(): GF;
195
- /**
196
- * Create a new cli
197
- *
198
- * @example
199
- *
200
- * ```ts
201
- * const cli = Clerc.create();
202
- * ```
203
- *
204
- * @param name
205
- * @param description
206
- * @param version
207
- * @returns
208
- */
209
- static create(name?: string, description?: string, version?: string): Clerc<{}, {}>;
210
- /**
211
- * Set the name of the cli
212
- *
213
- * @example
214
- *
215
- * ```ts
216
- * Clerc.create().name("test");
217
- * ```
218
- *
219
- * @param name
220
- * @returns
221
- */
222
- name(name: string): this;
223
- /**
224
- * Set the script name of the cli
225
- *
226
- * @example
227
- *
228
- * ```ts
229
- * Clerc.create().scriptName("test");
230
- * ```
231
- *
232
- * @param scriptName
233
- * @returns
234
- */
235
- scriptName(scriptName: string): this;
236
- /**
237
- * Set the description of the cli
238
- *
239
- * @example
240
- *
241
- * ```ts
242
- * Clerc.create().description("test cli");
243
- * ```
244
- *
245
- * @param description
246
- * @returns
247
- */
248
- description(description: string): this;
249
- /**
250
- * Set the version of the cli
251
- *
252
- * @example
253
- *
254
- * ```ts
255
- * Clerc.create().version("1.0.0");
256
- * ```
257
- *
258
- * @param version
259
- * @returns
260
- */
261
- version(version: string): this;
262
- /**
263
- * Set the Locale You must call this method once after you created the Clerc
264
- * instance.
265
- *
266
- * @example
267
- *
268
- * ```ts
269
- * Clerc.create()
270
- * .locale("en")
271
- * .command(...)
272
- * ```
273
- *
274
- * @param locale
275
- * @returns
276
- */
277
- locale(locale: string): this;
278
- /**
279
- * Set the fallback Locale You must call this method once after you created
280
- * the Clerc instance.
281
- *
282
- * @example
283
- *
284
- * ```ts
285
- * Clerc.create()
286
- * .fallbackLocale("en")
287
- * .command(...)
288
- * ```
289
- *
290
- * @param fallbackLocale
291
- * @returns
292
- */
293
- fallbackLocale(fallbackLocale: string): this;
294
- /**
295
- * Register a error handler
296
- *
297
- * @example
298
- *
299
- * ```ts
300
- * Clerc.create().errorHandler((err) => {
301
- * console.log(err);
302
- * });
303
- * ```
304
- *
305
- * @param handler
306
- * @returns
307
- */
308
- errorHandler(handler: (err: any) => void): this;
309
- /**
310
- * Register a command
311
- *
312
- * @example
313
- *
314
- * ```ts
315
- * Clerc.create().command("test", "test command", {
316
- * alias: "t",
317
- * flags: {
318
- * foo: {
319
- * alias: "f",
320
- * description: "foo flag",
321
- * },
322
- * },
323
- * });
324
- * ```
325
- *
326
- * @example
327
- *
328
- * ```ts
329
- * Clerc.create().command("", "root", {
330
- * flags: {
331
- * foo: {
332
- * alias: "f",
333
- * description: "foo flag",
334
- * },
335
- * },
336
- * });
337
- * ```
338
- *
339
- * @param name
340
- * @param description
341
- * @param options
342
- * @returns
343
- */
344
- command<C extends CommandWithHandler<any, any>[]>(c: [...C]): this;
345
- command<N extends string | RootType, O extends CommandOptions<[...P], A, F>, P extends string[] = string[], A extends MaybeArray$1<string | RootType> = MaybeArray$1<string | RootType>, F extends Flags = Flags>(c: CommandWithHandler<N, O & CommandOptions<[...P], A, F>>): this & Clerc<C & Record<N, Command<N, O>>, GF>;
346
- command<N extends string | RootType, O extends CommandOptions<[...P], A, F>, P extends string[] = string[], A extends MaybeArray$1<string | RootType> = MaybeArray$1<string | RootType>, F extends Flags = Flags>(name: N, description: string, options?: O & CommandOptions<[...P], A, F>): this & Clerc<C & Record<N, Command<N, O>>, GF>;
347
- /**
348
- * Register a global flag
349
- *
350
- * @example
351
- *
352
- * ```ts
353
- * Clerc.create().flag("help", "help", {
354
- * alias: "h",
355
- * type: Boolean,
356
- * });
357
- * ```
358
- *
359
- * @param name
360
- * @param description
361
- * @param options
362
- * @returns
363
- */
364
- flag<N extends string, O extends GlobalFlagOption>(name: N, description: string, options: O): this & Clerc<C, GF & Record<N, O>>;
365
- /**
366
- * Register a handler
367
- *
368
- * @example
369
- *
370
- * ```ts
371
- * Clerc.create()
372
- * .command("test", "test command")
373
- * .on("test", (ctx) => {
374
- * console.log(ctx);
375
- * });
376
- * ```
377
- *
378
- * @param name
379
- * @param handler
380
- * @returns
381
- */
382
- on<K extends LiteralUnion<keyof CM, string | RootType>, CM extends this["_commands"] = this["_commands"]>(name: K, handler: Handler<CM, K, this["_flags"]>): this;
383
- /**
384
- * Use a plugin
385
- *
386
- * @example
387
- *
388
- * ```ts
389
- * Clerc.create().use(plugin);
390
- * ```
391
- *
392
- * @param plugin
393
- * @returns
394
- */
395
- use<T extends Clerc, U extends Clerc>(plugin: Plugin<T, U>): this & Clerc<C & U["_commands"]> & U;
396
- /**
397
- * @deprecated This is a typo. Use `intercetor()` instead.
398
- */
399
- inspector(interceptor: Interceptor): this;
400
- /**
401
- * Register a interceptor
402
- *
403
- * @example
404
- *
405
- * ```ts
406
- * Clerc.create().interceptor((ctx, next) => {
407
- * console.log(ctx);
408
- * next();
409
- * });
410
- * ```
411
- *
412
- * @param interceptor
413
- * @returns
414
- */
415
- interceptor(interceptor: Interceptor): this;
416
- /**
417
- * Parse the command line arguments
418
- *
419
- * @example
420
- *
421
- * ```ts
422
- * Clerc.create().parse(process.argv.slice(2)); // Optional
423
- * ```
424
- *
425
- * @param args
426
- * @param optionsOrArgv
427
- * @returns
428
- */
429
- parse(optionsOrArgv?: string[] | ParseOptions): this;
430
- /**
431
- * Run matched command
432
- *
433
- * @example
434
- *
435
- * ```ts
436
- * Clerc.create().parse({ run: false }).runMatchedCommand();
437
- * ```
438
- *
439
- * @returns
440
- */
441
- runMatchedCommand(): this;
166
+ type CommandsRecord = Record<string, Command>;
167
+ type CommandsMap = Map<string, Command>;
168
+ type MakeEmitterEvents<Commands extends CommandsRecord, GlobalFlags extends ClercFlagsDefinition = ClercFlagsDefinition> = { [K in keyof Commands]: [CommandHandlerContext<Commands[K], GlobalFlags>] };
169
+ type CommandHandlerContext<C extends Command = Command, GF extends ClercFlagsDefinition = ClercFlagsDefinition> = DeepPrettify<PartialRequired<BaseContext<C, GF>, "command" | "calledAs"> & {
170
+ resolved: true;
171
+ }>;
172
+ type CommandHandler<C extends Command = Command, GF extends ClercFlagsDefinition = ClercFlagsDefinition> = (context: CommandHandlerContext<C, GF>) => void;
173
+ //#endregion
174
+ //#region src/types/interceptor.d.ts
175
+ type InterceptorContext<C extends Command = Command, GF extends ClercFlagsDefinition = {}> = DeepPrettify<BaseContext<C, GF>>;
176
+ /**
177
+ * Function to call the next interceptor in the chain.
178
+ * **MUST** be awaited.
179
+ */
180
+ type InterceptorNext = () => void | Promise<void>;
181
+ type InterceptorHandler<C extends Command = Command, GF extends ClercFlagsDefinition = {}> = (context: InterceptorContext<C, GF>, next: InterceptorNext) => void | Promise<void>;
182
+ interface InterceptorObject<C extends Command = Command, GF extends ClercFlagsDefinition = {}> {
183
+ enforce?: "pre" | "normal" | "post";
184
+ handler: InterceptorHandler<C, GF>;
442
185
  }
443
-
444
- declare class CommandExistsError extends Error {
445
- commandName: string;
446
- constructor(commandName: string, t: TranslateFn);
186
+ type Interceptor<C extends Command = Command, GF extends ClercFlagsDefinition = {}> = InterceptorHandler<C, GF> | InterceptorObject<C, GF>;
187
+ //#endregion
188
+ //#region src/types/plugin.d.ts
189
+ interface Plugin {
190
+ setup: (cli: Clerc) => void;
447
191
  }
448
- declare class NoSuchCommandError extends Error {
449
- commandName: string;
450
- constructor(commandName: string, t: TranslateFn);
192
+ //#endregion
193
+ //#region src/cli.d.ts
194
+ interface CreateOptions {
195
+ name?: string;
196
+ scriptName?: string;
197
+ description?: string;
198
+ version?: string;
451
199
  }
452
- declare class NoCommandGivenError extends Error {
453
- constructor(t: TranslateFn);
200
+ interface ParseOptions {
201
+ argv?: string[];
202
+ run?: boolean;
454
203
  }
455
- declare class CommandNameConflictError extends Error {
456
- n1: string;
457
- n2: string;
458
- constructor(n1: string, n2: string, t: TranslateFn);
204
+ declare class Clerc<Commands extends CommandsRecord = {}, GlobalFlags extends ClercFlagsDefinition = {}> {
205
+ #private;
206
+ private constructor();
207
+ get _name(): string;
208
+ get _scriptName(): string;
209
+ get _description(): string;
210
+ get _version(): string;
211
+ get _commands(): CommandsMap;
212
+ get _globalFlags(): GlobalFlags;
213
+ static create(options?: CreateOptions): Clerc;
214
+ name(name: string): this;
215
+ scriptName(scriptName: string): this;
216
+ description(description: string): this;
217
+ version(version: string): this;
218
+ use(plugin: Plugin): this;
219
+ errorHandler(handler: ErrorHandler$1): this;
220
+ command<Name$1 extends string, Parameters extends string[] = [], Flags extends ClercFlagsDefinition = {}>(command: CommandWithHandler<Name$1, [...Parameters], Flags>): Clerc<Commands & Record<string, CommandWithHandler<Name$1, Parameters, Flags>>, GlobalFlags>;
221
+ command<Name$1 extends string, Parameters extends string[] = [], Flags extends ClercFlagsDefinition = {}>(name: Name$1 extends keyof Commands ? ["COMMAND ALREADY EXISTS"] : Name$1, description: string, options?: CommandOptions<[...Parameters], Flags>): Clerc<Commands & Record<Name$1, Command<Name$1, Parameters, Flags>>, GlobalFlags>;
222
+ globalFlag<Name$1 extends string, Flag extends FlagDefinitionValue>(name: Name$1, description: string, options: Flag): Clerc<Commands, GlobalFlags & Record<Name$1, Flag>>;
223
+ interceptor(interceptor: Interceptor<Command, GlobalFlags>): this;
224
+ on<Name$1 extends LiteralUnion<keyof Commands, string>>(name: Name$1, handler: CommandHandler<Commands[Name$1], GlobalFlags>): this;
225
+ run(): void;
226
+ parse(argvOrOptions?: string[] | ParseOptions): this;
459
227
  }
460
- declare class ScriptNameNotSetError extends Error {
461
- constructor(t: TranslateFn);
228
+ //#endregion
229
+ //#region src/commands.d.ts
230
+ declare function resolveCommand(commandsMap: CommandsMap, parameters: string[]): [Command, string] | [undefined, undefined];
231
+ //#endregion
232
+ //#region src/errors.d.ts
233
+ declare class NoSuchCommandError extends Error {
234
+ commandName: string;
235
+ constructor(commandName: string, text?: string);
462
236
  }
463
- declare class DescriptionNotSetError extends Error {
464
- constructor(t: TranslateFn);
237
+ declare class NoCommandSpecifiedError extends Error {
238
+ constructor(text?: string);
465
239
  }
466
- declare class VersionNotSetError extends Error {
467
- constructor(t: TranslateFn);
240
+ declare class InvalidCommandError extends Error {
241
+ constructor(message: string);
468
242
  }
469
- declare class InvalidCommandNameError extends Error {
470
- commandName: string;
471
- constructor(commandName: string, t: TranslateFn);
243
+ declare class MissingRequiredMetadataError extends Error {
244
+ constructor(metadataName: string);
472
245
  }
473
- declare class LocaleNotCalledFirstError extends Error {
474
- constructor(t: TranslateFn);
246
+ declare class InvalidParametersError extends Error {
247
+ constructor(message: string);
475
248
  }
476
-
477
- type MaybeArray<T> = T | T[];
478
-
479
- declare const definePlugin: <T extends Clerc<{}, {}>, U extends Clerc<{}, {}>>(p: Plugin<T, U>) => Plugin<T, U>;
480
- declare const defineHandler: <C extends Clerc<{}, {}>, K extends keyof C["_commands"]>(_cli: C, _key: K, handler: Handler<C["_commands"], K>) => Handler<C["_commands"], K>;
481
- declare const defineInterceptor: <C extends Clerc<{}, {}>>(_cli: C, interceptor: Interceptor<C["_commands"]>) => Interceptor<C["_commands"]>;
482
- /**
483
- * @deprecated This is a typo. Use `defineInterceptor` instead.
484
- */
485
- declare const defineInspector: <C extends Clerc<{}, {}>>(_cli: C, interceptor: Interceptor<C["_commands"]>) => Interceptor<C["_commands"]>;
486
- declare const defineCommand: <N extends string | typeof Root, O extends CommandOptions<[...P], MaybeArray<string | typeof Root>, Flags>, P extends string[]>(command: Command<N, O & CommandOptions<[...P], MaybeArray<string | typeof Root>, Flags>>, handler?: HandlerInCommand<HandlerContext<Record<N, Command<N, O>> & Record<never, never>, N, {}>> | undefined) => CommandWithHandler<N, O & CommandOptions<[...P], MaybeArray<string | typeof Root>, Flags>>;
487
-
488
- declare function resolveFlattenCommands(commands: Commands, t: TranslateFn): Map<string[] | typeof Root, CommandAlias>;
489
- declare function resolveCommand(commands: Commands, argv: string[], t: TranslateFn): [Command<string | RootType> | undefined, string[] | RootType | undefined];
490
- declare const resolveArgv: () => string[];
491
- declare function compose(interceptors: Interceptor[]): (ctx: InterceptorContext) => void;
492
- declare const isValidName: (name: CommandType) => boolean;
493
- declare const withBrackets: (s: string, isOptional?: boolean) => string;
494
- declare const formatCommandName: (name: string | string[] | RootType) => string;
495
- declare const detectLocale: () => string;
496
- declare const stripFlags: (argv: string[]) => string[];
497
-
498
- export { Clerc, Command, CommandAlias, CommandCustomProperties, CommandExistsError, CommandNameConflictError, CommandOptions, CommandType, CommandWithHandler, Commands, DescriptionNotSetError, FallbackType, Flag, FlagOptions, Flags, GlobalFlagOption, GlobalFlagOptions, Handler, HandlerContext, HandlerInCommand, I18N, Inspector, InspectorContext, InspectorFn, InspectorObject, Interceptor, InterceptorContext, InterceptorFn, InterceptorObject, InvalidCommandNameError, LocaleNotCalledFirstError, Locales, MakeEventMap, NoCommandGivenError, NoSuchCommandError, ParseOptions, Plugin, Root, RootType, ScriptNameNotSetError, TranslateFn, VersionNotSetError, compose, defineCommand, defineHandler, defineInspector, defineInterceptor, definePlugin, detectLocale, formatCommandName, isValidName, resolveArgv, resolveCommand, resolveFlattenCommands, stripFlags, withBrackets };
249
+ //#endregion
250
+ //#region src/helpers.d.ts
251
+ declare const defineCommand: <Name$1 extends string, Parameters extends string[] = [], Flags extends ClercFlagsDefinition = {}>(command: CommandWithHandler<Name$1, [...Parameters], Flags>) => CommandWithHandler<Name$1, [...Parameters], Flags>;
252
+ //#endregion
253
+ //#region src/ignore.d.ts
254
+ declare function createStopAtFirstParameter(): IgnoreFunction;
255
+ //#endregion
256
+ //#region src/plugin.d.ts
257
+ declare const definePlugin: (plugin: Plugin) => Plugin;
258
+ //#endregion
259
+ export { BaseContext, Clerc, ClercFlagOptions, ClercFlagsDefinition, Command, CommandCustomOptions, CommandHandler, CommandHandlerContext, CommandOptions, CommandWithHandler, CommandsMap, CommandsRecord, DOUBLE_DASH, ErrorHandler, InferParameters, Interceptor, InterceptorContext, InterceptorHandler, InterceptorNext, InterceptorObject, InvalidCommandError, InvalidParametersError, KNOWN_FLAG, MakeEmitterEvents, MissingRequiredMetadataError, NoCommandSpecifiedError, NoSuchCommandError, PARAMETER, Plugin, UNKNOWN_FLAG, createStopAtFirstParameter, defineCommand, definePlugin, resolveCommand };