@wooksjs/event-cli 0.4.26 → 0.4.27

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/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
 
12
12
  As a part of `wooks` event processing framework, `@wooksjs/event-cli` implements CLI events and provides composables that let you:
13
13
 
14
- - access flags (- or --)
14
+ - access flags (- or --)
15
15
 
16
16
  ## Installation
17
17
 
@@ -26,13 +26,13 @@ import { createCliApp, useCliOptions } from '@wooksjs/event-cli'
26
26
  const app = createCliApp()
27
27
 
28
28
  app.cli('test', () => {
29
- console.log('options:')
30
- return useCliOptions()
29
+ console.log('options:')
30
+ return useCliOptions()
31
31
  })
32
32
 
33
33
  app.cli(':arg', () => {
34
- console.log('run argument:', useRouteParams().params)
35
- return 'done'
34
+ console.log('run argument:', useRouteParams().params)
35
+ return 'done'
36
36
  })
37
37
 
38
38
  app.run()
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
- var eventCore = require('@wooksjs/event-core');
4
- var wooks = require('wooks');
5
3
  var cliHelp = require('@prostojs/cli-help');
6
4
  var minimist = require('minimist');
5
+ var wooks = require('wooks');
6
+ var eventCore = require('@wooksjs/event-core');
7
7
 
