44 Option as CommanderOption ,
55} from 'commander' ;
66import { compact } from 'lodash-es' ;
7+ import pIsPromise from 'p-is-promise' ;
8+
9+ export type HandlerInput = ( ...args : unknown [ ] ) => unknown ;
710
811export type Handler = ( ...args : unknown [ ] ) => void | Promise < void > ;
912
@@ -34,8 +37,9 @@ export type Config = {
3437 defaultCommandName ?: string ;
3538} ;
3639
37- export type CommandObjectInput = Omit < Command , 'options' > & {
40+ export type CommandObjectInput = Omit < Command , 'options' | 'handler' > & {
3841 options ?: OptionsInput ;
42+ handler : HandlerInput ;
3943} ;
4044
4145export type CommandObjectInObjectInput = Omit < CommandObjectInput , 'name' > &
@@ -51,9 +55,10 @@ export type OptionInObjectInput = Omit<Option, 'name'> &
5155 Partial < Pick < Option , 'name' > > ;
5256
5357export type OptionsInput = Option [ ] | Record < string , OptionInObjectInput > ;
54- type ConfigInput = Omit < Partial < Config > , 'commands' | 'options' > & {
58+ type ConfigInput = Omit < Partial < Config > , 'commands' | 'options' | 'action' > & {
5559 commands ?: CommandsInput ;
5660 options ?: OptionsInput ;
61+ action ?: HandlerInput ;
5762} ;
5863
5964const applyOptions = ( program , options : Option [ ] = [ ] ) => {
@@ -95,24 +100,42 @@ const getNormalizedCommands = (commands?: CommandsInput): Command[] => {
95100 if ( Array . isArray ( commands ) ) {
96101 return commands . map ( command => ( {
97102 ...command ,
103+ handler : toVoidReturning ( command . handler ) ,
98104 options : getNormalizedOptions ( command . options ) ,
99105 } ) ) ;
100106 }
101107
102108 return Object . entries ( commands ) . map ( ( [ name , command ] ) => ( {
103109 name,
104110 ...( typeof command === 'function'
105- ? { handler : command , options : [ ] }
106- : { ...command , options : getNormalizedOptions ( command . options ) } ) ,
111+ ? { handler : toVoidReturning ( command ) , options : [ ] }
112+ : {
113+ ...command ,
114+ handler : toVoidReturning ( command . handler ) ,
115+ options : getNormalizedOptions ( command . options ) ,
116+ } ) ,
107117 } ) ) ;
108118} ;
109119
120+ const toVoidReturning =
121+ func =>
122+ ( ...args ) => {
123+ const result = func ( ...args ) ;
124+
125+ if ( pIsPromise ( result ) ) {
126+ return Promise . resolve ( ) ;
127+ }
128+ } ;
129+
110130export default ( configInput : ConfigInput = { } ) => {
111131 const config : Config = defu (
112132 {
113133 ...configInput ,
114134 commands : getNormalizedCommands ( configInput . commands ) ,
115135 options : getNormalizedOptions ( configInput . options ) ,
136+ ...( configInput . action && {
137+ action : toVoidReturning ( configInput . action ) ,
138+ } ) ,
116139 } ,
117140 { allowUnknownOption : false } ,
118141 ) ;
0 commit comments