@wooksjs/event-cli 0.4.10 → 0.4.12

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