@clerc/core 0.34.0 → 0.35.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.d.ts CHANGED
@@ -220,430 +220,426 @@ type LiteralUnion<
220
220
  BaseType extends Primitive,
221
221
  > = LiteralType | (BaseType & Record<never, never>);
222
222
 
223
- type Equals<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
224
- type Dict<T> = Record<string, T>;
225
- type MaybeArray$1<T> = T | T[];
226
- type AlphabetLowercase = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z";
227
- type Numeric = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
228
- type AlphaNumeric = AlphabetLowercase | Uppercase<AlphabetLowercase> | Numeric;
223
+ type Equals<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
224
+ type Dict<T> = Record<string, T>;
225
+ type MaybeArray$1<T> = T | T[];
226
+ type AlphabetLowercase = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z";
227
+ type Numeric = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
228
+ type AlphaNumeric = AlphabetLowercase | Uppercase<AlphabetLowercase> | Numeric;
229
229
  type CamelCase<Word extends string> = (Word extends `${infer FirstCharacter}${infer Rest}` ? (FirstCharacter extends AlphaNumeric ? `${FirstCharacter}${CamelCase<Rest>}` : Capitalize<CamelCase<Rest>>) : Word);
230
230
 
231
- declare const DOUBLE_DASH = "--";
232
- type TypeFunction<ReturnType = any> = (value: any) => ReturnType;
233
- type TypeFunctionArray<ReturnType> = readonly [TypeFunction<ReturnType>];
234
- type FlagType<ReturnType = any> = TypeFunction<ReturnType> | TypeFunctionArray<ReturnType>;
235
- type FlagSchemaBase<TF> = {
236
- /**
237
- Type of the flag as a function that parses the argv string and returns the parsed value.
238
-
239
- @example
240
- ```
241
- type: String
242
- ```
243
-
244
- @example Wrap in an array to accept multiple values.
245
- ```
246
- type: [Boolean]
247
- ```
248
-
249
- @example Custom function type that uses moment.js to parse string as date.
250
- ```
251
- type: function CustomDate(value: string) {
252
- return moment(value).toDate();
253
- }
254
- ```
255
- */
256
- type: TF;
257
- /**
258
- A single-character alias for the flag.
259
-
260
- @example
261
- ```
262
- alias: 's'
263
- ```
264
- */
265
- alias?: string;
266
- } & Record<PropertyKey, unknown>;
267
- type FlagSchemaDefault<TF, DefaultType = any> = FlagSchemaBase<TF> & {
268
- /**
269
- Default value of the flag. Also accepts a function that returns the default value.
270
- [Default: undefined]
271
-
272
- @example
273
- ```
274
- default: 'hello'
275
- ```
276
-
277
- @example
278
- ```
279
- default: () => [1, 2, 3]
280
- ```
281
- */
282
- default: DefaultType | (() => DefaultType);
283
- };
284
- type FlagSchema<TF = FlagType> = (FlagSchemaBase<TF> | FlagSchemaDefault<TF>);
285
- type FlagTypeOrSchema<ExtraOptions = Record<string, unknown>> = FlagType | (FlagSchema & ExtraOptions);
286
- type Flags$1<ExtraOptions = Record<string, unknown>> = Record<string, FlagTypeOrSchema<ExtraOptions>>;
287
- 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));
288
- interface ParsedFlags<Schemas = Record<string, unknown>> {
289
- flags: Schemas;
290
- unknownFlags: Record<string, (string | boolean)[]>;
291
- _: string[] & {
292
- [DOUBLE_DASH]: string[];
293
- };
294
- }
295
- type TypeFlag<Schemas extends Flags$1> = ParsedFlags<{
296
- [flag in keyof Schemas]: InferFlagType<Schemas[flag]>;
231
+ declare const DOUBLE_DASH = "--";
232
+ type TypeFunction<ReturnType = any> = (value: any) => ReturnType;
233
+ type TypeFunctionArray<ReturnType> = readonly [TypeFunction<ReturnType>];
234
+ type FlagType<ReturnType = any> = TypeFunction<ReturnType> | TypeFunctionArray<ReturnType>;
235
+ type FlagSchemaBase<TF> = {
236
+ /**
237
+ Type of the flag as a function that parses the argv string and returns the parsed value.
238
+
239
+ @example
240
+ ```
241
+ type: String
242
+ ```
243
+
244
+ @example Wrap in an array to accept multiple values.
245
+ ```
246
+ type: [Boolean]
247
+ ```
248
+
249
+ @example Custom function type that uses moment.js to parse string as date.
250
+ ```
251
+ type: function CustomDate(value: string) {
252
+ return moment(value).toDate();
253
+ }
254
+ ```
255
+ */
256
+ type: TF;
257
+ /**
258
+ A single-character alias for the flag.
259
+
260
+ @example
261
+ ```
262
+ alias: 's'
263
+ ```
264
+ */
265
+ alias?: string;
266
+ } & Record<PropertyKey, unknown>;
267
+ type FlagSchemaDefault<TF, DefaultType = any> = FlagSchemaBase<TF> & {
268
+ /**
269
+ Default value of the flag. Also accepts a function that returns the default value.
270
+ [Default: undefined]
271
+
272
+ @example
273
+ ```
274
+ default: 'hello'
275
+ ```
276
+
277
+ @example
278
+ ```
279
+ default: () => [1, 2, 3]
280
+ ```
281
+ */
282
+ default: DefaultType | (() => DefaultType);
283
+ };
284
+ type FlagSchema<TF = FlagType> = (FlagSchemaBase<TF> | FlagSchemaDefault<TF>);
285
+ type FlagTypeOrSchema<ExtraOptions = Record<string, unknown>> = FlagType | (FlagSchema & ExtraOptions);
286
+ type Flags$1<ExtraOptions = Record<string, unknown>> = Record<string, FlagTypeOrSchema<ExtraOptions>>;
287
+ 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));
288
+ interface ParsedFlags<Schemas = Record<string, unknown>> {
289
+ flags: Schemas;
290
+ unknownFlags: Record<string, (string | boolean)[]>;
291
+ _: string[] & {
292
+ [DOUBLE_DASH]: string[];
293
+ };
294
+ }
295
+ type TypeFlag<Schemas extends Flags$1> = ParsedFlags<{
296
+ [flag in keyof Schemas]: InferFlagType<Schemas[flag]>;
297
297
  }>;
298
298
 
299
- type StripBrackets<Parameter extends string> = (Parameter extends `<${infer ParameterName}>` | `[${infer ParameterName}]` ? (ParameterName extends `${infer SpreadName}...` ? SpreadName : ParameterName) : never);
300
- type ParameterType<Parameter extends string> = (Parameter extends `<${infer _ParameterName}...>` | `[${infer _ParameterName}...]` ? string[] : Parameter extends `<${infer _ParameterName}>` ? string : Parameter extends `[${infer _ParameterName}]` ? string | undefined : never);
301
- type NonNullableParameters<T extends string[] | undefined> = T extends undefined ? [] : NonNullable<T>;
302
- type TransformParameters<C extends Command> = {
303
- [Parameter in NonNullableParameters<C["parameters"]>[number] as CamelCase<StripBrackets<Parameter>>]: ParameterType<Parameter>;
304
- };
305
- type MakeEventMap<T extends Commands> = {
306
- [K in keyof T]: [InspectorContext];
307
- };
308
- type FallbackFlags<F extends Flags | undefined> = Equals<NonNullableFlag<F>["flags"], {}> extends true ? Dict<any> : NonNullableFlag<F>["flags"];
309
- type NonNullableFlag<F extends Flags | undefined> = TypeFlag<NonNullable<F>>;
310
- type ParseFlag<C extends Commands, N extends keyof C, GF extends FlagsWithoutDescription = {}> = N extends keyof C ? OmitIndexSignature<NonNullableFlag<C[N]["flags"] & GF>["flags"]> : FallbackFlags<C[N]["flags"] & GF>["flags"];
311
- type ParseRaw<C extends Command, GF extends FlagsWithoutDescription = {}> = NonNullableFlag<C["flags"] & GF> & {
312
- flags: FallbackFlags<C["flags"] & GF>;
313
- parameters: string[];
314
- mergedFlags: FallbackFlags<C["flags"] & GF> & NonNullableFlag<C["flags"] & GF>["unknownFlags"];
315
- };
299
+ type StripBrackets<Parameter extends string> = (Parameter extends `<${infer ParameterName}>` | `[${infer ParameterName}]` ? (ParameterName extends `${infer SpreadName}...` ? SpreadName : ParameterName) : never);
300
+ type ParameterType<Parameter extends string> = (Parameter extends `<${infer _ParameterName}...>` | `[${infer _ParameterName}...]` ? string[] : Parameter extends `<${infer _ParameterName}>` ? string : Parameter extends `[${infer _ParameterName}]` ? string | undefined : never);
301
+ type NonNullableParameters<T extends string[] | undefined> = T extends undefined ? [] : NonNullable<T>;
302
+ type TransformParameters<C extends Command> = {
303
+ [Parameter in NonNullableParameters<C["parameters"]>[number] as CamelCase<StripBrackets<Parameter>>]: ParameterType<Parameter>;
304
+ };
305
+ type MakeEventMap<T extends Commands> = {
306
+ [K in keyof T]: [InspectorContext];
307
+ };
308
+ type FallbackFlags<F extends Flags | undefined> = Equals<NonNullableFlag<F>["flags"], {}> extends true ? Dict<any> : NonNullableFlag<F>["flags"];
309
+ type NonNullableFlag<F extends Flags | undefined> = TypeFlag<NonNullable<F>>;
310
+ 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"];
311
+ type ParseRaw<C extends Command, GF extends GlobalFlagOptions = {}> = NonNullableFlag<C["flags"] & GF> & {
312
+ flags: FallbackFlags<C["flags"] & GF>;
313
+ parameters: string[];
314
+ mergedFlags: FallbackFlags<C["flags"] & GF> & NonNullableFlag<C["flags"] & GF>["unknownFlags"];
315
+ };
316
316
  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]>;
