@wooksjs/event-cli 0.4.8 → 0.4.10

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.cjs +408 -403
  2. package/dist/index.mjs +408 -403
  3. package/package.json +7 -4
package/dist/index.cjs CHANGED
@@ -5,19 +5,19 @@ var wooks = require('wooks');
5
5
  var cliHelp = require('@prostojs/cli-help');
6
6
  var minimist = require('minimist');
7
7
 
8
- function createCliContext(data, options) {
9
- return eventCore.createEventContext({
10
- event: Object.assign(Object.assign({}, data), { type: 'CLI' }),
11
- options,
12
- });
13
- }
14
- /**
15
- * Wrapper on top of useEventContext that provides
16
- * proper context types for CLI event
17
- * @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
18
- */
19
- function useCliContext() {
20
- return eventCore.useEventContext('CLI');
8
+ function createCliContext(data, options) {
9
+ return eventCore.createEventContext({
10
+ event: Object.assign(Object.assign({}, data), { type: 'CLI' }),
11
+ options,
12
+ });
13
+ }
14
+ /**
15
+ * Wrapper on top of useEventContext that provides
16
+ * proper context types for CLI event
17
+ * @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
18
+ */
19
+ function useCliContext() {
20
+ return eventCore.useEventContext('CLI');
21
21
  }
22
22
 
23
23
  /******************************************************************************
@@ -34,7 +34,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
34
34
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
35
35
  PERFORMANCE OF THIS SOFTWARE.
36
36
  ***************************************************************************** */
37
- /* global Reflect, Promise */
37
+ /* global Reflect, Promise, SuppressedError, Symbol */
38
38
 
39
39
 
40
40
  function __awaiter(thisArg, _arguments, P, generator) {
@@ -45,400 +45,405 @@ function __awaiter(thisArg, _arguments, P, generator) {
45
45
  function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
46
46
  step((generator = generator.apply(thisArg, _arguments || [])).next());
47
47
  });
48
- }
49
-
50
- const cliShortcuts = {
51
- cli: 'CLI',
52
- };
53
- class WooksCli extends wooks.WooksAdapterBase {
54
- constructor(opts, wooks) {
55
- super(wooks, opts === null || opts === void 0 ? void 0 : opts.logger, opts === null || opts === void 0 ? void 0 : opts.router);
56
- this.opts = opts;
57
- this.alreadyComputedAliases = false;
58
- this.logger = (opts === null || opts === void 0 ? void 0 : opts.logger) || this.getLogger('wooks-cli');
59
- this.cliHelp =
60
- (opts === null || opts === void 0 ? void 0 : opts.cliHelp) instanceof cliHelp.CliHelpRenderer
61
- ? opts.cliHelp
62
- : new cliHelp.CliHelpRenderer(opts === null || opts === void 0 ? void 0 : opts.cliHelp);
63
- }
64
- /**
65
- * ### Register CLI Command
66
- * Command path segments may be separated by / or space.
67
- *
68
- * For example the folowing path are interpreted the same:
69
- * - "command test use:dev :name"
70
- * - "command/test/use:dev/:name"
71
- *
72
- * Where name will become an argument
73
- *
74
- * ```js
75
- * // example without options
76
- * app.cli('command/:arg', () => 'arg = ' + useRouteParams().params.arg )
77
- *
78
- * // example with options
79
- * app.cli('command/:arg', {
80
- * description: 'Description of the command',
81
- * options: [{ keys: ['project', 'p'], description: 'Description of the option', value: 'myProject' }],
82
- * args: { arg: 'Description of the arg' },
83
- * aliases: ['cmd'], // alias "cmd/:arg" will be registered
84
- * examples: [{
85
- * description: 'Example of usage with someProject',
86
- * cmd: 'argValue -p=someProject',
87
- * // will result in help display:
88
- * // "# Example of usage with someProject\n" +
89
- * // "$ myCli command argValue -p=someProject\n"
90
- * }],
91
- * handler: () => 'arg = ' + useRouteParams().params.arg
92
- * })
93
- * ```
94
- *
95
- * @param path command path
96
- * @param _options handler or options
97
- *
98
- * @returns
99
- */
100
- cli(path, _options) {
101
- var _a;
102
- const options = typeof _options === 'function' ? { handler: _options } : _options;
103
- const handler = typeof _options === 'function' ? _options : _options.handler;
104
- const makePath = (s) => '/' + s.replace(/\s+/g, '/');
105
- // register handler
106
- const targetPath = makePath(path);
107
- const routed = this.on('CLI', targetPath, handler);
108
- if (options.onRegister) {
109
- options.onRegister(targetPath, 0, routed);
110
- }
111
- // register direct aliases
112
- for (const alias of options.aliases || []) {
113
- const vars = routed.getArgs().map((k) => ':' + k).join('/');
114
- const targetPath = makePath(alias) + (vars ? '/' + vars : '');
115
- this.on('CLI', targetPath, handler);
116
- if (options.onRegister) {
117
- options.onRegister(targetPath, 1, routed);
118
- }
119
- }
120
- // register helpCli entry
121
- const command = routed.getStaticPart().replace(/\//g, ' ').trim();
122
- const args = Object.assign({}, (options.args || {}));
123
- for (const arg of routed.getArgs()) {
124
- if (!args[arg]) {
125
- args[arg] = '';
126
- }
127
- }
128
- this.cliHelp.addEntry({
129
- command,
130
- aliases: (_a = options.aliases) === null || _a === void 0 ? void 0 : _a.map(alias => alias.replace(/\\:/g, ':')),
131
- args,
132
- description: options.description,
133
- examples: options.examples,
134
- options: options.options,
135
- custom: { handler: options.handler, cb: options.onRegister },
136
- });
137
- return routed;
138
- }
139
- computeAliases() {
140
- if (!this.alreadyComputedAliases) {
141
- this.alreadyComputedAliases = true;
142
- const aliases = this.cliHelp.getComputedAliases();
143
- for (const [alias, entry] of Object.entries(aliases)) {
144
- if (entry.custom) {
145
- const vars = Object.keys(entry.args || {})
146
- .map((k) => ':' + k)
147
- .join('/');
148
- const path = '/' +
149
- alias.replace(/\s+/g, '/').replace(/:/g, '\\:') +
150
- (vars ? '/' + vars : '');
151
- this.on('CLI', path, entry.custom.handler);
152
- if (entry.custom.cb) {
153
- entry.custom.cb(path, 3);
154
- }
155
- }
156
- }
157
- }
158
- }
159
- /**
160
- * ## run
161
- * ### Start command processing
162
- * Triggers command processing
163
- *
164
- * By default takes `process.argv.slice(2)` as a command
165
- *
166
- * It's possible to replace the command by passing an argument
167
- *
168
- * @param _argv optionally overwrite `process.argv.slice(2)` with your `argv` array
169
- */
170
- run(_argv, _opts) {
171
- var _a, _b;
172
- return __awaiter(this, void 0, void 0, function* () {
173
- const argv = _argv || process.argv.slice(2);
174
- const parsedFlags = minimist(argv, _opts);
175
- const pathParams = parsedFlags._;
176
- const path = '/' +
177
- pathParams.map((v) => encodeURI(v).replace(/\//g, '%2F')).join('/');
178
- const { restoreCtx, clearCtx, store } = createCliContext({ opts: _opts, argv, pathParams, cliHelp: this.cliHelp, command: path.replace(/\//g, ' ').trim() }, this.mergeEventOptions((_a = this.opts) === null || _a === void 0 ? void 0 : _a.eventOptions));
179
- store('flags').value = parsedFlags;
180
- this.computeAliases();
181
- const { handlers: foundHandlers, firstStatic } = this.wooks.lookup('CLI', path);
182
- if (typeof firstStatic === 'string') {
183
- // overwriting command with firstStatic to properly search for help
184
- store('event').set('command', firstStatic.replace(/\//g, ' ').trim());
185
- }
186
- const handlers = foundHandlers ||
187
- (((_b = this.opts) === null || _b === void 0 ? void 0 : _b.onNotFound) && [this.opts.onNotFound]) ||
188
- null;
189
- if (handlers) {
190
- try {
191
- for (const handler of handlers) {
192
- restoreCtx();
193
- const response = yield handler();
194
- if (typeof response === 'string') {
195
- console.log(response);
196
- }
197
- else if (Array.isArray(response)) {
198
- response.forEach((r) => console.log(typeof r === 'string'
199
- ? r
200
- : JSON.stringify(r, null, ' ')));
201
- }
202
- else if (response instanceof Error) {
203
- this.onError(response);
204
- }
205
- else if (response) {
206
- if (response) {
207
- console.log(JSON.stringify(response, null, ' '));
208
- }
209
- }
210
- }
211
- }
212
- catch (e) {
213
- this.onError(e);
214
- }
215
- clearCtx();
216
- }
217
- else {
218
- this.onUnknownCommand(pathParams);
219
- clearCtx();
220
- }
221
- });
222
- }
223
- onError(e) {
224
- var _a;
225
- if ((_a = this.opts) === null || _a === void 0 ? void 0 : _a.onError) {
226
- this.opts.onError(e);
227
- }
228
- else {
229
- this.error(e.message);
230
- process.exit(1);
231
- }
232
- }
233
- /**
234
- * Triggers `unknown command` processing and callbacks
235
- * @param pathParams `string[]` containing command
236
- */
237
- onUnknownCommand(pathParams) {
238
- var _a;
239
- const raiseError = () => {
240
- this.error('' + 'Unknown command: ' + pathParams.join(' '));
241
- process.exit(1);
242
- };
243
- if ((_a = this.opts) === null || _a === void 0 ? void 0 : _a.onUnknownCommand) {
244
- this.opts.onUnknownCommand(pathParams, raiseError);
245
- }
246
- else {
247
- raiseError();
248
- }
249
- }
250
- error(e) {
251
- if (typeof e === 'string') {
252
- console.error('' + 'ERROR: ' + '' + e);
253
- }
254
- else {
255
- console.error('' + 'ERROR: ' + '' + e.message);
256
- }
257
- }
258
48
  }
259
- /**
260
- * Factory for WooksCli App
261
- * @param opts TWooksCliOptions
262
- * @param wooks Wooks | WooksAdapterBase
263
- * @returns WooksCli
264
- */
265
- function createCliApp(opts, wooks) {
266
- return new WooksCli(opts, wooks);
49
+
50
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
51
+ var e = new Error(message);
52
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
53
+ };
54
+
55
+ const cliShortcuts = {
56
+ cli: 'CLI',
57
+ };
58
+ class WooksCli extends wooks.WooksAdapterBase {
59
+ constructor(opts, wooks) {
60
+ super(wooks, opts === null || opts === void 0 ? void 0 : opts.logger, opts === null || opts === void 0 ? void 0 : opts.router);
61
+ this.opts = opts;
62
+ this.alreadyComputedAliases = false;
63
+ this.logger = (opts === null || opts === void 0 ? void 0 : opts.logger) || this.getLogger('wooks-cli');
64
+ this.cliHelp =
65
+ (opts === null || opts === void 0 ? void 0 : opts.cliHelp) instanceof cliHelp.CliHelpRenderer
66
+ ? opts.cliHelp
67
+ : new cliHelp.CliHelpRenderer(opts === null || opts === void 0 ? void 0 : opts.cliHelp);
68
+ }
69
+ /**
70
+ * ### Register CLI Command
71
+ * Command path segments may be separated by / or space.
72
+ *
73
+ * For example the folowing path are interpreted the same:
74
+ * - "command test use:dev :name"
75
+ * - "command/test/use:dev/:name"
76
+ *
77
+ * Where name will become an argument
78
+ *
79
+ * ```js
80
+ * // example without options
81
+ * app.cli('command/:arg', () => 'arg = ' + useRouteParams().params.arg )
82
+ *
83
+ * // example with options
84
+ * app.cli('command/:arg', {
85
+ * description: 'Description of the command',
86
+ * options: [{ keys: ['project', 'p'], description: 'Description of the option', value: 'myProject' }],
87
+ * args: { arg: 'Description of the arg' },
88
+ * aliases: ['cmd'], // alias "cmd/:arg" will be registered
89
+ * examples: [{
90
+ * description: 'Example of usage with someProject',
91
+ * cmd: 'argValue -p=someProject',
92
+ * // will result in help display:
93
+ * // "# Example of usage with someProject\n" +
94
+ * // "$ myCli command argValue -p=someProject\n"
95
+ * }],
96
+ * handler: () => 'arg = ' + useRouteParams().params.arg
97
+ * })
98
+ * ```
99
+ *
100
+ * @param path command path
101
+ * @param _options handler or options
102
+ *
103
+ * @returns
104
+ */
105
+ cli(path, _options) {
106
+ var _a;
107
+ const options = typeof _options === 'function' ? { handler: _options } : _options;
108
+ const handler = typeof _options === 'function' ? _options : _options.handler;
109
+ const makePath = (s) => '/' + s.replace(/\s+/g, '/');
110
+ // register handler
111
+ const targetPath = makePath(path);
112
+ const routed = this.on('CLI', targetPath, handler);
113
+ if (options.onRegister) {
114
+ options.onRegister(targetPath, 0, routed);
115
+ }
116
+ // register direct aliases
117
+ for (const alias of options.aliases || []) {
118
+ const vars = routed.getArgs().map((k) => ':' + k).join('/');
119
+ const targetPath = makePath(alias) + (vars ? '/' + vars : '');
120
+ this.on('CLI', targetPath, handler);
121
+ if (options.onRegister) {
122
+ options.onRegister(targetPath, 1, routed);
123
+ }
124
+ }
125
+ // register helpCli entry
126
+ const command = routed.getStaticPart().replace(/\//g, ' ').trim();
127
+ const args = Object.assign({}, (options.args || {}));
128
+ for (const arg of routed.getArgs()) {
129
+ if (!args[arg]) {
130
+ args[arg] = '';
131
+ }
132
+ }
133
+ this.cliHelp.addEntry({
134
+ command,
135
+ aliases: (_a = options.aliases) === null || _a === void 0 ? void 0 : _a.map(alias => alias.replace(/\\:/g, ':')), // unescape ":" character
136
+ args,
137
+ description: options.description,
138
+ examples: options.examples,
139
+ options: options.options,
140
+ custom: { handler: options.handler, cb: options.onRegister },
141
+ });
142
+ return routed;
143
+ }
144
+ computeAliases() {
145
+ if (!this.alreadyComputedAliases) {
146
+ this.alreadyComputedAliases = true;
147
+ const aliases = this.cliHelp.getComputedAliases();
148
+ for (const [alias, entry] of Object.entries(aliases)) {
149
+ if (entry.custom) {
150
+ const vars = Object.keys(entry.args || {})
151
+ .map((k) => ':' + k)
152
+ .join('/');
153
+ const path = '/' +
154
+ alias.replace(/\s+/g, '/').replace(/:/g, '\\:') +
155
+ (vars ? '/' + vars : '');
156
+ this.on('CLI', path, entry.custom.handler);
157
+ if (entry.custom.cb) {
158
+ entry.custom.cb(path, 3);
159
+ }
160
+ }
161
+ }
162
+ }
163
+ }
164
+ /**
165
+ * ## run
166
+ * ### Start command processing
167
+ * Triggers command processing
168
+ *
169
+ * By default takes `process.argv.slice(2)` as a command
170
+ *
171
+ * It's possible to replace the command by passing an argument
172
+ *
173
+ * @param _argv optionally overwrite `process.argv.slice(2)` with your `argv` array
174
+ */
175
+ run(_argv, _opts) {
176
+ var _a, _b;
177
+ return __awaiter(this, void 0, void 0, function* () {
178
+ const argv = _argv || process.argv.slice(2);
179
+ const parsedFlags = minimist(argv, _opts);
180
+ const pathParams = parsedFlags._;
181
+ const path = '/' +
182
+ pathParams.map((v) => encodeURI(v).replace(/\//g, '%2F')).join('/');
183
+ const { restoreCtx, clearCtx, store } = createCliContext({ opts: _opts, argv, pathParams, cliHelp: this.cliHelp, command: path.replace(/\//g, ' ').trim() }, this.mergeEventOptions((_a = this.opts) === null || _a === void 0 ? void 0 : _a.eventOptions));
184
+ store('flags').value = parsedFlags;
185
+ this.computeAliases();
186
+ const { handlers: foundHandlers, firstStatic } = this.wooks.lookup('CLI', path);
187
+ if (typeof firstStatic === 'string') {
188
+ // overwriting command with firstStatic to properly search for help
189
+ store('event').set('command', firstStatic.replace(/\//g, ' ').trim());
190
+ }
191
+ const handlers = foundHandlers ||
192
+ (((_b = this.opts) === null || _b === void 0 ? void 0 : _b.onNotFound) && [this.opts.onNotFound]) ||
193
+ null;
194
+ if (handlers) {
195
+ try {
196
+ for (const handler of handlers) {
197
+ restoreCtx();
198
+ const response = yield handler();
199
+ if (typeof response === 'string') {
200
+ console.log(response);
201
+ }
202
+ else if (Array.isArray(response)) {
203
+ response.forEach((r) => console.log(typeof r === 'string'
204
+ ? r
205
+ : JSON.stringify(r, null, ' ')));
206
+ }
207
+ else if (response instanceof Error) {
208
+ this.onError(response);
209
+ }
210
+ else if (response) {
211
+ if (response) {
212
+ console.log(JSON.stringify(response, null, ' '));
213
+ }
214
+ }
215
+ }
216
+ }
217
+ catch (e) {
218
+ this.onError(e);
219
+ }
220
+ clearCtx();
221
+ }
222
+ else {
223
+ this.onUnknownCommand(pathParams);
224
+ clearCtx();
225
+ }
226
+ });
227
+ }
228
+ onError(e) {
229
+ var _a;
230
+ if ((_a = this.opts) === null || _a === void 0 ? void 0 : _a.onError) {
231
+ this.opts.onError(e);
232
+ }
233
+ else {
234
+ this.error(e.message);
235
+ process.exit(1);
236
+ }
237
+ }
238
+ /**
239
+ * Triggers `unknown command` processing and callbacks
240
+ * @param pathParams `string[]` containing command
241
+ */
242
+ onUnknownCommand(pathParams) {
243
+ var _a;
244
+ const raiseError = () => {
245
+ this.error('' + 'Unknown command: ' + pathParams.join(' '));
246
+ process.exit(1);
247
+ };
248
+ if ((_a = this.opts) === null || _a === void 0 ? void 0 : _a.onUnknownCommand) {
249
+ this.opts.onUnknownCommand(pathParams, raiseError);
250
+ }
251
+ else {
252
+ raiseError();
253
+ }
254
+ }
255
+ error(e) {
256
+ if (typeof e === 'string') {
257
+ console.error('' + 'ERROR: ' + '' + e);
258
+ }
259
+ else {
260
+ console.error('' + 'ERROR: ' + '' + e.message);
261
+ }
262
+ }
263
+ }
264
+ /**
265
+ * Factory for WooksCli App
266
+ * @param opts TWooksCliOptions
267
+ * @param wooks Wooks | WooksAdapterBase
268
+ * @returns WooksCli
269
+ */
270
+ function createCliApp(opts, wooks) {
271
+ return new WooksCli(opts, wooks);
267
272
  }
268
273
 
269
- /**
270
- * ## useCliHelp
271
- * ### Composable
272
- * ```js
273
- * // example of printing cli instructions
274
- * const { print } = useCliHelp()
275
- * // print with colors
276
- * print(true)
277
- * // print with no colors
278
- * // print(false)
279
- * ```
280
- * @returns
281
- */
282
- function useCliHelp() {
283
- const event = useCliContext().store('event');
284
- const getCliHelp = () => event.get('cliHelp');
285
- const getEntry = () => { var _a; return (_a = getCliHelp().match(event.get('command'))) === null || _a === void 0 ? void 0 : _a.main; };
286
- return {
287
- getCliHelp,
288
- getEntry,
289
- render: (width, withColors) => getCliHelp().render(event.get('command'), width, withColors),
290
- print: (withColors) => getCliHelp().print(event.get('command'), withColors),
291
- };
292
- }
293
- /**
294
- * ## useAutoHelp
295
- * ### Composable
296
- *
297
- * Prints help if `--help` option provided.
298
- *
299
- * ```js
300
- * // example of use: print help and exit
301
- * app.cli('test', () => {
302
- * useAutoHelp() && process.exit(0)
303
- * return 'hit test command'
304
- * })
305
- *
306
- * // add option -h to print help, no colors
307
- * app.cli('test/nocolors', () => {
308
- * useAutoHelp(['help', 'h'], false) && process.exit(0)
309
- * return 'hit test nocolors command'
310
- * })
311
- * ```
312
- * @param keys default `['help']` - list of options to trigger help render
313
- * @param colors default `true`, prints with colors when true
314
- * @returns true when --help was provided. Otherwise returns false
315
- */
316
- function useAutoHelp(keys = ['help'], colors = true) {
317
- for (const option of keys) {
318
- if (useCliOption(option) === true) {
319
- // try {
320
- useCliHelp().print(colors);
321
- return true;
322
- // } catch (e) {
323
- // throw new
324
- // }
325
- }
326
- }
327
- }
328
- /**
329
- * ##useCommandLookupHelp
330
- * ### Composable
331
- *
332
- * Tries to find valid command based on provided command.
333
- *
334
- * If manages to find a valid command, throws an error
335
- * suggesting a list of valid commands
336
- *
337
- * Best to use in `onUnknownCommand` callback:
338
- *
339
- * ```js
340
- * const app = createCliApp({
341
- * onUnknownCommand: (path, raiseError) => {
342
- * // will throw an error suggesting a list
343
- * // of valid commands if could find some
344
- * useCommandLookupHelp()
345
- * // fallback to a regular error handler
346
- * raiseError()
347
- * },
348
- * })
349
- * ```
350
- *
351
- * @param lookupDepth depth of search in backwards
352
- * @example
353
- *
354
- * For provided command `run test:drive dir`
355
- * - lookup1: `run test:drive dir` (deep = 0)
356
- * - lookup2: `run test:drive` (deep = 1)
357
- * - lookup3: `run test` (deep = 2)
358
- * - lookup4: `run` (deep = 3)
359
- * ...
360
- */
361
- function useCommandLookupHelp(lookupDepth = 3) {
362
- const parts = useCliContext()
363
- .store('event')
364
- .get('pathParams')
365
- .map((p) => (p + ' ').split(':').map((s, i) => (i ? ':' + s : s)))
366
- .flat();
367
- const cliHelp = useCliHelp().getCliHelp();
368
- const cmd = cliHelp.getCliName();
369
- let data;
370
- for (let i = 0; i < Math.min(parts.length, lookupDepth + 1); i++) {
371
- const pathParams = parts
372
- .slice(0, i ? -i : parts.length)
373
- .join('')
374
- .trim();
375
- try {
376
- data = cliHelp.match(pathParams);
377
- break;
378
- }
379
- catch (e) {
380
- const variants = cliHelp.lookup(pathParams);
381
- if (variants.length) {
382
- throw new Error(`Wrong command, did you mean:\n${variants
383
- .slice(0, 7)
384
- .map((c) => ` $ ${cmd} ${c.main.command}`)
385
- .join('\n')}`);
386
- }
387
- }
388
- }
389
- if (data) {
390
- const { main, children } = data;
391
- if (main.args && Object.keys(main.args).length) {
392
- throw new Error(`Arguments expected: ${Object.keys(main.args)
393
- .map((l) => `<${l}>`)
394
- .join(', ')}`);
395
- }
396
- else if (children && children.length) {
397
- throw new Error(`Wrong command, did you mean:\n${children
398
- .slice(0, 7)
399
- .map((c) => ` $ ${cmd} ${c.command}`)
400
- .join('\n')}`);
401
- }
402
- }
274
+ /**
275
+ * ## useCliHelp
276
+ * ### Composable
277
+ * ```js
278
+ * // example of printing cli instructions
279
+ * const { print } = useCliHelp()
280
+ * // print with colors
281
+ * print(true)
282
+ * // print with no colors
283
+ * // print(false)
284
+ * ```
285
+ * @returns
286
+ */
287
+ function useCliHelp() {
288
+ const event = useCliContext().store('event');
289
+ const getCliHelp = () => event.get('cliHelp');
290
+ const getEntry = () => { var _a; return (_a = getCliHelp().match(event.get('command'))) === null || _a === void 0 ? void 0 : _a.main; };
291
+ return {
292
+ getCliHelp,
293
+ getEntry,
294
+ render: (width, withColors) => getCliHelp().render(event.get('command'), width, withColors),
295
+ print: (withColors) => getCliHelp().print(event.get('command'), withColors),
296
+ };
297
+ }
298
+ /**
299
+ * ## useAutoHelp
300
+ * ### Composable
301
+ *
302
+ * Prints help if `--help` option provided.
303
+ *
304
+ * ```js
305
+ * // example of use: print help and exit
306
+ * app.cli('test', () => {
307
+ * useAutoHelp() && process.exit(0)
308
+ * return 'hit test command'
309
+ * })
310
+ *
311
+ * // add option -h to print help, no colors
312
+ * app.cli('test/nocolors', () => {
313
+ * useAutoHelp(['help', 'h'], false) && process.exit(0)
314
+ * return 'hit test nocolors command'
315
+ * })
316
+ * ```
317
+ * @param keys default `['help']` - list of options to trigger help render
318
+ * @param colors default `true`, prints with colors when true
319
+ * @returns true when --help was provided. Otherwise returns false
320
+ */
321
+ function useAutoHelp(keys = ['help'], colors = true) {
322
+ for (const option of keys) {
323
+ if (useCliOption(option) === true) {
324
+ // try {
325
+ useCliHelp().print(colors);
326
+ return true;
327
+ // } catch (e) {
328
+ // throw new
329
+ // }
330
+ }
331
+ }
332
+ }
333
+ /**
334
+ * ##useCommandLookupHelp
335
+ * ### Composable
336
+ *
337
+ * Tries to find valid command based on provided command.
338
+ *
339
+ * If manages to find a valid command, throws an error
340
+ * suggesting a list of valid commands
341
+ *
342
+ * Best to use in `onUnknownCommand` callback:
343
+ *
344
+ * ```js
345
+ * const app = createCliApp({
346
+ * onUnknownCommand: (path, raiseError) => {
347
+ * // will throw an error suggesting a list
348
+ * // of valid commands if could find some
349
+ * useCommandLookupHelp()
350
+ * // fallback to a regular error handler
351
+ * raiseError()
352
+ * },
353
+ * })
354
+ * ```
355
+ *
356
+ * @param lookupDepth depth of search in backwards
357
+ * @example
358
+ *
359
+ * For provided command `run test:drive dir`
360
+ * - lookup1: `run test:drive dir` (deep = 0)
361
+ * - lookup2: `run test:drive` (deep = 1)
362
+ * - lookup3: `run test` (deep = 2)
363
+ * - lookup4: `run` (deep = 3)
364
+ * ...
365
+ */
366
+ function useCommandLookupHelp(lookupDepth = 3) {
367
+ const parts = useCliContext()
368
+ .store('event')
369
+ .get('pathParams')
370
+ .map((p) => (p + ' ').split(':').map((s, i) => (i ? ':' + s : s)))
371
+ .flat();
372
+ const cliHelp = useCliHelp().getCliHelp();
373
+ const cmd = cliHelp.getCliName();
374
+ let data;
375
+ for (let i = 0; i < Math.min(parts.length, lookupDepth + 1); i++) {
376
+ const pathParams = parts
377
+ .slice(0, i ? -i : parts.length)
378
+ .join('')
379
+ .trim();
380
+ try {
381
+ data = cliHelp.match(pathParams);
382
+ break;
383
+ }
384
+ catch (e) {
385
+ const variants = cliHelp.lookup(pathParams);
386
+ if (variants.length) {
387
+ throw new Error(`Wrong command, did you mean:\n${variants
388
+ .slice(0, 7)
389
+ .map((c) => ` $ ${cmd} ${c.main.command}`)
390
+ .join('\n')}`);
391
+ }
392
+ }
393
+ }
394
+ if (data) {
395
+ const { main, children } = data;
396
+ if (main.args && Object.keys(main.args).length) {
397
+ throw new Error(`Arguments expected: ${Object.keys(main.args)
398
+ .map((l) => `<${l}>`)
399
+ .join(', ')}`);
400
+ }
401
+ else if (children && children.length) {
402
+ throw new Error(`Wrong command, did you mean:\n${children
403
+ .slice(0, 7)
404
+ .map((c) => ` $ ${cmd} ${c.command}`)
405
+ .join('\n')}`);
406
+ }
407
+ }
403
408
  }
404
409
 
405
- /**
406
- * Get CLI Options
407
- *
408
- * @returns an object with CLI options
409
- */
410
- function useCliOptions() {
411
- const { store } = useCliContext();
412
- const flags = store('flags');
413
- if (!flags.value) {
414
- const event = store('event');
415
- flags.value = minimist(event.value.argv, event.get('opts'));
416
- }
417
- return flags.value;
418
- }
419
- /**
420
- * Getter for Cli Option value
421
- *
422
- * @param name name of the option
423
- * @returns value of a CLI option
424
- */
425
- function useCliOption(name) {
426
- var _a;
427
- try {
428
- const options = ((_a = useCliHelp().getEntry()) === null || _a === void 0 ? void 0 : _a.options) || [];
429
- const opt = options.find(o => o.keys.includes(name));
430
- if (opt) {
431
- for (const key of opt.keys) {
432
- if (useCliOptions()[key]) {
433
- return useCliOptions()[key];
434
- }
435
- }
436
- }
437
- }
438
- catch (e) {
439
- //
440
- }
441
- return useCliOptions()[name];
410
+ /**
411
+ * Get CLI Options
412
+ *
413
+ * @returns an object with CLI options
414
+ */
415
+ function useCliOptions() {
416
+ const { store } = useCliContext();
417
+ const flags = store('flags');
418
+ if (!flags.value) {
419
+ const event = store('event');
420
+ flags.value = minimist(event.value.argv, event.get('opts'));
421
+ }
422
+ return flags.value;
423
+ }
424
+ /**
425
+ * Getter for Cli Option value
426
+ *
427
+ * @param name name of the option
428
+ * @returns value of a CLI option
429
+ */
430
+ function useCliOption(name) {
431
+ var _a;
432
+ try {
433
+ const options = ((_a = useCliHelp().getEntry()) === null || _a === void 0 ? void 0 : _a.options) || [];
434
+ const opt = options.find(o => o.keys.includes(name));
435
+ if (opt) {
436
+ for (const key of opt.keys) {
437
+ if (useCliOptions()[key]) {
438
+ return useCliOptions()[key];
439
+ }
440
+ }
441
+ }
442
+ }
443
+ catch (e) {
444
+ //
445
+ }
446
+ return useCliOptions()[name];
442
447
  }
443
448
 
444
449
  exports.WooksCli = WooksCli;