8
8
  function createCliContext(data, options) {
9
9
  return eventCore.createEventContext({
@@ -35,15 +35,18 @@ class WooksCli extends wooks.WooksAdapterBase {
35
35
  cli(path, _options) {
36
36
  const options = typeof _options === 'function' ? { handler: _options } : _options;
37
37
  const handler = typeof _options === 'function' ? _options : _options.handler;
38
- const makePath = (s) => '/' + s.replace(/\s+/g, '/');
38
+ const makePath = (s) => `/${s.replace(/\s+/g, '/')}`;
39
39
  const targetPath = makePath(path);
40
40
  const routed = this.on('CLI', targetPath, handler);
41
41
  if (options.onRegister) {
42
42
  options.onRegister(targetPath, 0, routed);
43
43
  }
44
44
  for (const alias of options.aliases || []) {
45
- const vars = routed.getArgs().map((k) => ':' + k).join('/');
46
- const targetPath = makePath(alias) + (vars ? '/' + vars : '');
45
+ const vars = routed
46
+ .getArgs()
47
+ .map(k => `:${k}`)
48
+ .join('/');
49
+ const targetPath = makePath(alias) + (vars ? `/${vars}` : '');
47
50
  this.on('CLI', targetPath, handler);
48
51
  if (options.onRegister) {
49
52
  options.onRegister(targetPath, 1, routed);
@@ -51,7 +54,7 @@ class WooksCli extends wooks.WooksAdapterBase {
51
54
  }
52
55
  const command = routed.getStaticPart().replace(/\//g, ' ').trim();
53
56
  const args = {
54
- ...(options.args || {}),
57
+ ...options.args,
55
58
  };
56
59
  for (const arg of routed.getArgs()) {
57
60
  if (!args[arg]) {
@@ -76,11 +79,9 @@ class WooksCli extends wooks.WooksAdapterBase {
76
79
  for (const [alias, entry] of Object.entries(aliases)) {
77
80
  if (entry.custom) {
78
81
  const vars = Object.keys(entry.args || {})
79
- .map((k) => ':' + k)
82
+ .map(k => `:${k}`)
80
83
  .join('/');
81
- const path = '/' +
82
- alias.replace(/\s+/g, '/').replace(/:/g, '\\:') +
83
- (vars ? '/' + vars : '');
84
+ const path = `/${alias.replace(/\s+/g, '/').replace(/:/g, '\\:')}${vars ? `/${vars}` : ''}`;
84
85
  this.on('CLI', path, entry.custom.handler);
85
86
  if (entry.custom.cb) {
86
87
  entry.custom.cb(path, 3);
@@ -93,18 +94,21 @@ class WooksCli extends wooks.WooksAdapterBase {
93
94
  const argv = _argv || process.argv.slice(2);
94
95
  const parsedFlags = minimist(argv, _opts);
95
96
  const pathParams = parsedFlags._;
96
- const path = '/' +
97
- pathParams.map((v) => encodeURI(v).replace(/\//g, '%2F')).join('/');
98
- const { restoreCtx, clearCtx, store } = createCliContext({ opts: _opts, argv, pathParams, cliHelp: this.cliHelp, command: path.replace(/\//g, ' ').trim() }, this.mergeEventOptions(this.opts?.eventOptions));
97
+ const path = `/${pathParams.map(v => encodeURI(v).replace(/\//g, '%2F')).join('/')}`;
98
+ const { restoreCtx, clearCtx, store } = createCliContext({
99
+ opts: _opts,
100
+ argv,
101
+ pathParams,
102
+ cliHelp: this.cliHelp,
103
+ command: path.replace(/\//g, ' ').trim(),
104
+ }, this.mergeEventOptions(this.opts?.eventOptions));
99
105
  store('flags').value = parsedFlags;
100
106
  this.computeAliases();
101
107
  const { handlers: foundHandlers, firstStatic } = this.wooks.lookup('CLI', path);
102
108
  if (typeof firstStatic === 'string') {
103
109
  store('event').set('command', firstStatic.replace(/\//g, ' ').trim());
104
110
  }
105
- const handlers = foundHandlers ||
106
- (this.opts?.onNotFound && [this.opts.onNotFound]) ||
107
- null;
111
+ const handlers = foundHandlers || (this.opts?.onNotFound && [this.opts.onNotFound]) || null;
108
112
  if (handlers) {
109
113
  try {
110
114
  for (const handler of handlers) {
@@ -114,22 +118,20 @@ class WooksCli extends wooks.WooksAdapterBase {
114
118
  console.log(response);
115
119
  }
116
120
  else if (Array.isArray(response)) {
117
- response.forEach((r) => console.log(typeof r === 'string'
118
- ? r
119
- : JSON.stringify(r, null, ' ')));
121
+ response.forEach(r => {
122
+ console.log(typeof r === 'string' ? r : JSON.stringify(r, null, ' '));
123
+ });
120
124
  }
121
125
  else if (response instanceof Error) {
122
126
  this.onError(response);
123
127
  }
124
128
  else if (response) {
125
- if (response) {
126
- console.log(JSON.stringify(response, null, ' '));
127
- }
129
+ console.log(JSON.stringify(response, null, ' '));
128
130
  }
129
131
  }
130
132
  }
131
- catch (e) {
132
- this.onError(e);
133
+ catch (error) {
134
+ this.onError(error);
133
135
  }
134
136
  clearCtx();
135
137
  }
@@ -149,7 +151,7 @@ class WooksCli extends wooks.WooksAdapterBase {
149
151
  }
150
152
  onUnknownCommand(pathParams) {
151
153
  const raiseError = () => {
152
- this.error('' + 'Unknown command: ' + pathParams.join(' '));
154
+ this.error(`${''}Unknown command: ${pathParams.join(' ')}`);
153
155
  process.exit(1);
154
156
  };
155
157
  if (this.opts?.onUnknownCommand) {
@@ -161,10 +163,10 @@ class WooksCli extends wooks.WooksAdapterBase {
161
163
  }
162
164
  error(e) {
163
165
  if (typeof e === 'string') {
164
- console.error('' + 'ERROR: ' + '' + e);
166
+ console.error(`${''}ERROR: ${''}${e}`);
165
167
  }
166
168
  else {
167
- console.error('' + 'ERROR: ' + '' + e.message);
169
+ console.error(`${''}ERROR: ${''}${e.message}`);
168
170
  }
169
171
  }
170
172
  }
@@ -172,15 +174,43 @@ function createCliApp(opts, wooks) {
172
174
  return new WooksCli(opts, wooks);
173
175
  }
174
176
 
177
+ function useCliOptions() {
178
+ const { store } = useCliContext();
179
+ const flags = store('flags');
180
+ if (!flags.value) {
181
+ const event = store('event');
182
+ flags.value = minimist(event.value?.argv, event.get('opts'));
183
+ }
184
+ return flags.value;
185
+ }
186
+ function useCliOption(name) {
187
+ try {
188
+ const options = useCliHelp().getEntry().options || [];
189
+ const opt = options.find(o => o.keys.includes(name));
190
+ if (opt) {
191
+ for (const key of opt.keys) {
192
+ if (useCliOptions()[key]) {
193
+ return useCliOptions()[key];
194
+ }
195
+ }
196
+ }
197
+ }
198
+ catch (error) {
199
+ }
200
+ return useCliOptions()[name];
201
+ }
202
+
175
203
  function useCliHelp() {
176
204
  const event = useCliContext().store('event');
177
205
  const getCliHelp = () => event.get('cliHelp');
178
- const getEntry = () => getCliHelp().match(event.get('command'))?.main;
206
+ const getEntry = () => getCliHelp().match(event.get('command')).main;
179
207
  return {
180
208
  getCliHelp,
181
209
  getEntry,
182
210
  render: (width, withColors) => getCliHelp().render(event.get('command'), width, withColors),
183
- print: (withColors) => getCliHelp().print(event.get('command'), withColors),
211
+ print: (withColors) => {
212
+ getCliHelp().print(event.get('command'), withColors);
213
+ },
184
214
  };
185
215
  }
186
216
  function useAutoHelp(keys = ['help'], colors = true) {
@@ -195,8 +225,7 @@ function useCommandLookupHelp(lookupDepth = 3) {
195
225
  const parts = useCliContext()
196
226
  .store('event')
197
227
  .get('pathParams')
198
- .map((p) => (p + ' ').split(':').map((s, i) => (i ? ':' + s : s)))
199
- .flat();
228
+ .flatMap(p => `${p} `.split(':').map((s, i) => (i ? `:${s}` : s)));
200
229
  const cliHelp = useCliHelp().getCliHelp();
201
230
  const cmd = cliHelp.getCliName();
202
231
  let data;
@@ -209,58 +238,32 @@ function useCommandLookupHelp(lookupDepth = 3) {
209
238
  data = cliHelp.match(pathParams);
210
239
  break;
211
240
  }
212
- catch (e) {
241
+ catch (error) {
213
242
  const variants = cliHelp.lookup(pathParams);
214
- if (variants.length) {
243
+ if (variants.length > 0) {
215
244
  throw new Error(`Wrong command, did you mean:\n${variants
216
245
  .slice(0, 7)
217
- .map((c) => ` $ ${cmd} ${c.main.command}`)
246
+ .map(c => ` $ ${cmd} ${c.main.command}`)
218
247
  .join('\n')}`);
219
248
  }
220
249
  }
221
250
  }
222
251
  if (data) {
223
252
  const { main, children } = data;
224
- if (main.args && Object.keys(main.args).length) {
253
+ if (main.args && Object.keys(main.args).length > 0) {
225
254
  throw new Error(`Arguments expected: ${Object.keys(main.args)
226
- .map((l) => `<${l}>`)
255
+ .map(l => `<${l}>`)
227
256
  .join(', ')}`);
228
257
  }
229
- else if (children && children.length) {
258
+ else if (children && children.length > 0) {
230
259
  throw new Error(`Wrong command, did you mean:\n${children
231
260
  .slice(0, 7)
232
- .map((c) => ` $ ${cmd} ${c.command}`)
261
+ .map(c => ` $ ${cmd} ${c.command}`)
233
262
  .join('\n')}`);
234
263
  }
235
264
  }
236
265
  }
237
266
 
238
- function useCliOptions() {
239
- const { store } = useCliContext();
240
- const flags = store('flags');
241
- if (!flags.value) {
242
- const event = store('event');
243
- flags.value = minimist(event.value.argv, event.get('opts'));
244
- }
245
- return flags.value;
246
- }
247
- function useCliOption(name) {
248
- try {
249
- const options = useCliHelp().getEntry()?.options || [];
250
- const opt = options.find(o => o.keys.includes(name));
251
- if (opt) {
252
- for (const key of opt.keys) {
253
- if (useCliOptions()[key]) {
254
- return useCliOptions()[key];
255
- }
256
- }
257
- }
258
- }
259
- catch (e) {
260
- }
261
- return useCliOptions()[name];
262
- }
263
-
264
267
  exports.WooksCli = WooksCli;
265
268
  exports.cliShortcuts = cliShortcuts;
266
269
  exports.createCliApp = createCliApp;
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
1
- import * as _wooksjs_event_core from '@wooksjs/event-core';
2
- import { TEventOptions, TEmpty } from '@wooksjs/event-core';
3
- import * as _prostojs_cli_help from '@prostojs/cli-help';
4
- import { CliHelpRenderer, TCliHelpOptions, TCliEntry } from '@prostojs/cli-help';
5
1
  import * as _prostojs_router from '@prostojs/router';
6
2
  import { TProstoRouterPathHandle } from '@prostojs/router';
7
- import { TWooksHandler, TWooksOptions, WooksAdapterBase, Wooks } from 'wooks';
8
- import minimist from 'minimist';
3
+ import * as _prostojs_cli_help from '@prostojs/cli-help';
4
+ import { CliHelpRenderer, TCliHelpOptions, TCliEntry } from '@prostojs/cli-help';
9
5
  import { TConsoleBase } from '@prostojs/logger';
6
+ import * as _wooksjs_event_core from '@wooksjs/event-core';
7
+ import { TEventOptions, TEmpty } from '@wooksjs/event-core';
8
+ import minimist from 'minimist';
9
+ import { TWooksHandler, TWooksOptions, WooksAdapterBase, Wooks } from 'wooks';
10
10
 
11
11
  interface TCliEventData {
12
12
  argv: string[];
@@ -17,11 +17,9 @@ interface TCliEventData {
17
17
  cliHelp: TCliHelpRenderer;
18
18
  }
19
19
  interface TCliContextStore {
20
- flags?: {
21
- [name: string]: boolean | string;
22
- };
20
+ flags?: Record<string, boolean | string>;
23
21
  }
24
- type TCliHelpCustom = {
22
+ interface TCliHelpCustom {
25
23
  handler: TWooksHandler<any>;
26
24
  /**
27
25
  * ### Callback for registered path
@@ -30,63 +28,15 @@ type TCliHelpCustom = {
30
28
  * @param aliasType 0 - direct command, 1 - direct alias, 2 - computed alias
31
29
  */
32
30
  cb?: <T>(path: string, aliasType: number, route?: TProstoRouterPathHandle<T>) => void;
33
- };
31
+ }
34
32
  type TCliHelpRenderer = CliHelpRenderer<TCliHelpCustom>;
35
33
 
36
- declare function createCliContext(data: Omit<TCliEventData, 'type'>, options: TEventOptions): {
37
- getCtx: () => TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>;
38
- restoreCtx: () => _wooksjs_event_core.TGenericContextStore<TEmpty>;
39
- clearCtx: () => null;
40
- store: <K extends "flags" | keyof _wooksjs_event_core.TGenericContextStore<TCliEventData>>(key: K) => {
41
- value: (TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K];
42
- hook: <K2 extends keyof Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2) => {
43
- value: Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K][K2];
44
- isDefined: boolean;
45
- };
46
- init: <K2_1 extends keyof Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_1, getter: () => Required<Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>[K2_1]) => Required<Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>[K2_1];
47
- set: <K2_2 extends keyof Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_2, v: Required<(TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K]>[K2_2]) => Required<(TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K]>[K2_2];
48
- get: <K2_3 extends keyof Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_3) => Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K][K2_3];
49
- has: <K2_4 extends keyof Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_4) => boolean;
50
- del: <K2_5 extends keyof Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_5) => void;
51
- entries: () => [string, unknown][];
52
- clear: () => void;
53
- };
54
- getStore: <K_1 extends "flags" | keyof _wooksjs_event_core.TGenericContextStore<TCliEventData>>(key: K_1) => (TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K_1];
55
- setStore: <K_2 extends "flags" | keyof _wooksjs_event_core.TGenericContextStore<TCliEventData>>(key: K_2, v: (TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K_2]) => void;
56
- };
57
- /**
58
- * Wrapper on top of useEventContext that provides
59
- * proper context types for CLI event
60
- * @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
61
- */
62
- declare function useCliContext<T extends TEmpty>(): {
63
- getCtx: () => TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>;
64
- restoreCtx: () => _wooksjs_event_core.TGenericContextStore<TEmpty>;
65
- clearCtx: () => null;
66
- store: <K extends "flags" | keyof _wooksjs_event_core.TGenericContextStore<TCliEventData> | keyof T>(key: K) => {
67
- value: (TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K];
68
- hook: <K2 extends keyof Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2) => {
69
- value: Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K][K2];
70
- isDefined: boolean;
71
- };
72
- init: <K2_1 extends keyof Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_1, getter: () => Required<Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>[K2_1]) => Required<Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>[K2_1];
73
- set: <K2_2 extends keyof Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_2, v: Required<(TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K]>[K2_2]) => Required<(TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K]>[K2_2];
74
- get: <K2_3 extends keyof Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_3) => Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K][K2_3];
75
- has: <K2_4 extends keyof Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_4) => boolean;
76
- del: <K2_5 extends keyof Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_5) => void;
77
- entries: () => [string, unknown][];
78
- clear: () => void;
79
- };
80
- getStore: <K_1 extends "flags" | keyof _wooksjs_event_core.TGenericContextStore<TCliEventData> | keyof T>(key: K_1) => (TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K_1];
81
- setStore: <K_2 extends "flags" | keyof _wooksjs_event_core.TGenericContextStore<TCliEventData> | keyof T>(key: K_2, v: (TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K_2]) => void;
82
- };
83
-
84
34
  declare const cliShortcuts: {
85
35
  cli: string;
86
36
  };
87
37
  interface TWooksCliOptions {
88
- onError?(e: Error): void;
89
- onNotFound?: TWooksHandler<unknown>;
38
+ onError?: (e: Error) => void;
39
+ onNotFound?: TWooksHandler;
90
40
  onUnknownCommand?: (params: string[], raiseError: () => void) => unknown;
91
41
  logger?: TConsoleBase;
92
42
  eventOptions?: TEventOptions;
@@ -169,22 +119,6 @@ declare class WooksCli extends WooksAdapterBase {
169
119
  */
170
120
  declare function createCliApp(opts?: TWooksCliOptions, wooks?: Wooks | WooksAdapterBase): WooksCli;
171
121
 
172
- /**
173
- * Get CLI Options
174
- *
175
- * @returns an object with CLI options
176
- */
177
- declare function useCliOptions(): {
178
- [name: string]: string | boolean;
179
- };
180
- /**
181
- * Getter for Cli Option value
182
- *
183
- * @param name name of the option
184
- * @returns value of a CLI option
185
- */
186
- declare function useCliOption(name: string): string | boolean;
187
-
188
122
  /**
189
123
  * ## useCliHelp
190
124
  * ### Composable
@@ -263,4 +197,66 @@ declare function useAutoHelp(keys?: string[], colors?: boolean): true | undefine
263
197
  */
264
198
  declare function useCommandLookupHelp(lookupDepth?: number): void;
265
199
 
200
+ /**
201
+ * Get CLI Options
202
+ *
203
+ * @returns an object with CLI options
204
+ */
205
+ declare function useCliOptions(): Record<string, string | boolean>;
206
+ /**
207
+ * Getter for Cli Option value
208
+ *
209
+ * @param name name of the option
210
+ * @returns value of a CLI option
211
+ */
212
+ declare function useCliOption(name: string): string | boolean;
213
+
214
+ declare function createCliContext(data: Omit<TCliEventData, 'type'>, options: TEventOptions): {
215
+ getCtx: () => TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>;
216
+ restoreCtx: () => _wooksjs_event_core.TGenericContextStore<TEmpty>;
217
+ clearCtx: () => null;
218
+ store: <K extends "flags" | keyof _wooksjs_event_core.TGenericContextStore<TCliEventData>>(key: K) => {
219
+ value: (TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K] | undefined;
220
+ hook: <K2 extends keyof Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2) => {
221
+ value: Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K][K2];
222
+ isDefined: boolean;
223
+ };
224
+ init: <K2_1 extends keyof Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_1, getter: () => Required<Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>[K2_1]) => Required<Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>[K2_1];
225
+ set: <K2_2 extends keyof Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_2, v: Required<(TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K]>[K2_2]) => Required<(TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K]>[K2_2];
226
+ get: <K2_3 extends keyof Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_3) => Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K][K2_3];
227
+ has: <K2_4 extends keyof Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_4) => boolean;
228
+ del: <K2_5 extends keyof Required<TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_5) => void;
229
+ entries: () => [string, unknown][];
230
+ clear: () => void;
231
+ };
232
+ getStore: <K_1 extends "flags" | keyof _wooksjs_event_core.TGenericContextStore<TCliEventData>>(key: K_1) => (TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K_1];
233
+ setStore: <K_2 extends "flags" | keyof _wooksjs_event_core.TGenericContextStore<TCliEventData>>(key: K_2, v: (TCliContextStore & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K_2]) => void;
234
+ };
235
+ /**
236
+ * Wrapper on top of useEventContext that provides
237
+ * proper context types for CLI event
238
+ * @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
239
+ */
240
+ declare function useCliContext<T extends TEmpty>(): {
241
+ getCtx: () => TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>;
242
+ restoreCtx: () => _wooksjs_event_core.TGenericContextStore<TEmpty>;
243
+ clearCtx: () => null;
244
+ store: <K extends "flags" | keyof _wooksjs_event_core.TGenericContextStore<TCliEventData> | keyof T>(key: K) => {
245
+ value: (TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K] | undefined;
246
+ hook: <K2 extends keyof Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2) => {
247
+ value: Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K][K2];
248
+ isDefined: boolean;
249
+ };
250
+ init: <K2_1 extends keyof Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_1, getter: () => Required<Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>[K2_1]) => Required<Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>[K2_1];
251
+ set: <K2_2 extends keyof Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_2, v: Required<(TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K]>[K2_2]) => Required<(TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K]>[K2_2];
252
+ get: <K2_3 extends keyof Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_3) => Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K][K2_3];
253
+ has: <K2_4 extends keyof Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_4) => boolean;
254
+ del: <K2_5 extends keyof Required<TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>>[K]>(key2: K2_5) => void;
255
+ entries: () => [string, unknown][];
256
+ clear: () => void;
257
+ };
258
+ getStore: <K_1 extends "flags" | keyof _wooksjs_event_core.TGenericContextStore<TCliEventData> | keyof T>(key: K_1) => (TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K_1];
259
+ setStore: <K_2 extends "flags" | keyof _wooksjs_event_core.TGenericContextStore<TCliEventData> | keyof T>(key: K_2, v: (TCliContextStore & T & _wooksjs_event_core.TGenericContextStore<TCliEventData>)[K_2]) => void;
260
+ };
261
+
266
262
  export { type TCliContextStore, type TCliEventData, type TCliHelpCustom, type TCliHelpRenderer, type TWooksCliEntry, type TWooksCliOptions, WooksCli, cliShortcuts, createCliApp, createCliContext, useAutoHelp, useCliContext, useCliHelp, useCliOption, useCliOptions, useCommandLookupHelp };
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { createEventContext, useEventContext } from '@wooksjs/event-core';
2
- import { WooksAdapterBase } from 'wooks';
3
1
  import { CliHelpRenderer } from '@prostojs/cli-help';
4
2
  import minimist from 'minimist';
3
+ import { WooksAdapterBase } from 'wooks';
4
+ import { createEventContext, useEventContext } from '@wooksjs/event-core';
5
5
 
6
6
  function createCliContext(data, options) {
7
7
  return createEventContext({
@@ -33,15 +33,18 @@ class WooksCli extends WooksAdapterBase {
33
33
  cli(path, _options) {
34
34
  const options = typeof _options === 'function' ? { handler: _options } : _options;
35
35
  const handler = typeof _options === 'function' ? _options : _options.handler;
36
- const makePath = (s) => '/' + s.replace(/\s+/g, '/');
36
+ const makePath = (s) => `/${s.replace(/\s+/g, '/')}`;
37
37
  const targetPath = makePath(path);
38
38
  const routed = this.on('CLI', targetPath, handler);
39
39
  if (options.onRegister) {
40
40
  options.onRegister(targetPath, 0, routed);
41
41
  }
42
42
  for (const alias of options.aliases || []) {
43
- const vars = routed.getArgs().map((k) => ':' + k).join('/');
44
- const targetPath = makePath(alias) + (vars ? '/' + vars : '');
43
+ const vars = routed
44
+ .getArgs()
45
+ .map(k => `:${k}`)
46
+ .join('/');
47
+ const targetPath = makePath(alias) + (vars ? `/${vars}` : '');
45
48
  this.on('CLI', targetPath, handler);
46
49
  if (options.onRegister) {
47
50
  options.onRegister(targetPath, 1, routed);
@@ -49,7 +52,7 @@ class WooksCli extends WooksAdapterBase {
49
52
  }
50
53
  const command = routed.getStaticPart().replace(/\//g, ' ').trim();
51
54
  const args = {
52
- ...(options.args || {}),
55
+ ...options.args,
53
56
  };
54
57
  for (const arg of routed.getArgs()) {
55
58
  if (!args[arg]) {
@@ -74,11 +77,9 @@ class WooksCli extends WooksAdapterBase {
74
77
  for (const [alias, entry] of Object.entries(aliases)) {
75
78
  if (entry.custom) {
76
79
  const vars = Object.keys(entry.args || {})
77
- .map((k) => ':' + k)
80
+ .map(k => `:${k}`)
78
81
  .join('/');
79
- const path = '/' +
80
- alias.replace(/\s+/g, '/').replace(/:/g, '\\:') +
81
- (vars ? '/' + vars : '');
82
+ const path = `/${alias.replace(/\s+/g, '/').replace(/:/g, '\\:')}${vars ? `/${vars}` : ''}`;
82
83
  this.on('CLI', path, entry.custom.handler);
83
84
  if (entry.custom.cb) {
84
85
  entry.custom.cb(path, 3);
@@ -91,18 +92,21 @@ class WooksCli extends WooksAdapterBase {
91
92
  const argv = _argv || process.argv.slice(2);
92
93
  const parsedFlags = minimist(argv, _opts);
93
94
  const pathParams = parsedFlags._;
94
- const path = '/' +
95
- pathParams.map((v) => encodeURI(v).replace(/\//g, '%2F')).join('/');
96
- const { restoreCtx, clearCtx, store } = createCliContext({ opts: _opts, argv, pathParams, cliHelp: this.cliHelp, command: path.replace(/\//g, ' ').trim() }, this.mergeEventOptions(this.opts?.eventOptions));
95
+ const path = `/${pathParams.map(v => encodeURI(v).replace(/\//g, '%2F')).join('/')}`;
96
+ const { restoreCtx, clearCtx, store } = createCliContext({
97
+ opts: _opts,
98
+ argv,
99
+ pathParams,
100
+ cliHelp: this.cliHelp,
101
+ command: path.replace(/\//g, ' ').trim(),
102
+ }, this.mergeEventOptions(this.opts?.eventOptions));
97
103
  store('flags').value = parsedFlags;
98
104
  this.computeAliases();
99
105
  const { handlers: foundHandlers, firstStatic } = this.wooks.lookup('CLI', path);
100
106
  if (typeof firstStatic === 'string') {
101
107
  store('event').set('command', firstStatic.replace(/\//g, ' ').trim());
102
108
  }
103
- const handlers = foundHandlers ||
104
- (this.opts?.onNotFound && [this.opts.onNotFound]) ||
105
- null;
109
+ const handlers = foundHandlers || (this.opts?.onNotFound && [this.opts.onNotFound]) || null;
106
110
  if (handlers) {
107
111
  try {
108
112
  for (const handler of handlers) {
@@ -112,22 +116,20 @@ class WooksCli extends WooksAdapterBase {
112
116
  console.log(response);
113
117
  }
114
118
  else if (Array.isArray(response)) {
115
- response.forEach((r) => console.log(typeof r === 'string'
116
- ? r
117
- : JSON.stringify(r, null, ' ')));
119
+ response.forEach(r => {
120
+ console.log(typeof r === 'string' ? r : JSON.stringify(r, null, ' '));
121
+ });
118
122
  }
119
123
  else if (response instanceof Error) {
120
124
  this.onError(response);
121
125
  }
122
126
  else if (response) {
123
- if (response) {
124
- console.log(JSON.stringify(response, null, ' '));
125
- }
127
+ console.log(JSON.stringify(response, null, ' '));
126
128
  }
127
129
  }
128
130
  }
129
- catch (e) {
130
- this.onError(e);
131
+ catch (error) {
132
+ this.onError(error);
131
133
  }
132
134
  clearCtx();
133
135
  }
@@ -147,7 +149,7 @@ class WooksCli extends WooksAdapterBase {
147
149
  }
148
150
  onUnknownCommand(pathParams) {
149
151
  const raiseError = () => {
150
- this.error('' + 'Unknown command: ' + pathParams.join(' '));
152
+ this.error(`${''}Unknown command: ${pathParams.join(' ')}`);
151
153
  process.exit(1);
152
154
  };
153
155
  if (this.opts?.onUnknownCommand) {
@@ -159,10 +161,10 @@ class WooksCli extends WooksAdapterBase {
159
161
  }
160
162
  error(e) {
161
163
  if (typeof e === 'string') {
162
- console.error('' + 'ERROR: ' + '' + e);
164
+ console.error(`${''}ERROR: ${''}${e}`);
163
165
  }
164
166
  else {
165
- console.error('' + 'ERROR: ' + '' + e.message);
167
+ console.error(`${''}ERROR: ${''}${e.message}`);
166
168
  }
167
169
  }
168
170
  }
@@ -170,15 +172,43 @@ function createCliApp(opts, wooks) {
170
172
  return new WooksCli(opts, wooks);
171
173
  }
172
174
 
175
+ function useCliOptions() {
176
+ const { store } = useCliContext();
177
+ const flags = store('flags');
178
+ if (!flags.value) {
179
+ const event = store('event');
180
+ flags.value = minimist(event.value?.argv, event.get('opts'));
181
+ }
182
+ return flags.value;
183
+ }
184
+ function useCliOption(name) {
185
+ try {
186
+ const options = useCliHelp().getEntry().options || [];
187
+ const opt = options.find(o => o.keys.includes(name));
188
+ if (opt) {
189
+ for (const key of opt.keys) {
190
+ if (useCliOptions()[key]) {
191
+ return useCliOptions()[key];
192
+ }
193
+ }
194
+ }
195
+ }
196
+ catch (error) {
197
+ }
198
+ return useCliOptions()[name];
199
+ }
200
+
173
201
  function useCliHelp() {
174
202
  const event = useCliContext().store('event');
175
203
  const getCliHelp = () => event.get('cliHelp');
176
- const getEntry = () => getCliHelp().match(event.get('command'))?.main;
204
+ const getEntry = () => getCliHelp().match(event.get('command')).main;
177
205
  return {
178
206
  getCliHelp,
179
207
  getEntry,
180
208
  render: (width, withColors) => getCliHelp().render(event.get('command'), width, withColors),
181
- print: (withColors) => getCliHelp().print(event.get('command'), withColors),
209
+ print: (withColors) => {
210
+ getCliHelp().print(event.get('command'), withColors);
211
+ },
182
212
  };
183
213
  }
184
214
  function useAutoHelp(keys = ['help'], colors = true) {
@@ -193,8 +223,7 @@ function useCommandLookupHelp(lookupDepth = 3) {
193
223
  const parts = useCliContext()
194
224
  .store('event')
195
225
  .get('pathParams')
196
- .map((p) => (p + ' ').split(':').map((s, i) => (i ? ':' + s : s)))
197
- .flat();
226
+ .flatMap(p => `${p} `.split(':').map((s, i) => (i ? `:${s}` : s)));
198
227
  const cliHelp = useCliHelp().getCliHelp();
199
228
  const cmd = cliHelp.getCliName();
200
229
  let data;
@@ -207,56 +236,30 @@ function useCommandLookupHelp(lookupDepth = 3) {
207
236
  data = cliHelp.match(pathParams);
208
237
  break;
209
238
  }
210
- catch (e) {
239
+ catch (error) {
211
240
  const variants = cliHelp.lookup(pathParams);
212
- if (variants.length) {
241
+ if (variants.length > 0) {
213
242
  throw new Error(`Wrong command, did you mean:\n${variants
214
243
  .slice(0, 7)
215
- .map((c) => ` $ ${cmd} ${c.main.command}`)
244
+ .map(c => ` $ ${cmd} ${c.main.command}`)
216
245
  .join('\n')}`);
217
246
  }
218
247
  }
219
248
  }
220
249
  if (data) {
221
250
  const { main, children } = data;
222
- if (main.args && Object.keys(main.args).length) {
251
+ if (main.args && Object.keys(main.args).length > 0) {
223
252
  throw new Error(`Arguments expected: ${Object.keys(main.args)
224
- .map((l) => `<${l}>`)
253
+ .map(l => `<${l}>`)
225
254
  .join(', ')}`);
226
255
  }
227
- else if (children && children.length) {
256
+ else if (children && children.length > 0) {
228
257
  throw new Error(`Wrong command, did you mean:\n${children
229
258
  .slice(0, 7)
230
- .map((c) => ` $ ${cmd} ${c.command}`)
259
+ .map(c => ` $ ${cmd} ${c.command}`)
231
260
  .join('\n')}`);
232
261
  }
233
262
  }
234
263
  }
235
264
 
236
- function useCliOptions() {
237
- const { store } = useCliContext();
238
- const flags = store('flags');
239
- if (!flags.value) {
240
- const event = store('event');
241
- flags.value = minimist(event.value.argv, event.get('opts'));
242
- }
243
- return flags.value;
244
- }
245
- function useCliOption(name) {
246
- try {
247
- const options = useCliHelp().getEntry()?.options || [];
248
- const opt = options.find(o => o.keys.includes(name));
249
- if (opt) {
250
- for (const key of opt.keys) {
251
- if (useCliOptions()[key]) {
252
- return useCliOptions()[key];
253
- }
254
- }
255
- }
256
- }
257
- catch (e) {
258
- }
259
- return useCliOptions()[name];
260
- }
261
-
262
265
  export { WooksCli, cliShortcuts, createCliApp, createCliContext, useAutoHelp, useCliContext, useCliHelp, useCliOption, useCliOptions, useCommandLookupHelp };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wooksjs/event-cli",
3
- "version": "0.4.26",
3
+ "version": "0.4.27",
4
4
  "description": "@wooksjs/event-cli",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",
@@ -39,8 +39,8 @@
39
39
  "url": "https://github.com/wooksjs/wooksjs/issues"
40
40
  },
41
41
  "peerDependencies": {
42
- "wooks": "0.4.26",
43
- "@wooksjs/event-core": "0.4.26"
42
+ "wooks": "0.4.27",
43
+ "@wooksjs/event-core": "0.4.27"
44
44
  },
45
45
  "dependencies": {
46
46
  "minimist": "^1.2.6",