317
317
 
318
- interface Plugin<T extends Clerc = Clerc, U extends Clerc = Clerc> {
319
- setup: (cli: T) => U;
318
+ interface Plugin<T extends Clerc = Clerc, U extends Clerc = Clerc> {
319
+ setup: (cli: T) => U;
320
320
  }
321
321
 
322
- type Locales = Dict<Dict<string>>;
323
- type TranslateFn = (name: string, ...args: string[]) => string | undefined;
324
- interface I18N {
325
- add: (locales: Locales) => void;
326
- t: TranslateFn;
322
+ type Locales = Dict<Dict<string>>;
323
+ type TranslateFn = (name: string, ...args: string[]) => string | undefined;
324
+ interface I18N {
325
+ add: (locales: Locales) => void;
326
+ t: TranslateFn;
327
327
  }
328
328
 
329
- type CommandType = RootType | string;
330
- type FlagOptions = FlagSchema & {
331
- description: string;
332
- };
333
- type Flag = FlagOptions & {
334
- name: string;
335
- };
336
- type FlagWithoutDescription = Omit<Flag, "description">;
337
- type Flags = Dict<FlagOptions>;
338
- type FlagsWithoutDescription = Dict<FlagWithoutDescription>;
339
- declare interface CommandCustomProperties {
340
- }
341
- interface CommandOptions<P extends string[] = string[], A extends MaybeArray$1<string | RootType> = MaybeArray$1<string | RootType>, F extends Flags = Flags> extends CommandCustomProperties {
342
- alias?: A;
343
- parameters?: P;
344
- flags?: F;
345
- examples?: [string, string][];
346
- notes?: string[];
347
- }
348
- type Command<N extends string | RootType = string, O extends CommandOptions = CommandOptions> = O & {
349
- name: N;
350
- description: string;
351
- };
352
- type CommandAlias<N extends string | RootType = string, O extends CommandOptions = CommandOptions> = Command<N, O> & {
353
- __isAlias?: true;
354
- };
355
- type CommandWithHandler<N extends string | RootType = string, O extends CommandOptions = CommandOptions> = Command<N, O> & {
356
- handler?: HandlerInCommand<HandlerContext<Record<N, Command<N, O>> & Record<never, never>, N>>;
357
- };
358
- type Commands = Dict<Command> & {
359
- [Root]?: Command;
360
- };
361
- interface ParseOptions {
362
- argv?: string[];
363
- run?: boolean;
364
- }
365
- interface HandlerContext<C extends Commands = Commands, N extends keyof C = keyof C, GF extends FlagsWithoutDescription = {}> {
366
- name?: LiteralUnion<N, string>;
367
- called?: string | RootType;
368
- resolved: boolean;
369
- hasRootOrAlias: boolean;
370
- hasRoot: boolean;
371
- raw: Simplify<ParseRaw<C[N], GF>>;
372
- parameters: Simplify<ParseParameters<C, N>>;
373
- unknownFlags: ParsedFlags["unknownFlags"];
374
- flags: Simplify<ParseFlag<C, N, GF> & Record<string, any>>;
375
- cli: Clerc<C, GF>;
376
- }
377
- type Handler<C extends Commands = Commands, K extends keyof C = keyof C, GF extends FlagsWithoutDescription = {}> = (ctx: HandlerContext<C, K, GF>) => void;
378
- type HandlerInCommand<C extends HandlerContext> = (ctx: {
379
- [K in keyof C]: C[K];
380
- }) => void;
381
- type FallbackType<T, U> = {} extends T ? U : T;
382
- type InspectorContext<C extends Commands = Commands> = HandlerContext<C> & {
383
- flags: FallbackType<TypeFlag<NonNullable<C[keyof C]["flags"]>>["flags"], Dict<any>>;
384
- };
385
- type Inspector<C extends Commands = Commands> = InspectorFn<C> | InspectorObject<C>;
386
- type InspectorFn<C extends Commands = Commands> = (ctx: InspectorContext<C>, next: () => void) => (() => void) | void;
387
- interface InspectorObject<C extends Commands = Commands> {
388
- enforce?: "pre" | "post";
389
- fn: InspectorFn<C>;
329
+ type CommandType = RootType | string;
330
+ type FlagOptions = FlagSchema & {
331
+ description: string;
332
+ };
333
+ type Flag = FlagOptions & {
334
+ name: string;
335
+ };
336
+ type GlobalFlagOption = FlagSchema;
337
+ type Flags = Dict<FlagOptions>;
338
+ type GlobalFlagOptions = Dict<GlobalFlagOption>;
339
+ declare interface CommandCustomProperties {
340
+ }
341
+ interface CommandOptions<P extends string[] = string[], A extends MaybeArray$1<string | RootType> = MaybeArray$1<string | RootType>, F extends Flags = Flags> extends CommandCustomProperties {
342
+ alias?: A;
343
+ parameters?: P;
344
+ flags?: F;
345
+ }
346
+ type Command<N extends string | RootType = string, O extends CommandOptions = CommandOptions> = O & {
347
+ name: N;
348
+ description: string;
349
+ };
350
+ type CommandAlias<N extends string | RootType = string, O extends CommandOptions = CommandOptions> = Command<N, O> & {
351
+ __isAlias?: true;
352
+ };
353
+ type CommandWithHandler<N extends string | RootType = string, O extends CommandOptions = CommandOptions> = Command<N, O> & {
354
+ handler?: HandlerInCommand<HandlerContext<Record<N, Command<N, O>> & Record<never, never>, N>>;
355
+ };
356
+ type Commands = Dict<Command> & {
357
+ [Root]?: Command;
358
+ };
359
+ interface ParseOptions {
360
+ argv?: string[];
361
+ run?: boolean;
362
+ }
363
+ interface HandlerContext<C extends Commands = Commands, N extends keyof C = keyof C, GF extends GlobalFlagOptions = {}> {
364
+ name?: LiteralUnion<N, string>;
365
+ called?: string | RootType;
366
+ resolved: boolean;
367
+ hasRootOrAlias: boolean;
368
+ hasRoot: boolean;
369
+ raw: Simplify<ParseRaw<C[N], GF>>;
370
+ parameters: Simplify<ParseParameters<C, N>>;
371
+ unknownFlags: ParsedFlags["unknownFlags"];
372
+ flags: Simplify<ParseFlag<C, N, GF> & Record<string, any>>;
373
+ cli: Clerc<C, GF>;
374
+ }
375
+ type Handler<C extends Commands = Commands, K extends keyof C = keyof C, GF extends GlobalFlagOptions = {}> = (ctx: HandlerContext<C, K, GF>) => void;
376
+ type HandlerInCommand<C extends HandlerContext> = (ctx: {
377
+ [K in keyof C]: C[K];
378
+ }) => void;
379
+ type FallbackType<T, U> = {} extends T ? U : T;
380
+ type InspectorContext<C extends Commands = Commands> = HandlerContext<C> & {
381
+ flags: FallbackType<TypeFlag<NonNullable<C[keyof C]["flags"]>>["flags"], Dict<any>>;
382
+ };
383
+ type Inspector<C extends Commands = Commands> = InspectorFn<C> | InspectorObject<C>;
384
+ type InspectorFn<C extends Commands = Commands> = (ctx: InspectorContext<C>, next: () => void) => (() => void) | void;
385
+ interface InspectorObject<C extends Commands = Commands> {
386
+ enforce?: "pre" | "post";
387
+ fn: InspectorFn<C>;
390
388
  }
391
389
 
392
- declare const Root: unique symbol;
393
- type RootType = typeof Root;
394
- declare class Clerc<C extends Commands = {}, GF extends FlagsWithoutDescription = {}> {
395
- #private;
396
- i18n: I18N;
397
- private constructor();
398
- get _name(): string;
399
- get _description(): string;
400
- get _version(): string;
401
- get _inspectors(): Inspector<Commands>[];
402
- get _commands(): C;
403
- get _flags(): GF;
404
- /**
405
- * Create a new cli
406
- * @returns
407
- * @example
408
- * ```ts
409
- * const cli = Clerc.create()
410
- * ```
411
- */
412
- static create(name?: string, description?: string, version?: string): Clerc<{}, {}>;
413
- /**
414
- * Set the name of the cli
415
- * @param name
416
- * @returns
417
- * @example
418
- * ```ts
419
- * Clerc.create()
420
- * .name("test")
421
- * ```
422
- */
423
- name(name: string): this;
424
- /**
425
- * Set the description of the cli
426
- * @param description
427
- * @returns
428
- * @example
429
- * ```ts
430
- * Clerc.create()
431
- * .description("test cli")
432
- * ```
433
- */
434
- description(description: string): this;
435
- /**
436
- * Set the version of the cli
437
- * @param version
438
- * @returns
439
- * @example
440
- * ```ts
441
- * Clerc.create()
442
- * .version("1.0.0")
443
- * ```
444
- */
445
- version(version: string): this;
446
- /**
447
- * Set the Locale
448
- * You must call this method once after you created the Clerc instance.
449
- * @param locale
450
- * @returns
451
- * @example
452
- * ```ts
453
- * Clerc.create()
454
- * .locale("en")
455
- * .command(...)
456
- * ```
457
- */
458
- locale(locale: string): this;
459
- /**
460
- * Set the fallback Locale
461
- * You must call this method once after you created the Clerc instance.
462
- * @param fallbackLocale
463
- * @returns
464
- * @example
465
- * ```ts
466
- * Clerc.create()
467
- * .fallbackLocale("en")
468
- * .command(...)
469
- * ```
470
- */
471
- fallbackLocale(fallbackLocale: string): this;
472
- /**
473
- * Register a error handler
474
- * @param handler
475
- * @returns
476
- * @example
477
- * ```ts
478
- * Clerc.create()
479
- * .errorHandler((err) => { console.log(err); })
480
- * ```
481
- */
482
- errorHandler(handler: (err: any) => void): this;
483
- /**
484
- * Register a command
485
- * @param name
486
- * @param description
487
- * @param options
488
- * @returns
489
- * @example
490
- * ```ts
491
- * Clerc.create()
492
- * .command("test", "test command", {
493
- * alias: "t",
494
- * flags: {
495
- * foo: {
496
- * alias: "f",
497
- * description: "foo flag",
498
- * }
499
- * }
500
- * })
501
- * ```
502
- * @example
503
- * ```ts
504
- * Clerc.create()
505
- * .command("", "root", {
506
- * flags: {
507
- * foo: {
508
- * alias: "f",
509
- * description: "foo flag",
510
- * }
511
- * }
512
- * })
513
- * ```
514
- */
515
- 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>;
516
- 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>;
517
- /**
518
- * Register a global flag
519
- * @param name
520
- * @param options
521
- * @returns
522
- * @example
523
- * ```ts
524
- * Clerc.create()
525
- * .flag("help", {
526
- * alias: "h",
527
- * description: "help",
528
- * })
529
- * ```
530
- */
531
- flag<N extends string, O extends FlagWithoutDescription>(name: N, description: string, options: O): this & Clerc<C, GF & Record<N, O>>;
532
- /**
533
- * Register a handler
534
- * @param name
535
- * @param handler
536
- * @returns
537
- * @example
538
- * ```ts
539
- * Clerc.create()
540
- * .command("test", "test command")
541
- * .on("test", (ctx) => {
542
- * console.log(ctx);
543
- * })
544
- * ```
545
- */
546
- on<K extends LiteralUnion<keyof CM, string | RootType>, CM extends this["_commands"] = this["_commands"]>(name: K, handler: Handler<CM, K, this["_flags"]>): this;
547
- /**
548
- * Use a plugin
549
- * @param plugin
550
- * @returns
551
- * @example
552
- * ```ts
553
- * Clerc.create()
554
- * .use(plugin)
555
- * ```
556
- */
557
- use<T extends Clerc, U extends Clerc>(plugin: Plugin<T, U>): this & Clerc<C & U["_commands"]> & U;
558
- /**
559
- * Register a inspector
560
- * @param inspector
561
- * @returns
562
- * @example
563
- * ```ts
564
- * Clerc.create()
565
- * .inspector((ctx, next) => {
566
- * console.log(ctx);
567
- * next();
568
- * })
569
- * ```
570
- */
571
- inspector(inspector: Inspector): this;
572
- /**
573
- * Parse the command line arguments
574
- * @param args
575
- * @returns
576
- * @example
577
- * ```ts
578
- * Clerc.create()
579
- * .parse(process.argv.slice(2)) // Optional
580
- * ```
581
- */
582
- parse(optionsOrArgv?: string[] | ParseOptions): this;
583
- /**
584
- * Run matched command
585
- * @returns
586
- * @example
587
- * ```ts
588
- * Clerc.create()
589
- * .parse({ run: false })
590
- * .runMatchedCommand()
591
- * ```
592
- */
593
- runMatchedCommand(): this;
390
+ declare const Root: unique symbol;
391
+ type RootType = typeof Root;
392
+ declare class Clerc<C extends Commands = {}, GF extends GlobalFlagOptions = {}> {
393
+ #private;
394
+ i18n: I18N;
395
+ private constructor();
396
+ get _name(): string;
397
+ get _description(): string;
398
+ get _version(): string;
399
+ get _inspectors(): Inspector[];
400
+ get _commands(): C;
401
+ get _flags(): GF;
402
+ /**
403
+ * Create a new cli
404
+ * @returns
405
+ * @example
406
+ * ```ts
407
+ * const cli = Clerc.create()
408
+ * ```
409
+ */
410
+ static create(name?: string, description?: string, version?: string): Clerc<{}, {}>;
411
+ /**
412
+ * Set the name of the cli
413
+ * @param name
414
+ * @returns
415
+ * @example
416
+ * ```ts
417
+ * Clerc.create()
418
+ * .name("test")
419
+ * ```
420
+ */
421
+ name(name: string): this;
422
+ /**
423
+ * Set the description of the cli
424
+ * @param description
425
+ * @returns
426
+ * @example
427
+ * ```ts
428
+ * Clerc.create()
429
+ * .description("test cli")
430
+ * ```
431
+ */
432
+ description(description: string): this;
433
+ /**
434
+ * Set the version of the cli
435
+ * @param version
436
+ * @returns
437
+ * @example
438
+ * ```ts
439
+ * Clerc.create()
440
+ * .version("1.0.0")
441
+ * ```
442
+ */
443
+ version(version: string): this;
444
+ /**
445
+ * Set the Locale
446
+ * You must call this method once after you created the Clerc instance.
447
+ * @param locale
448
+ * @returns
449
+ * @example
450
+ * ```ts
451
+ * Clerc.create()
452
+ * .locale("en")
453
+ * .command(...)
454
+ * ```
455
+ */
456
+ locale(locale: string): this;
457
+ /**
458
+ * Set the fallback Locale
459
+ * You must call this method once after you created the Clerc instance.
460
+ * @param fallbackLocale
461
+ * @returns
462
+ * @example
463
+ * ```ts
464
+ * Clerc.create()
465
+ * .fallbackLocale("en")
466
+ * .command(...)
467
+ * ```
468
+ */
469
+ fallbackLocale(fallbackLocale: string): this;
470
+ /**
471
+ * Register a error handler
472
+ * @param handler
473
+ * @returns
474
+ * @example
475
+ * ```ts
476
+ * Clerc.create()
477
+ * .errorHandler((err) => { console.log(err); })
478
+ * ```
479
+ */
480
+ errorHandler(handler: (err: any) => void): this;
481
+ /**
482
+ * Register a command
483
+ * @param name
484
+ * @param description
485
+ * @param options
486
+ * @returns
487
+ * @example
488
+ * ```ts
489
+ * Clerc.create()
490
+ * .command("test", "test command", {
491
+ * alias: "t",
492
+ * flags: {
493
+ * foo: {
494
+ * alias: "f",
495
+ * description: "foo flag",
496
+ * }
497
+ * }
498
+ * })
499
+ * ```
500
+ * @example
501
+ * ```ts
502
+ * Clerc.create()
503
+ * .command("", "root", {
504
+ * flags: {
505
+ * foo: {
506
+ * alias: "f",
507
+ * description: "foo flag",
508
+ * }
509
+ * }
510
+ * })
511
+ * ```
512
+ */
513
+ 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>;
514
+ 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>;
515
+ /**
516
+ * Register a global flag
517
+ * @param name
518
+ * @param description
519
+ * @param options
520
+ * @returns
521
+ * @example
522
+ * ```ts
523
+ * Clerc.create()
524
+ * .flag("help", "help", {
525
+ * alias: "h",
526
+ * type: Boolean,
527
+ * })
528
+ * ```
529
+ */
530
+ flag<N extends string, O extends GlobalFlagOption>(name: N, description: string, options: O): this & Clerc<C, GF & Record<N, O>>;
531
+ /**
532
+ * Register a handler
533
+ * @param name
534
+ * @param handler
535
+ * @returns
536
+ * @example
537
+ * ```ts
538
+ * Clerc.create()
539
+ * .command("test", "test command")
540
+ * .on("test", (ctx) => {
541
+ * console.log(ctx);
542
+ * })
543
+ * ```
544
+ */
545
+ on<K extends LiteralUnion<keyof CM, string | RootType>, CM extends this["_commands"] = this["_commands"]>(name: K, handler: Handler<CM, K, this["_flags"]>): this;
546
+ /**
547
+ * Use a plugin
548
+ * @param plugin
549
+ * @returns
550
+ * @example
551
+ * ```ts
552
+ * Clerc.create()
553
+ * .use(plugin)
554
+ * ```
555
+ */
556
+ use<T extends Clerc, U extends Clerc>(plugin: Plugin<T, U>): this & Clerc<C & U["_commands"]> & U;
557
+ /**
558
+ * Register a inspector
559
+ * @param inspector
560
+ * @returns
561
+ * @example
562
+ * ```ts
563
+ * Clerc.create()
564
+ * .inspector((ctx, next) => {
565
+ * console.log(ctx);
566
+ * next();
567
+ * })
568
+ * ```
569
+ */
570
+ inspector(inspector: Inspector): this;
571
+ /**
572
+ * Parse the command line arguments
573
+ * @param args
574
+ * @returns
575
+ * @example
576
+ * ```ts
577
+ * Clerc.create()
578
+ * .parse(process.argv.slice(2)) // Optional
579
+ * ```
580
+ */
581
+ parse(optionsOrArgv?: string[] | ParseOptions): this;
582
+ /**
583
+ * Run matched command
584
+ * @returns
585
+ * @example
586
+ * ```ts
587
+ * Clerc.create()
588
+ * .parse({ run: false })
589
+ * .runMatchedCommand()
590
+ * ```
591
+ */
592
+ runMatchedCommand(): this;
594
593
  }
595
594
 
596
595
  type MaybeArray<T> = T | T[];
597
596
 
598
- declare const definePlugin: <T extends Clerc<{}, {}>, U extends Clerc<{}, {}>>(p: Plugin<T, U>) => Plugin<T, U>;
599
- declare const defineHandler: <C extends Clerc<{}, {}>, K extends keyof C["_commands"]>(_cli: C, _key: K, handler: Handler<C["_commands"], K, {}>) => Handler<C["_commands"], K, {}>;
600
- declare const defineInspector: <C extends Clerc<{}, {}>>(_cli: C, inspector: Inspector<C["_commands"]>) => Inspector<C["_commands"]>;
597
+ declare const definePlugin: <T extends Clerc<{}, {}>, U extends Clerc<{}, {}>>(p: Plugin<T, U>) => Plugin<T, U>;
598
+ declare const defineHandler: <C extends Clerc<{}, {}>, K extends keyof C["_commands"]>(_cli: C, _key: K, handler: Handler<C["_commands"], K>) => Handler<C["_commands"], K>;
599
+ declare const defineInspector: <C extends Clerc<{}, {}>>(_cli: C, inspector: Inspector<C["_commands"]>) => Inspector<C["_commands"]>;
601
600
  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>>;
602
601
 
603
- declare class CommandExistsError extends Error {
604
- commandName: string;
605
- constructor(commandName: string, t: TranslateFn);
606
- }
607
- declare class NoSuchCommandError extends Error {
608
- commandName: string;
609
- constructor(commandName: string, t: TranslateFn);
610
- }
611
- declare class NoCommandGivenError extends Error {
612
- constructor(t: TranslateFn);
613
- }
614
- declare class CommandNameConflictError extends Error {
615
- n1: string;
616
- n2: string;
617
- constructor(n1: string, n2: string, t: TranslateFn);
618
- }
619
- declare class NameNotSetError extends Error {
620
- constructor(t: TranslateFn);
621
- }
622
- declare class DescriptionNotSetError extends Error {
623
- constructor(t: TranslateFn);
624
- }
625
- declare class VersionNotSetError extends Error {
626
- constructor(t: TranslateFn);
627
- }
628
- declare class InvalidCommandNameError extends Error {
629
- commandName: string;
630
- constructor(commandName: string, t: TranslateFn);
631
- }
632
- declare class LocaleNotCalledFirstError extends Error {
633
- constructor(t: TranslateFn);
602
+ declare class CommandExistsError extends Error {
603
+ commandName: string;
604
+ constructor(commandName: string, t: TranslateFn);
605
+ }
606
+ declare class NoSuchCommandError extends Error {
607
+ commandName: string;
608
+ constructor(commandName: string, t: TranslateFn);
609
+ }
610
+ declare class NoCommandGivenError extends Error {
611
+ constructor(t: TranslateFn);
612
+ }
613
+ declare class CommandNameConflictError extends Error {
614
+ n1: string;
615
+ n2: string;
616
+ constructor(n1: string, n2: string, t: TranslateFn);
617
+ }
618
+ declare class NameNotSetError extends Error {
619
+ constructor(t: TranslateFn);
620
+ }
621
+ declare class DescriptionNotSetError extends Error {
622
+ constructor(t: TranslateFn);
623
+ }
624
+ declare class VersionNotSetError extends Error {
625
+ constructor(t: TranslateFn);
626
+ }
627
+ declare class InvalidCommandNameError extends Error {
628
+ commandName: string;
629
+ constructor(commandName: string, t: TranslateFn);
630
+ }
631
+ declare class LocaleNotCalledFirstError extends Error {
632
+ constructor(t: TranslateFn);
634
633
  }
635
634
 
636
- declare function resolveFlattenCommands(commands: Commands, t: TranslateFn): Map<string[] | typeof Root, CommandAlias<string, CommandOptions<string[], MaybeArray$1<string | typeof Root>, Flags>>>;
637
- declare function resolveCommand(commands: Commands, argv: string[], t: TranslateFn): [Command<string | RootType> | undefined, string[] | RootType | undefined];
638
- declare function resolveCommandStrict(commands: Commands, name: CommandType | string[], t: TranslateFn): [Command<string | RootType> | undefined, string[] | RootType | undefined];
639
- declare function resolveSubcommandsByParent(commands: Commands, parent: string | string[], depth?: number): Command<string, CommandOptions<string[], MaybeArray$1<string | typeof Root>, Flags>>[];
640
- declare const resolveRootCommands: (commands: Commands) => Command<string, CommandOptions<string[], MaybeArray$1<string | typeof Root>, Flags>>[];
641
- declare const resolveArgv: () => string[];
642
- declare function compose(inspectors: Inspector[]): (ctx: InspectorContext) => void;
643
- declare const isValidName: (name: CommandType) => boolean;
644
- declare const withBrackets: (s: string, isOptional?: boolean) => string;
645
- declare const formatCommandName: (name: string | string[] | RootType) => string;
646
- declare const detectLocale: () => string;
635
+ declare function resolveFlattenCommands(commands: Commands, t: TranslateFn): Map<string[] | typeof Root, CommandAlias>;
636
+ declare function resolveCommand(commands: Commands, argv: string[], t: TranslateFn): [Command<string | RootType> | undefined, string[] | RootType | undefined];
637
+ declare const resolveArgv: () => string[];
638
+ declare function compose(inspectors: Inspector[]): (ctx: InspectorContext) => void;
639
+ declare const isValidName: (name: CommandType) => boolean;
640
+ declare const withBrackets: (s: string, isOptional?: boolean) => string;
641
+ declare const formatCommandName: (name: string | string[] | RootType) => string;
642
+ declare const detectLocale: () => string;
647
643
  declare const stripFlags: (argv: string[]) => string[];
648
644
 
649
- export { Clerc, Command, CommandAlias, CommandCustomProperties, CommandExistsError, CommandNameConflictError, CommandOptions, CommandType, CommandWithHandler, Commands, DescriptionNotSetError, FallbackType, Flag, FlagOptions, FlagWithoutDescription, Flags, FlagsWithoutDescription, Handler, HandlerContext, HandlerInCommand, I18N, Inspector, InspectorContext, InspectorFn, InspectorObject, InvalidCommandNameError, LocaleNotCalledFirstError, Locales, MakeEventMap, NameNotSetError, NoCommandGivenError, NoSuchCommandError, ParseOptions, Plugin, Root, RootType, TranslateFn, VersionNotSetError, compose, defineCommand, defineHandler, defineInspector, definePlugin, detectLocale, formatCommandName, isValidName, resolveArgv, resolveCommand, resolveCommandStrict, resolveFlattenCommands, resolveRootCommands, resolveSubcommandsByParent, stripFlags, withBrackets };
645
+ 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, InvalidCommandNameError, LocaleNotCalledFirstError, Locales, MakeEventMap, NameNotSetError, NoCommandGivenError, NoSuchCommandError, ParseOptions, Plugin, Root, RootType, TranslateFn, VersionNotSetError, compose, defineCommand, defineHandler, defineInspector, definePlugin, detectLocale, formatCommandName, isValidName, resolveArgv, resolveCommand, resolveFlattenCommands, stripFlags, withBrackets };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{format as ce}from"node:util";class Re{constructor(){this.listenerMap={},this.wildcardListeners=new Set}on(t,s){return t==="*"?(this.wildcardListeners.add(s),this):(this.listenerMap[t]||(this.listenerMap[t]=new Set),this.listenerMap[t].add(s),this)}emit(t,...s){return this.listenerMap[t]&&(this.wildcardListeners.forEach(r=>r(t,...s)),this.listenerMap[t].forEach(r=>r(...s))),this}off(t,s){var r,n;return t==="**"?(this.listenerMap={},this.wildcardListeners.clear(),this):t==="*"?(s?this.wildcardListeners.delete(s):this.wildcardListeners.clear(),this):(s?(r=this.listenerMap[t])==null||r.delete(s):(n=this.listenerMap[t])==null||n.clear(),this)}}const $e="known-flag",je="unknown-flag",qe="argument",{stringify:A}=JSON,Te=/\B([A-Z])/g,Ge=e=>e.replace(Te,"-$1").toLowerCase(),{hasOwnProperty:He}=Object.prototype,k=(e,t)=>He.call(e,t),Ue=e=>Array.isArray(e),ue=e=>typeof e=="function"?[e,!1]:Ue(e)?[e[0],!0]:ue(e.type),Ve=(e,t)=>e===Boolean?t!=="false":t,Je=(e,t)=>typeof t=="boolean"?t:e===Number&&t===""?Number.NaN:e(t),ze=/[\s.:=]/,Ke=e=>{const t=`Flag name ${A(e)}`;if(e.length===0)throw new Error(`${t} cannot be empty`);if(e.length===1)throw new Error(`${t} must be longer than a character`);const s=e.match(ze);if(s)throw new Error(`${t} cannot contain ${A(s==null?void 0:s[0])}`)},Ze=e=>{const t={},s=(r,n)=>{if(k(t,r))throw new Error(`Duplicate flags named ${A(r)}`);t[r]=n};for(const r in e){if(!k(e,r))continue;Ke(r);const n=e[r],o=[[],...ue(n),n];s(r,o);const a=Ge(r);if(r!==a&&s(a,o),"alias"in n&&typeof n.alias=="string"){const{alias:i}=n,c=`Flag alias ${A(i)} for flag ${A(r)}`;if(i.length===0)throw new Error(`${c} cannot be empty`);if(i.length>1)throw new Error(`${c} must be a single character`);s(i,o)}}return t},Qe=(e,t)=>{const s={};for(const r in e){if(!k(e,r))continue;const[n,,o,a]=t[r];if(n.length===0&&"default"in a){let{default:i}=a;typeof i=="function"&&(i=i()),s[r]=i}else s[r]=o?n:n.pop()}return s},R="--",Xe=/[.:=]/,Ye=/^-{1,2}\w/,et=e=>{if(!Ye.test(e))return;const t=!e.startsWith(R);let s=e.slice(t?1:2),r;const n=s.match(Xe);if(n){const{index:o}=n;r=s.slice(o+1),s=s.slice(0,o)}return[s,r,t]},tt=(e,{onFlag:t,onArgument:s})=>{let r;const n=(o,a)=>{if(typeof r!="function")return!0;r(o,a),r=void 0};for(let o=0;o<e.length;o+=1){const a=e[o];if(a===R){n();const c=e.slice(o+1);s==null||s(c,[o],!0);break}const i=et(a);if(i){if(n(),!t)continue;const[c,l,m]=i;if(m)for(let d=0;d<c.length;d+=1){n();const g=d===c.length-1;r=t(c[d],g?l:void 0,[o,d+1,g])}else r=t(c,l,[o])}else n(a,[o])&&(s==null||s([a],[o]))}n()},st=(e,t)=>{for(const[s,r,n]of t.reverse()){if(r){const o=e[s];let a=o.slice(0,r);if(n||(a+=o.slice(r+1)),a!=="-"){e[s]=a;continue}}e.splice(s,1)}},le=(e,t=process.argv.slice(2),{ignore:s}={})=>{const r=[],n=Ze(e),o={},a=[];return a[R]=[],tt(t,{onFlag(i,c,l){const m=k(n,i);if(!(s!=null&&s(m?$e:je,i,c))){if(m){const[d,g]=n[i],S=Ve(g,c),v=(T,G)=>{r.push(l),G&&r.push(G),d.push(Je(g,T||""))};return S===void 0?v:v(S)}k(o,i)||(o[i]=[]),o[i].push(c===void 0?!0:c),r.push(l)}},onArgument(i,c,l){s!=null&&s(qe,t[c[0]])||(a.push(...i),l?(a[R]=i,t.splice(c[0])):r.push(c))}}),st(t,r),{flags:Qe(e,n),unknownFlags:o,_:a}};function H(e){return e!==null&&typeof e=="object"}function U(e,t,s=".",r){if(!H(t))return U(e,{},s,r);const n=Object.assign({},t);for(const o in e){if(o==="__proto__"||o==="constructor")continue;const a=e[o];a!=null&&(r&&r(n,o,a,s)||(Array.isArray(a)&&Array.isArray(n[o])?n[o]=[...a,...n[o]]:H(a)&&H(n[o])?n[o]=U(a,n[o],(s?`${s}.`:"")+o.toString(),r):n[o]=a))}return n}function rt(e){return(...t)=>t.reduce((s,r)=>U(s,r,"",e),{})}const ot=rt(),V=e=>Array.isArray(e)?e:[e],nt=e=>e.replace(/[\W_]([a-z\d])?/gi,(t,s)=>s?s.toUpperCase():""),he=(e,t)=>t.length!==e.length?!1:e.every((s,r)=>s===t[r]),de=(e,t)=>t.length>e.length?!1:he(e.slice(0,t.length),t),L=JSON.stringify;class fe extends Error{constructor(t,s){super(s("core.commandExists",L(t))),this.commandName=t}}class me extends Error{constructor(t,s){super(s("core.noSuchCommand",L(t))),this.commandName=t}}class pe extends Error{constructor(t){super(t("core.noCommandGiven"))}}class Ce extends Error{constructor(t,s,r){super(r("core.commandNameConflict",L(t),L(s))),this.n1=t,this.n2=s}}class we extends Error{constructor(t){super(t("core.nameNotSet"))}}class ge extends Error{constructor(t){super(t("core.descriptionNotSet"))}}class Ee extends Error{constructor(t){super(t("core.versionNotSet"))}}class _e extends Error{constructor(t,s){super(s("core.badNameFormat",L(t))),this.commandName=t}}class J extends Error{constructor(t){super(t("core.localeMustBeCalledFirst"))}}const ve=typeof Deno!="undefined",at=typeof process!="undefined"&&!ve,it=process.versions.electron&&!process.defaultApp;function Me(e,t,s,r){if(s.alias){const n=V(s.alias);for(const o of n){if(o in t)throw new Ce(t[o].name,s.name,r);e.set(typeof o=="symbol"?o:o.split(" "),{...s,__isAlias:!0})}}}function z(e,t){const s=new Map;e[f]&&(s.set(f,e[f]),Me(s,e,e[f],t));for(const r of Object.values(e))Me(s,e,r,t),s.set(r.name.split(" "),r);return s}function Fe(e,t,s){const r=z(e,s);for(const[n,o]of r.entries()){const a=le((o==null?void 0:o.flags)||{},[...t]),{_:i}=a;if(n!==f&&de(i,n))return[o,n]}return r.has(f)?[r.get(f),f]:[void 0,void 0]}function ct(e,t,s){if(t===f)return[e[f],f];const r=V(t),n=z(e,s);let o,a;return n.forEach((i,c)=>{c===f||a===f||he(r,c)&&(o=i,a=c)}),[o,a]}function ye(e,t,s=1/0){const r=t===""?[]:Array.isArray(t)?t:t.split(" ");return Object.values(e).filter(n=>{const o=n.name.split(" ");return de(o,r)&&o.length-r.length<=s})}const ut=e=>ye(e,"",1),K=()=>at?process.argv.slice(it?1:2):ve?Deno.args:[];function Be(e){const t={pre:[],normal:[],post:[]};for(const r of e){const n=typeof r=="object"?r:{fn:r},{enforce:o,fn:a}=n;o==="post"||o==="pre"?t[o].push(a):t.normal.push(a)}const s=[...t.pre,...t.normal,...t.post];return r=>{const n=[];let o=0;const a=i=>{o=i;const c=s[i],l=c(r,a.bind(null,i+1));l&&n.push(l)};if(a(0),o+1===s.length)for(const i of n)i()}}const lt=/\s\s+/,Ne=e=>e===f?!0:!(e.startsWith(" ")||e.endsWith(" "))&&!lt.test(e),ht=(e,t)=>t?`[${e}]`:`<${e}>`,dt="<Root>",Se=e=>Array.isArray(e)?e.join(" "):typeof e=="string"?e:dt,Ae=()=>process.env.CLERC_LOCALE?process.env.CLERC_LOCALE:Intl.DateTimeFormat().resolvedOptions().locale,ke=e=>e.filter(t=>!t.startsWith("-")),{stringify:B}=JSON;function Z(e,t){const s=[];let r,n;for(const o of e){if(n)throw new Error(t("core.spreadParameterMustBeLast",B(n)));const a=o[0],i=o[o.length-1];let c;if(a==="<"&&i===">"&&(c=!0,r))throw new Error(t("core.requiredParameterMustBeBeforeOptional",B(o),B(r)));if(a==="["&&i==="]"&&(c=!1,r=o),c===void 0)throw new Error(t("core.parameterMustBeWrappedInBrackets",B(o)));let l=o.slice(1,-1);const m=l.slice(-3)==="...";m&&(n=o,l=l.slice(0,-3)),s.push({name:l,required:c,spread:m})}return s}function Q(e,t,s,r){for(let n=0;n<t.length;n+=1){const{name:o,required:a,spread:i}=t[n],c=nt(o);if(c in e)throw new Error(r("core.parameterIsUsedMoreThanOnce",B(o)));const l=i?s.slice(n):s[n];if(i&&(n=t.length),a&&(!l||i&&l.length===0))throw new Error(r("core.missingRequiredParameter",B(o)));e[c]=l}}const ft={en:{"core.commandExists":'Command "%s" exists.',"core.noSuchCommand":"No such command: %s.","core.noCommandGiven":"No command given.","core.commandNameConflict":"Command name %s conflicts with %s. Maybe caused by alias.","core.nameNotSet":"Name not set.","core.descriptionNotSet":"Description not set.","core.versionNotSet":"Version not set.","core.badNameFormat":"Bad name format: %s.","core.localeMustBeCalledFirst":"locale() or fallbackLocale() must be called at first.","core.cliParseMustBeCalled":"cli.parse() must be called.","core.spreadParameterMustBeLast":"Invalid Parameter: Spread parameter %s must be last.","core.requiredParameterCannotComeAfterOptionalParameter":"Invalid Parameter: Required parameter %s cannot come after optional parameter %s.","core.parameterMustBeWrappedInBrackets":"Invalid Parameter: Parameter %s must be wrapped in <> (required parameter) or [] (optional parameter).","core.parameterIsUsedMoreThanOnce":"Invalid Parameter: Parameter %s is used more than once.","core.missingRequiredParameter":"Missing required parameter %s."},"zh-CN":{"core.commandExists":'\u547D\u4EE4 "%s" \u5DF2\u5B58\u5728\u3002',"core.noSuchCommand":"\u627E\u4E0D\u5230\u547D\u4EE4: %s\u3002","core.noCommandGiven":"\u6CA1\u6709\u8F93\u5165\u547D\u4EE4\u3002","core.commandNameConflict":"\u547D\u4EE4\u540D\u79F0 %s \u548C %s \u51B2\u7A81\u3002 \u53EF\u80FD\u662F\u7531\u4E8E\u522B\u540D\u5BFC\u81F4\u7684\u3002","core.nameNotSet":"\u672A\u8BBE\u7F6ECLI\u540D\u79F0\u3002","core.descriptionNotSet":"\u672A\u8BBE\u7F6ECLI\u63CF\u8FF0\u3002","core.versionNotSet":"\u672A\u8BBE\u7F6ECLI\u7248\u672C\u3002","core.badNameFormat":"\u9519\u8BEF\u7684\u547D\u4EE4\u540D\u5B57\u683C\u5F0F: %s\u3002","core.localeMustBeCalledFirst":"locale() \u6216 fallbackLocale() \u5FC5\u987B\u5728\u6700\u5F00\u59CB\u8C03\u7528\u3002","core.cliParseMustBeCalled":"cli.parse() \u5FC5\u987B\u88AB\u8C03\u7528\u3002","core.spreadParameterMustBeLast":"\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u5C55\u5F00\u53C2\u6570 %s \u5FC5\u987B\u5728\u6700\u540E\u3002","core.requiredParameterCannotComeAfterOptionalParameter":"\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u5FC5\u586B\u53C2\u6570 %s \u4E0D\u80FD\u5728\u53EF\u9009\u53C2\u6570 %s \u4E4B\u540E\u3002","core.parameterMustBeWrappedInBrackets":"\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u53C2\u6570 %s \u5FC5\u987B\u88AB <> (\u5FC5\u586B\u53C2\u6570) \u6216 [] (\u53EF\u9009\u53C2\u6570) \u5305\u88F9\u3002","core.parameterIsUsedMoreThanOnce":"\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u53C2\u6570 %s \u88AB\u4F7F\u7528\u4E86\u591A\u6B21\u3002","core.missingRequiredParameter":"\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570 %s\u3002"}};var X=(e,t,s)=>{if(!t.has(e))throw TypeError("Cannot "+s)},u=(e,t,s)=>(X(e,t,"read from private field"),s?s.call(e):t.get(e)),h=(e,t,s)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,s)},C=(e,t,s,r)=>(X(e,t,"write to private field"),r?r.call(e,s):t.set(e,s),s),p=(e,t,s)=>(X(e,t,"access private method"),s),_,M,F,W,D,$,j,N,b,O,P,I,x,y,Y,Le,ee,We,te,De,w,E,se,be,re,Oe,oe,Pe,q,ne,ae,Ie;const f=Symbol.for("Clerc.Root"),xe=class{constructor(e,t,s){h(this,Y),h(this,ee),h(this,te),h(this,w),h(this,se),h(this,re),h(this,oe),h(this,q),h(this,ae),h(this,_,""),h(this,M,""),h(this,F,""),h(this,W,[]),h(this,D,{}),h(this,$,new Re),h(this,j,{}),h(this,N,new Set),h(this,b,void 0),h(this,O,[]),h(this,P,!1),h(this,I,"en"),h(this,x,"en"),h(this,y,{}),this.i18n={add:r=>{C(this,y,ot(u(this,y),r))},t:(r,...n)=>{const o=u(this,y)[u(this,x)]||u(this,y)[u(this,I)],a=u(this,y)[u(this,I)];return o[r]?ce(o[r],...n):a[r]?ce(a[r],...n):void 0}},C(this,_,e||u(this,_)),C(this,M,t||u(this,M)),C(this,F,s||u(this,F)),C(this,x,Ae()),p(this,te,De).call(this)}get _name(){return u(this,_)}get _description(){return u(this,M)}get _version(){return u(this,F)}get _inspectors(){return u(this,W)}get _commands(){return u(this,D)}get _flags(){return u(this,j)}static create(e,t,s){return new xe(e,t,s)}name(e){return p(this,w,E).call(this),C(this,_,e),this}description(e){return p(this,w,E).call(this),C(this,M,e),this}version(e){return p(this,w,E).call(this),C(this,F,e),this}locale(e){if(u(this,P))throw new J(this.i18n.t);return C(this,x,e),this}fallbackLocale(e){if(u(this,P))throw new J(this.i18n.t);return C(this,I,e),this}errorHandler(e){return u(this,O).push(e),this}command(e,t,s={}){return p(this,q,ne).call(this,()=>p(this,se,be).call(this,e,t,s)),this}flag(e,t,s){return u(this,j)[e]={description:t,...s},this}on(e,t){return u(this,$).on(e,t),this}use(e){return p(this,w,E).call(this),e.setup(this)}inspector(e){return p(this,w,E).call(this),u(this,W).push(e),this}parse(e=K()){p(this,w,E).call(this);const{argv:t,run:s}=Array.isArray(e)?{argv:e,run:!0}:{argv:K(),...e};return C(this,b,[...t]),p(this,re,Oe).call(this),s&&this.runMatchedCommand(),this}runMatchedCommand(){return p(this,q,ne).call(this,()=>p(this,ae,Ie).call(this)),process.title=u(this,_),this}};let mt=xe;_=new WeakMap,M=new WeakMap,F=new WeakMap,W=new WeakMap,D=new WeakMap,$=new WeakMap,j=new WeakMap,N=new WeakMap,b=new WeakMap,O=new WeakMap,P=new WeakMap,I=new WeakMap,x=new WeakMap,y=new WeakMap,Y=new WeakSet,Le=function(){return u(this,N).has(f)},ee=new WeakSet,We=function(){return Object.prototype.hasOwnProperty.call(this._commands,f)},te=new WeakSet,De=function(){this.i18n.add(ft)},w=new WeakSet,E=function(){C(this,P,!0)},se=new WeakSet,be=function(e,t,s={}){p(this,w,E).call(this);const{t:r}=this.i18n,o=(d=>!(typeof d=="string"||d===f))(e),a=o?e.name:e;if(!Ne(a))throw new _e(a,r);const{handler:i=void 0,...c}=o?e:{name:a,description:t,...s},l=[c.name],m=c.alias?V(c.alias):[];c.alias&&l.push(...m);for(const d of l)if(u(this,N).has(d))throw new fe(Se(d),r);return u(this,D)[a]=c,u(this,N).add(c.name),m.forEach(d=>u(this,N).add(d)),o&&i&&this.on(e.name,i),this},re=new WeakSet,Oe=function(){const{t:e}=this.i18n;if(!u(this,_))throw new we(e);if(!u(this,M))throw new ge(e);if(!u(this,F))throw new Ee(e)},oe=new WeakSet,Pe=function(e){const t=u(this,b),{t:s}=this.i18n,[r,n]=e(),o=!!r,a=le((r==null?void 0:r.flags)||{},[...t]),{_:i,flags:c,unknownFlags:l}=a;let m=!o||r.name===f?i:i.slice(r.name.split(" ").length),d=(r==null?void 0:r.parameters)||[];const g=d.indexOf("--"),S=d.slice(g+1)||[],v=Object.create(null);if(g>-1&&S.length>0){d=d.slice(0,g);const ie=i["--"];m=m.slice(0,-ie.length||void 0),Q(v,Z(d,s),m,s),Q(v,Z(S,s),ie,s)}else Q(v,Z(d,s),m,s);const T={...c,...l};return{name:r==null?void 0:r.name,called:Array.isArray(n)?n.join(" "):n,resolved:o,hasRootOrAlias:u(this,Y,Le),hasRoot:u(this,ee,We),raw:{...a,parameters:m,mergedFlags:T},parameters:v,flags:c,unknownFlags:l,cli:this}},q=new WeakSet,ne=function(e){try{e()}catch(t){if(u(this,O).length>0)u(this,O).forEach(s=>s(t));else throw t}},ae=new WeakSet,Ie=function(){p(this,w,E).call(this);const{t:e}=this.i18n,t=u(this,b);if(!t)throw new Error(e("core.cliParseMustBeCalled"));const s=()=>Fe(u(this,D),t,e),r=()=>p(this,oe,Pe).call(this,s),n={enforce:"post",fn:i=>{const[c]=s(),l=ke(t).join(" ");if(!c)throw l?new me(l,e):new pe(e);u(this,$).emit(c.name,i)}},o=[...u(this,W),n];Be(o)(r())};const pt=e=>e,Ct=(e,t,s)=>s,wt=(e,t)=>t,gt=(e,t)=>({...e,handler:t});export{mt as Clerc,fe as CommandExistsError,Ce as CommandNameConflictError,ge as DescriptionNotSetError,_e as InvalidCommandNameError,J as LocaleNotCalledFirstError,we as NameNotSetError,pe as NoCommandGivenError,me as NoSuchCommandError,f as Root,Ee as VersionNotSetError,Be as compose,gt as defineCommand,Ct as defineHandler,wt as defineInspector,pt as definePlugin,Ae as detectLocale,Se as formatCommandName,Ne as isValidName,K as resolveArgv,Fe as resolveCommand,ct as resolveCommandStrict,z as resolveFlattenCommands,ut as resolveRootCommands,ye as resolveSubcommandsByParent,ke as stripFlags,ht as withBrackets};
1
+ import{format as ae}from"node:util";import"@clerc/core";class Pe{constructor(){this.listenerMap={},this.wildcardListeners=new Set}on(t,s){return t==="*"?(this.wildcardListeners.add(s),this):(this.listenerMap[t]||(this.listenerMap[t]=new Set),this.listenerMap[t].add(s),this)}emit(t,...s){return this.listenerMap[t]&&(this.wildcardListeners.forEach(r=>r(t,...s)),this.listenerMap[t].forEach(r=>r(...s))),this}off(t,s){var r,n;return t==="**"?(this.listenerMap={},this.wildcardListeners.clear(),this):t==="*"?(s?this.wildcardListeners.delete(s):this.wildcardListeners.clear(),this):(s?(r=this.listenerMap[t])==null||r.delete(s):(n=this.listenerMap[t])==null||n.clear(),this)}}const Ie="known-flag",xe="unknown-flag",Re="argument",{stringify:A}=JSON,$e=/\B([A-Z])/g,qe=e=>e.replace($e,"-$1").toLowerCase(),{hasOwnProperty:Te}=Object.prototype,L=(e,t)=>Te.call(e,t),je=e=>Array.isArray(e),ie=e=>typeof e=="function"?[e,!1]:je(e)?[e[0],!0]:ie(e.type),Ge=(e,t)=>e===Boolean?t!=="false":t,He=(e,t)=>typeof t=="boolean"?t:e===Number&&t===""?Number.NaN:e(t),Ue=/[\s.:=]/,Ve=e=>{const t=`Flag name ${A(e)}`;if(e.length===0)throw new Error(`${t} cannot be empty`);if(e.length===1)throw new Error(`${t} must be longer than a character`);const s=e.match(Ue);if(s)throw new Error(`${t} cannot contain ${A(s==null?void 0:s[0])}`)},Je=e=>{const t={},s=(r,n)=>{if(L(t,r))throw new Error(`Duplicate flags named ${A(r)}`);t[r]=n};for(const r in e){if(!L(e,r))continue;Ve(r);const n=e[r],o=[[],...ie(n),n];s(r,o);const a=qe(r);if(r!==a&&s(a,o),"alias"in n&&typeof n.alias=="string"){const{alias:i}=n,c=`Flag alias ${A(i)} for flag ${A(r)}`;if(i.length===0)throw new Error(`${c} cannot be empty`);if(i.length>1)throw new Error(`${c} must be a single character`);s(i,o)}}return t},ze=(e,t)=>{const s={};for(const r in e){if(!L(e,r))continue;const[n,,o,a]=t[r];if(n.length===0&&"default"in a){let{default:i}=a;typeof i=="function"&&(i=i()),s[r]=i}else s[r]=o?n:n.pop()}return s},T="--",Ke=/[.:=]/,Ze=/^-{1,2}\w/,Qe=e=>{if(!Ze.test(e))return;const t=!e.startsWith(T);let s=e.slice(t?1:2),r;const n=s.match(Ke);if(n){const{index:o}=n;r=s.slice(o+1),s=s.slice(0,o)}return[s,r,t]},Xe=(e,{onFlag:t,onArgument:s})=>{let r;const n=(o,a)=>{if(typeof r!="function")return!0;r(o,a),r=void 0};for(let o=0;o<e.length;o+=1){const a=e[o];if(a===T){n();const c=e.slice(o+1);s==null||s(c,[o],!0);break}const i=Qe(a);if(i){if(n(),!t)continue;const[c,l,p]=i;if(p)for(let d=0;d<c.length;d+=1){n();const C=d===c.length-1;r=t(c[d],C?l:void 0,[o,d+1,C])}else r=t(c,l,[o])}else n(a,[o])&&(s==null||s([a],[o]))}n()},Ye=(e,t)=>{for(const[s,r,n]of t.reverse()){if(r){const o=e[s];let a=o.slice(0,r);if(n||(a+=o.slice(r+1)),a!=="-"){e[s]=a;continue}}e.splice(s,1)}},ce=(e,t=process.argv.slice(2),{ignore:s}={})=>{const r=[],n=Je(e),o={},a=[];return a[T]=[],Xe(t,{onFlag(i,c,l){const p=L(n,i);if(!(s!=null&&s(p?Ie:xe,i,c))){if(p){const[d,C]=n[i],y=Ge(C,c),S=(B,q)=>{r.push(l),q&&r.push(q),d.push(He(C,B||""))};return y===void 0?S:S(y)}L(o,i)||(o[i]=[]),o[i].push(c===void 0?!0:c),r.push(l)}},onArgument(i,c,l){s!=null&&s(Re,t[c[0]])||(a.push(...i),l?(a[T]=i,t.splice(c[0])):r.push(c))}}),Ye(t,r),{flags:ze(e,n),unknownFlags:o,_:a}};function H(e){return e!==null&&typeof e=="object"}function U(e,t,s=".",r){if(!H(t))return U(e,{},s,r);const n=Object.assign({},t);for(const o in e){if(o==="__proto__"||o==="constructor")continue;const a=e[o];a!=null&&(r&&r(n,o,a,s)||(Array.isArray(a)&&Array.isArray(n[o])?n[o]=[...a,...n[o]]:H(a)&&H(n[o])?n[o]=U(a,n[o],(s?`${s}.`:"")+o.toString(),r):n[o]=a))}return n}function et(e){return(...t)=>t.reduce((s,r)=>U(s,r,"",e),{})}const tt=et(),ue=e=>Array.isArray(e)?e:[e],st=e=>e.replace(/[\W_]([a-z\d])?/gi,(t,s)=>s?s.toUpperCase():""),rt=(e,t)=>t.length!==e.length?!1:e.every((s,r)=>s===t[r]),ot=(e,t)=>t.length>e.length?!1:rt(e.slice(0,t.length),t),W=JSON.stringify;class le extends Error{constructor(t,s){super(s("core.commandExists",W(t))),this.commandName=t}}class he extends Error{constructor(t,s){super(s("core.noSuchCommand",W(t))),this.commandName=t}}class de extends Error{constructor(t){super(t("core.noCommandGiven"))}}class fe extends Error{constructor(t,s,r){super(r("core.commandNameConflict",W(t),W(s))),this.n1=t,this.n2=s}}class me extends Error{constructor(t){super(t("core.nameNotSet"))}}class pe extends Error{constructor(t){super(t("core.descriptionNotSet"))}}class Ce extends Error{constructor(t){super(t("core.versionNotSet"))}}class we extends Error{constructor(t,s){super(s("core.badNameFormat",W(t))),this.commandName=t}}class V extends Error{constructor(t){super(t("core.localeMustBeCalledFirst"))}}const ge=typeof Deno!="undefined",nt=typeof process!="undefined"&&!ge,at=process.versions.electron&&!process.defaultApp;function Ee(e,t,s,r){if(s.alias){const n=ue(s.alias);for(const o of n){if(o in t)throw new fe(t[o].name,s.name,r);e.set(typeof o=="symbol"?o:o.split(" "),{...s,__isAlias:!0})}}}function _e(e,t){const s=new Map;e[m]&&(s.set(m,e[m]),Ee(s,e,e[m],t));for(const r of Object.values(e))Ee(s,e,r,t),s.set(r.name.split(" "),r);return s}function ve(e,t,s){const r=_e(e,s);for(const[n,o]of r.entries()){const a=ce((o==null?void 0:o.flags)||{},[...t]),{_:i}=a;if(n!==m&&ot(i,n))return[o,n]}return r.has(m)?[r.get(m),m]:[void 0,void 0]}const J=()=>nt?process.argv.slice(at?1:2):ge?Deno.args:[];function Me(e){const t={pre:[],normal:[],post:[]};for(const r of e){const n=typeof r=="object"?r:{fn:r},{enforce:o,fn:a}=n;o==="post"||o==="pre"?t[o].push(a):t.normal.push(a)}const s=[...t.pre,...t.normal,...t.post];return r=>{const n=[];let o=0;const a=i=>{o=i;const c=s[i],l=c(r,a.bind(null,i+1));l&&n.push(l)};if(a(0),o+1===s.length)for(const i of n)i()}}const it=/\s\s+/,Fe=e=>e===m?!0:!(e.startsWith(" ")||e.endsWith(" "))&&!it.test(e),ct=(e,t)=>t?`[${e}]`:`<${e}>`,ut="<Root>",ye=e=>Array.isArray(e)?e.join(" "):typeof e=="string"?e:ut,Be=()=>process.env.CLERC_LOCALE?process.env.CLERC_LOCALE:Intl.DateTimeFormat().resolvedOptions().locale,Ne=e=>e.filter(t=>!t.startsWith("-")),{stringify:N}=JSON;function z(e,t){const s=[];let r,n;for(const o of e){if(n)throw new Error(t("core.spreadParameterMustBeLast",N(n)));const a=o[0],i=o[o.length-1];let c;if(a==="<"&&i===">"&&(c=!0,r))throw new Error(t("core.requiredParameterMustBeBeforeOptional",N(o),N(r)));if(a==="["&&i==="]"&&(c=!1,r=o),c===void 0)throw new Error(t("core.parameterMustBeWrappedInBrackets",N(o)));let l=o.slice(1,-1);const p=l.slice(-3)==="...";p&&(n=o,l=l.slice(0,-3)),s.push({name:l,required:c,spread:p})}return s}function K(e,t,s,r){for(let n=0;n<t.length;n+=1){const{name:o,required:a,spread:i}=t[n],c=st(o);if(c in e)throw new Error(r("core.parameterIsUsedMoreThanOnce",N(o)));const l=i?s.slice(n):s[n];if(i&&(n=t.length),a&&(!l||i&&l.length===0))throw new Error(r("core.missingRequiredParameter",N(o)));e[c]=l}}const lt={en:{"core.commandExists":'Command "%s" exists.',"core.noSuchCommand":"No such command: %s.","core.noCommandGiven":"No command given.","core.commandNameConflict":"Command name %s conflicts with %s. Maybe caused by alias.","core.nameNotSet":"Name not set.","core.descriptionNotSet":"Description not set.","core.versionNotSet":"Version not set.","core.badNameFormat":"Bad name format: %s.","core.localeMustBeCalledFirst":"locale() or fallbackLocale() must be called at first.","core.cliParseMustBeCalled":"cli.parse() must be called.","core.spreadParameterMustBeLast":"Invalid Parameter: Spread parameter %s must be last.","core.requiredParameterCannotComeAfterOptionalParameter":"Invalid Parameter: Required parameter %s cannot come after optional parameter %s.","core.parameterMustBeWrappedInBrackets":"Invalid Parameter: Parameter %s must be wrapped in <> (required parameter) or [] (optional parameter).","core.parameterIsUsedMoreThanOnce":"Invalid Parameter: Parameter %s is used more than once.","core.missingRequiredParameter":"Missing required parameter %s."},"zh-CN":{"core.commandExists":'\u547D\u4EE4 "%s" \u5DF2\u5B58\u5728\u3002',"core.noSuchCommand":"\u627E\u4E0D\u5230\u547D\u4EE4: %s\u3002","core.noCommandGiven":"\u6CA1\u6709\u8F93\u5165\u547D\u4EE4\u3002","core.commandNameConflict":"\u547D\u4EE4\u540D\u79F0 %s \u548C %s \u51B2\u7A81\u3002 \u53EF\u80FD\u662F\u7531\u4E8E\u522B\u540D\u5BFC\u81F4\u7684\u3002","core.nameNotSet":"\u672A\u8BBE\u7F6ECLI\u540D\u79F0\u3002","core.descriptionNotSet":"\u672A\u8BBE\u7F6ECLI\u63CF\u8FF0\u3002","core.versionNotSet":"\u672A\u8BBE\u7F6ECLI\u7248\u672C\u3002","core.badNameFormat":"\u9519\u8BEF\u7684\u547D\u4EE4\u540D\u5B57\u683C\u5F0F: %s\u3002","core.localeMustBeCalledFirst":"locale() \u6216 fallbackLocale() \u5FC5\u987B\u5728\u6700\u5F00\u59CB\u8C03\u7528\u3002","core.cliParseMustBeCalled":"cli.parse() \u5FC5\u987B\u88AB\u8C03\u7528\u3002","core.spreadParameterMustBeLast":"\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u5C55\u5F00\u53C2\u6570 %s \u5FC5\u987B\u5728\u6700\u540E\u3002","core.requiredParameterCannotComeAfterOptionalParameter":"\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u5FC5\u586B\u53C2\u6570 %s \u4E0D\u80FD\u5728\u53EF\u9009\u53C2\u6570 %s \u4E4B\u540E\u3002","core.parameterMustBeWrappedInBrackets":"\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u53C2\u6570 %s \u5FC5\u987B\u88AB <> (\u5FC5\u586B\u53C2\u6570) \u6216 [] (\u53EF\u9009\u53C2\u6570) \u5305\u88F9\u3002","core.parameterIsUsedMoreThanOnce":"\u4E0D\u5408\u6CD5\u7684\u53C2\u6570: \u53C2\u6570 %s \u88AB\u4F7F\u7528\u4E86\u591A\u6B21\u3002","core.missingRequiredParameter":"\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570 %s\u3002"}};var Z=(e,t,s)=>{if(!t.has(e))throw TypeError("Cannot "+s)},u=(e,t,s)=>(Z(e,t,"read from private field"),s?s.call(e):t.get(e)),h=(e,t,s)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,s)},w=(e,t,s,r)=>(Z(e,t,"write to private field"),r?r.call(e,s):t.set(e,s),s),f=(e,t,s)=>(Z(e,t,"access private method"),s),_,v,M,D,b,j,O,k,P,I,x,R,$,F,Q,ke,X,Se,Y,Ae,g,E,ee,Le,te,We,se,De,G,re,oe,be;const m=Symbol.for("Clerc.Root"),Oe=class{constructor(e,t,s){h(this,Q),h(this,X),h(this,Y),h(this,g),h(this,ee),h(this,te),h(this,se),h(this,G),h(this,oe),h(this,_,""),h(this,v,""),h(this,M,""),h(this,D,[]),h(this,b,{}),h(this,j,new Pe),h(this,O,{}),h(this,k,new Set),h(this,P,void 0),h(this,I,[]),h(this,x,!1),h(this,R,"en"),h(this,$,"en"),h(this,F,{}),this.i18n={add:r=>{w(this,F,tt(u(this,F),r))},t:(r,...n)=>{const o=u(this,F)[u(this,$)]||u(this,F)[u(this,R)],a=u(this,F)[u(this,R)];return o[r]?ae(o[r],...n):a[r]?ae(a[r],...n):void 0}},w(this,_,e||u(this,_)),w(this,v,t||u(this,v)),w(this,M,s||u(this,M)),w(this,$,Be()),f(this,Y,Ae).call(this)}get _name(){return u(this,_)}get _description(){return u(this,v)}get _version(){return u(this,M)}get _inspectors(){return u(this,D)}get _commands(){return u(this,b)}get _flags(){return u(this,O)}static create(e,t,s){return new Oe(e,t,s)}name(e){return f(this,g,E).call(this),w(this,_,e),this}description(e){return f(this,g,E).call(this),w(this,v,e),this}version(e){return f(this,g,E).call(this),w(this,M,e),this}locale(e){if(u(this,x))throw new V(this.i18n.t);return w(this,$,e),this}fallbackLocale(e){if(u(this,x))throw new V(this.i18n.t);return w(this,R,e),this}errorHandler(e){return u(this,I).push(e),this}command(e,t,s={}){return f(this,G,re).call(this,()=>f(this,ee,Le).call(this,e,t,s)),this}flag(e,t,s){return u(this,O)[e]={description:t,...s},this}on(e,t){return u(this,j).on(e,t),this}use(e){return f(this,g,E).call(this),e.setup(this)}inspector(e){return f(this,g,E).call(this),u(this,D).push(e),this}parse(e=J()){f(this,g,E).call(this);const{argv:t,run:s}=Array.isArray(e)?{argv:e,run:!0}:{argv:J(),...e};return w(this,P,[...t]),f(this,te,We).call(this),s&&this.runMatchedCommand(),this}runMatchedCommand(){return f(this,G,re).call(this,()=>f(this,oe,be).call(this)),process.title=u(this,_),this}};let ht=Oe;_=new WeakMap,v=new WeakMap,M=new WeakMap,D=new WeakMap,b=new WeakMap,j=new WeakMap,O=new WeakMap,k=new WeakMap,P=new WeakMap,I=new WeakMap,x=new WeakMap,R=new WeakMap,$=new WeakMap,F=new WeakMap,Q=new WeakSet,ke=function(){return u(this,k).has(m)},X=new WeakSet,Se=function(){return Object.prototype.hasOwnProperty.call(this._commands,m)},Y=new WeakSet,Ae=function(){this.i18n.add(lt)},g=new WeakSet,E=function(){w(this,x,!0)},ee=new WeakSet,Le=function(e,t,s={}){f(this,g,E).call(this);const{t:r}=this.i18n,o=(d=>!(typeof d=="string"||d===m))(e),a=o?e.name:e;if(!Fe(a))throw new we(a,r);const{handler:i=void 0,...c}=o?e:{name:a,description:t,...s},l=[c.name],p=c.alias?ue(c.alias):[];c.alias&&l.push(...p);for(const d of l)if(u(this,k).has(d))throw new le(ye(d),r);return u(this,b)[a]=c,u(this,k).add(c.name),p.forEach(d=>u(this,k).add(d)),o&&i&&this.on(e.name,i),this},te=new WeakSet,We=function(){const{t:e}=this.i18n;if(!u(this,_))throw new me(e);if(!u(this,v))throw new pe(e);if(!u(this,M))throw new Ce(e)},se=new WeakSet,De=function(e){const t=u(this,P),{t:s}=this.i18n,[r,n]=e(),o=!!r,a={...u(this,O),...r==null?void 0:r.flags},i=ce(a,[...t]),{_:c,flags:l,unknownFlags:p}=i;let d=!o||r.name===m?c:c.slice(r.name.split(" ").length),C=(r==null?void 0:r.parameters)||[];const y=C.indexOf("--"),S=C.slice(y+1)||[],B=Object.create(null);if(y>-1&&S.length>0){C=C.slice(0,y);const ne=c["--"];d=d.slice(0,-ne.length||void 0),K(B,z(C,s),d,s),K(B,z(S,s),ne,s)}else K(B,z(C,s),d,s);const q={...l,...p};return{name:r==null?void 0:r.name,called:Array.isArray(n)?n.join(" "):n,resolved:o,hasRootOrAlias:u(this,Q,ke),hasRoot:u(this,X,Se),raw:{...i,parameters:d,mergedFlags:q},parameters:B,flags:l,unknownFlags:p,cli:this}},G=new WeakSet,re=function(e){try{e()}catch(t){if(u(this,I).length>0)u(this,I).forEach(s=>s(t));else throw t}},oe=new WeakSet,be=function(){f(this,g,E).call(this);const{t:e}=this.i18n,t=u(this,P);if(!t)throw new Error(e("core.cliParseMustBeCalled"));const s=()=>ve(u(this,b),t,e),r=()=>f(this,se,De).call(this,s),n={enforce:"post",fn:i=>{const[c]=s(),l=Ne(t).join(" ");if(!c)throw l?new he(l,e):new de(e);u(this,j).emit(c.name,i)}},o=[...u(this,D),n];Me(o)(r())};const dt=e=>e,ft=(e,t,s)=>s,mt=(e,t)=>t,pt=(e,t)=>({...e,handler:t});export{ht as Clerc,le as CommandExistsError,fe as CommandNameConflictError,pe as DescriptionNotSetError,we as InvalidCommandNameError,V as LocaleNotCalledFirstError,me as NameNotSetError,de as NoCommandGivenError,he as NoSuchCommandError,m as Root,Ce as VersionNotSetError,Me as compose,pt as defineCommand,ft as defineHandler,mt as defineInspector,dt as definePlugin,Be as detectLocale,ye as formatCommandName,Fe as isValidName,J as resolveArgv,ve as resolveCommand,_e as resolveFlattenCommands,Ne as stripFlags,ct as withBrackets};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clerc/core",
3
- "version": "0.34.0",
3
+ "version": "0.35.0",
4
4
  "author": "Ray <i@mk1.io> (https://github.com/so1ve)",
5
5
  "description": "Clerc core",
6
6
  "keywords": [
@@ -52,7 +52,7 @@
52
52
  "lite-emit": "^1.4.0",
53
53
  "type-fest": "^3.6.0",
54
54
  "type-flag": "^3.0.0",
55
- "@clerc/utils": "0.34.0"
55
+ "@clerc/utils": "0.35.0"
56
56
  },
57
57
  "scripts": {
58
58
  "build": "puild --minify",