@wooksjs/event-cli 0.5.20 → 0.6.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 wooksjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs CHANGED
@@ -1,279 +1,290 @@
1
- 'use strict';
1
+ "use strict";
2
+ //#region rolldown:runtime
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
2
23
 
3
- var cliHelp = require('@prostojs/cli-help');
4
- var minimist = require('minimist');
5
- var wooks = require('wooks');
6
- var eventCore = require('@wooksjs/event-core');
24
+ //#endregion
25
+ const __prostojs_cli_help = __toESM(require("@prostojs/cli-help"));
26
+ const minimist = __toESM(require("minimist"));
27
+ const wooks = __toESM(require("wooks"));
28
+ const __wooksjs_event_core = __toESM(require("@wooksjs/event-core"));
7
29
 
30
+ //#region packages/event-cli/src/event-cli.ts
8
31
  function createCliContext(data, options) {
9
- return eventCore.createAsyncEventContext({
10
- event: {
11
- ...data,
12
- type: 'CLI',
13
- },
14
- options,
15
- });
32
+ return (0, __wooksjs_event_core.createAsyncEventContext)({
33
+ event: {
34
+ ...data,
35
+ type: "CLI"
36
+ },
37
+ options
38
+ });
16
39
  }
17
40
  function useCliContext() {
18
- return eventCore.useAsyncEventContext('CLI');
41
+ return (0, __wooksjs_event_core.useAsyncEventContext)("CLI");
19
42
  }
20
43
 
21
- const cliShortcuts = {
22
- cli: 'CLI',
44
+ //#endregion
45
+ //#region packages/event-cli/src/cli-adapter.ts
46
+ const cliShortcuts = { cli: "CLI" };
47
+ var WooksCli = class extends wooks.WooksAdapterBase {
48
+ logger;
49
+ cliHelp;
50
+ constructor(opts, wooks$1) {
51
+ super(wooks$1, opts?.logger, opts?.router);
52
+ this.opts = opts;
53
+ this.logger = opts?.logger || this.getLogger(`${"\x1B[96m"}[wooks-cli]`);
54
+ this.cliHelp = opts?.cliHelp instanceof __prostojs_cli_help.CliHelpRenderer ? opts.cliHelp : new __prostojs_cli_help.CliHelpRenderer(opts?.cliHelp);
55
+ }
56
+ /**
57
+ * ### Register CLI Command
58
+ * Command path segments may be separated by / or space.
59
+ *
60
+ * For example the folowing path are interpreted the same:
61
+ * - "command test use:dev :name"
62
+ * - "command/test/use:dev/:name"
63
+ *
64
+ * Where name will become an argument
65
+ *
66
+ * ```js
67
+ * // example without options
68
+ * app.cli('command/:arg', () => 'arg = ' + useRouteParams().params.arg )
69
+ *
70
+ * // example with options
71
+ * app.cli('command/:arg', {
72
+ * description: 'Description of the command',
73
+ * options: [{ keys: ['project', 'p'], description: 'Description of the option', value: 'myProject' }],
74
+ * args: { arg: 'Description of the arg' },
75
+ * aliases: ['cmd'], // alias "cmd/:arg" will be registered
76
+ * examples: [{
77
+ * description: 'Example of usage with someProject',
78
+ * cmd: 'argValue -p=someProject',
79
+ * // will result in help display:
80
+ * // "# Example of usage with someProject\n" +
81
+ * // "$ myCli command argValue -p=someProject\n"
82
+ * }],
83
+ * handler: () => 'arg = ' + useRouteParams().params.arg
84
+ * })
85
+ * ```
86
+ *
87
+ * @param path command path
88
+ * @param _options handler or options
89
+ *
90
+ * @returns
91
+ */
92
+ cli(path, _options) {
93
+ const options = typeof _options === "function" ? { handler: _options } : _options;
94
+ const handler = typeof _options === "function" ? _options : _options.handler;
95
+ const makePath = (s) => `/${s.replace(/\s+/gu, "/")}`;
96
+ const targetPath = makePath(path);
97
+ const routed = this.on("CLI", targetPath, handler);
98
+ if (options.onRegister) options.onRegister(targetPath, 0, routed);
99
+ for (const alias of options.aliases || []) {
100
+ const vars = routed.getArgs().map((k) => `:${k}`).join("/");
101
+ const targetPath$1 = makePath(alias) + (vars ? `/${vars}` : "");
102
+ this.on("CLI", targetPath$1, handler);
103
+ if (options.onRegister) options.onRegister(targetPath$1, 1, routed);
104
+ }
105
+ const command = routed.getStaticPart().replace(/\//gu, " ").trim();
106
+ const args = { ...options.args };
107
+ for (const arg of routed.getArgs()) if (!args[arg]) args[arg] = "";
108
+ this.cliHelp.addEntry({
109
+ command,
110
+ aliases: options.aliases?.map((alias) => alias.replace(/\\:/gu, ":")),
111
+ args,
112
+ description: options.description,
113
+ examples: options.examples,
114
+ options: options.options,
115
+ custom: {
116
+ handler: options.handler,
117
+ cb: options.onRegister
118
+ }
119
+ });
120
+ return routed;
121
+ }
122
+ alreadyComputedAliases = false;
123
+ computeAliases() {
124
+ if (!this.alreadyComputedAliases) {
125
+ this.alreadyComputedAliases = true;
126
+ const aliases = this.cliHelp.getComputedAliases();
127
+ for (const [alias, entry] of Object.entries(aliases)) if (entry.custom) {
128
+ const vars = Object.keys(entry.args || {}).map((k) => `:${k}`).join("/");
129
+ const path = `/${alias.replace(/\s+/gu, "/").replace(/:/gu, "\\:")}${vars ? `/${vars}` : ""}`;
130
+ this.on("CLI", path, entry.custom.handler);
131
+ if (entry.custom.cb) entry.custom.cb(path, 3);
132
+ }
133
+ }
134
+ }
135
+ /**
136
+ * ## run
137
+ * ### Start command processing
138
+ * Triggers command processing
139
+ *
140
+ * By default takes `process.argv.slice(2)` as a command
141
+ *
142
+ * It's possible to replace the command by passing an argument
143
+ *
144
+ * @param _argv optionally overwrite `process.argv.slice(2)` with your `argv` array
145
+ */
146
+ async run(_argv, _opts) {
147
+ const argv = _argv || process.argv.slice(2);
148
+ const parsedFlags = (0, minimist.default)(argv, _opts);
149
+ const pathParams = parsedFlags._;
150
+ const path = `/${pathParams.map((v) => encodeURI(v).replace(/\//gu, "%2F")).join("/")}`;
151
+ const runInContext = createCliContext({
152
+ opts: _opts,
153
+ argv,
154
+ pathParams,
155
+ cliHelp: this.cliHelp,
156
+ command: path.replace(/\//gu, " ").trim()
157
+ }, this.mergeEventOptions(this.opts?.eventOptions));
158
+ return runInContext(async () => {
159
+ const { store } = useCliContext();
160
+ store("flags").value = parsedFlags;
161
+ this.computeAliases();
162
+ const { handlers: foundHandlers, firstStatic } = this.wooks.lookup("CLI", path);
163
+ if (typeof firstStatic === "string") store("event").set("command", firstStatic.replace(/\//gu, " ").trim());
164
+ const handlers = foundHandlers || this.opts?.onNotFound && [this.opts.onNotFound] || null;
165
+ if (handlers) try {
166
+ for (const handler of handlers) {
167
+ const response = await handler();
168
+ if (typeof response === "string") console.log(response);
169
+ else if (Array.isArray(response)) response.forEach((r) => {
170
+ console.log(typeof r === "string" ? r : JSON.stringify(r, null, " "));
171
+ });
172
+ else if (response instanceof Error) {
173
+ this.onError(response);
174
+ return response;
175
+ } else if (response) console.log(JSON.stringify(response, null, " "));
176
+ }
177
+ } catch (error) {
178
+ this.onError(error);
179
+ return error;
180
+ }
181
+ else {
182
+ this.onUnknownCommand(pathParams);
183
+ return new Error("Unknown command");
184
+ }
185
+ });
186
+ }
187
+ onError(e) {
188
+ if (this.opts?.onError) this.opts.onError(e);
189
+ else {
190
+ this.error(e.message);
191
+ process.exit(1);
192
+ }
193
+ }
194
+ /**
195
+ * Triggers `unknown command` processing and callbacks
196
+ * @param pathParams `string[]` containing command
197
+ */
198
+ onUnknownCommand(pathParams) {
199
+ const raiseError = () => {
200
+ this.error(`${"\x1B[0m"}Unknown command: ${pathParams.join(" ")}`);
201
+ process.exit(1);
202
+ };
203
+ if (this.opts?.onUnknownCommand) this.opts.onUnknownCommand(pathParams, raiseError);
204
+ else raiseError();
205
+ }
206
+ error(e) {
207
+ if (typeof e === "string") console.error(`${"\x1B[31m"}ERROR: ${"\x1B[0m"}${e}`);
208
+ else console.error(`${"\x1B[31m"}ERROR: ${"\x1B[0m"}${e.message}`);
209
+ }
23
210
  };
24
- class WooksCli extends wooks.WooksAdapterBase {
25
- constructor(opts, wooks) {
26
- super(wooks, opts?.logger, opts?.router);
27
- this.opts = opts;
28
- this.alreadyComputedAliases = false;
29
- this.logger = opts?.logger || this.getLogger(`${''}[wooks-cli]`);
30
- this.cliHelp =
31
- opts?.cliHelp instanceof cliHelp.CliHelpRenderer
32
- ? opts.cliHelp
33
- : new cliHelp.CliHelpRenderer(opts?.cliHelp);
34
- }
35
- cli(path, _options) {
36
- const options = typeof _options === 'function' ? { handler: _options } : _options;
37
- const handler = typeof _options === 'function' ? _options : _options.handler;
38
- const makePath = (s) => `/${s.replace(/\s+/g, '/')}`;
39
- const targetPath = makePath(path);
40
- const routed = this.on('CLI', targetPath, handler);
41
- if (options.onRegister) {
42
- options.onRegister(targetPath, 0, routed);
43
- }
44
- for (const alias of options.aliases || []) {
45
- const vars = routed
46
- .getArgs()
47
- .map(k => `:${k}`)
48
- .join('/');
49
- const targetPath = makePath(alias) + (vars ? `/${vars}` : '');
50
- this.on('CLI', targetPath, handler);
51
- if (options.onRegister) {
52
- options.onRegister(targetPath, 1, routed);
53
- }
54
- }
55
- const command = routed.getStaticPart().replace(/\//g, ' ').trim();
56
- const args = {
57
- ...options.args,
58
- };
59
- for (const arg of routed.getArgs()) {
60
- if (!args[arg]) {
61
- args[arg] = '';
62
- }
63
- }
64
- this.cliHelp.addEntry({
65
- command,
66
- aliases: options.aliases?.map(alias => alias.replace(/\\:/g, ':')),
67
- args,
68
- description: options.description,
69
- examples: options.examples,
70
- options: options.options,
71
- custom: { handler: options.handler, cb: options.onRegister },
72
- });
73
- return routed;
74
- }
75
- computeAliases() {
76
- if (!this.alreadyComputedAliases) {
77
- this.alreadyComputedAliases = true;
78
- const aliases = this.cliHelp.getComputedAliases();
79
- for (const [alias, entry] of Object.entries(aliases)) {
80
- if (entry.custom) {
81
- const vars = Object.keys(entry.args || {})
82
- .map(k => `:${k}`)
83
- .join('/');
84
- const path = `/${alias.replace(/\s+/g, '/').replace(/:/g, '\\:')}${vars ? `/${vars}` : ''}`;
85
- this.on('CLI', path, entry.custom.handler);
86
- if (entry.custom.cb) {
87
- entry.custom.cb(path, 3);
88
- }
89
- }
90
- }
91
- }
92
- }
93
- async run(_argv, _opts) {
94
- const argv = _argv || process.argv.slice(2);
95
- const parsedFlags = minimist(argv, _opts);
96
- const pathParams = parsedFlags._;
97
- const path = `/${pathParams.map(v => encodeURI(v).replace(/\//g, '%2F')).join('/')}`;
98
- const runInContext = createCliContext({
99
- opts: _opts,
100
- argv,
101
- pathParams,
102
- cliHelp: this.cliHelp,
103
- command: path.replace(/\//g, ' ').trim(),
104
- }, this.mergeEventOptions(this.opts?.eventOptions));
105
- return runInContext(async () => {
106
- const { store } = useCliContext();
107
- store('flags').value = parsedFlags;
108
- this.computeAliases();
109
- const { handlers: foundHandlers, firstStatic } = this.wooks.lookup('CLI', path);
110
- if (typeof firstStatic === 'string') {
111
- store('event').set('command', firstStatic.replace(/\//g, ' ').trim());
112
- }
113
- const handlers = foundHandlers || (this.opts?.onNotFound && [this.opts.onNotFound]) || null;
114
- if (handlers) {
115
- try {
116
- for (const handler of handlers) {
117
- const response = await handler();
118
- if (typeof response === 'string') {
119
- console.log(response);
120
- }
121
- else if (Array.isArray(response)) {
122
- response.forEach(r => {
123
- console.log(typeof r === 'string' ? r : JSON.stringify(r, null, ' '));
124
- });
125
- }
126
- else if (response instanceof Error) {
127
- this.onError(response);
128
- return response;
129
- }
130
- else if (response) {
131
- console.log(JSON.stringify(response, null, ' '));
132
- }
133
- }
134
- }
135
- catch (error) {
136
- this.onError(error);
137
- return error;
138
- }
139
- }
140
- else {
141
- this.onUnknownCommand(pathParams);
142
- return new Error('Unknown command');
143
- }
144
- });
145
- }
146
- onError(e) {
147
- if (this.opts?.onError) {
148
- this.opts.onError(e);
149
- }
150
- else {
151
- this.error(e.message);
152
- process.exit(1);
153
- }
154
- }
155
- onUnknownCommand(pathParams) {
156
- const raiseError = () => {
157
- this.error(`${''}Unknown command: ${pathParams.join(' ')}`);
158
- process.exit(1);
159
- };
160
- if (this.opts?.onUnknownCommand) {
161
- this.opts.onUnknownCommand(pathParams, raiseError);
162
- }
163
- else {
164
- raiseError();
165
- }
166
- }
167
- error(e) {
168
- if (typeof e === 'string') {
169
- console.error(`${''}ERROR: ${''}${e}`);
170
- }
171
- else {
172
- console.error(`${''}ERROR: ${''}${e.message}`);
173
- }
174
- }
175
- }
176
- function createCliApp(opts, wooks) {
177
- return new WooksCli(opts, wooks);
211
+ function createCliApp(opts, wooks$1) {
212
+ return new WooksCli(opts, wooks$1);
178
213
  }
179
214
 
215
+ //#endregion
216
+ //#region packages/event-cli/src/composables/options.ts
180
217
  function useCliOptions() {
181
- const { store } = useCliContext();
182
- const flags = store('flags');
183
- if (!flags.value) {
184
- const event = store('event');
185
- flags.value = minimist(event.get('argv'), event.get('opts'));
186
- }
187
- return flags.value;
218
+ const { store } = useCliContext();
219
+ const flags = store("flags");
220
+ if (!flags.value) {
221
+ const event = store("event");
222
+ flags.value = (0, minimist.default)(event.get("argv"), event.get("opts"));
223
+ }
224
+ return flags.value;
188
225
  }
189
226
  function useCliOption(name) {
190
- try {
191
- const options = useCliHelp().getEntry().options || [];
192
- const opt = options.find(o => o.keys.includes(name));
193
- if (opt) {
194
- for (const key of opt.keys) {
195
- if (useCliOptions()[key]) {
196
- return useCliOptions()[key];
197
- }
198
- }
199
- }
200
- }
201
- catch (error) {
202
- }
203
- return useCliOptions()[name];
227
+ try {
228
+ const options = useCliHelp().getEntry().options || [];
229
+ const opt = options.find((o) => o.keys.includes(name));
230
+ if (opt) {
231
+ for (const key of opt.keys) if (useCliOptions()[key]) return useCliOptions()[key];
232
+ }
233
+ } catch (error) {}
234
+ return useCliOptions()[name];
204
235
  }
205
236
 
237
+ //#endregion
238
+ //#region packages/event-cli/src/composables/cli-help.ts
206
239
  function useCliHelp() {
207
- const event = useCliContext().store('event');
208
- const getCliHelp = () => event.get('cliHelp');
209
- const getEntry = () => getCliHelp().match(event.get('command')).main;
210
- return {
211
- getCliHelp,
212
- getEntry,
213
- render: (width, withColors) => getCliHelp().render(event.get('command'), width, withColors),
214
- print: (withColors) => {
215
- getCliHelp().print(event.get('command'), withColors);
216
- },
217
- };
240
+ const event = useCliContext().store("event");
241
+ const getCliHelp = () => event.get("cliHelp");
242
+ const getEntry = () => getCliHelp().match(event.get("command")).main;
243
+ return {
244
+ getCliHelp,
245
+ getEntry,
246
+ render: (width, withColors) => getCliHelp().render(event.get("command"), width, withColors),
247
+ print: (withColors) => {
248
+ getCliHelp().print(event.get("command"), withColors);
249
+ }
250
+ };
218
251
  }
219
- function useAutoHelp(keys = ['help'], colors = true) {
220
- for (const option of keys) {
221
- if (useCliOption(option) === true) {
222
- useCliHelp().print(colors);
223
- return true;
224
- }
225
- }
252
+ function useAutoHelp(keys = ["help"], colors = true) {
253
+ for (const option of keys) if (useCliOption(option) === true) {
254
+ useCliHelp().print(colors);
255
+ return true;
256
+ }
226
257
  }
227
258
  function useCommandLookupHelp(lookupDepth = 3) {
228
- const parts = useCliContext()
229
- .store('event')
230
- .get('pathParams')
231
- ?.flatMap(p => `${p} `.split(':').map((s, i) => (i ? `:${s}` : s))) || [];
232
- const cliHelp = useCliHelp().getCliHelp();
233
- const cmd = cliHelp.getCliName();
234
- let data;
235
- for (let i = 0; i < Math.min(parts.length, lookupDepth + 1); i++) {
236
- const pathParams = parts
237
- .slice(0, i ? -i : parts.length)
238
- .join('')
239
- .trim();
240
- try {
241
- data = cliHelp.match(pathParams);
242
- break;
243
- }
244
- catch (error) {
245
- const variants = cliHelp.lookup(pathParams);
246
- if (variants.length > 0) {
247
- throw new Error(`Wrong command, did you mean:\n${variants
248
- .slice(0, 7)
249
- .map(c => ` $ ${cmd} ${c.main.command}`)
250
- .join('\n')}`);
251
- }
252
- }
253
- }
254
- if (data) {
255
- const { main, children } = data;
256
- if (main.args && Object.keys(main.args).length > 0) {
257
- throw new Error(`Arguments expected: ${Object.keys(main.args)
258
- .map(l => `<${l}>`)
259
- .join(', ')}`);
260
- }
261
- else if (children?.length > 0) {
262
- throw new Error(`Wrong command, did you mean:\n${children
263
- .slice(0, 7)
264
- .map(c => ` $ ${cmd} ${c.command}`)
265
- .join('\n')}`);
266
- }
267
- }
259
+ const parts = useCliContext().store("event").get("pathParams")?.flatMap((p) => `${p} `.split(":").map((s, i) => i ? `:${s}` : s)) || [];
260
+ const cliHelp = useCliHelp().getCliHelp();
261
+ const cmd = cliHelp.getCliName();
262
+ let data;
263
+ for (let i = 0; i < Math.min(parts.length, lookupDepth + 1); i++) {
264
+ const pathParams = parts.slice(0, i ? -i : parts.length).join("").trim();
265
+ try {
266
+ data = cliHelp.match(pathParams);
267
+ break;
268
+ } catch (error) {
269
+ const variants = cliHelp.lookup(pathParams);
270
+ if (variants.length > 0) throw new Error(`Wrong command, did you mean:\n${variants.slice(0, 7).map((c) => ` $ ${cmd} ${c.main.command}`).join("\n")}`);
271
+ }
272
+ }
273
+ if (data) {
274
+ const { main, children } = data;
275
+ if (main.args && Object.keys(main.args).length > 0) throw new Error(`Arguments expected: ${Object.keys(main.args).map((l) => `<${l}>`).join(", ")}`);
276
+ else if (children?.length > 0) throw new Error(`Wrong command, did you mean:\n${children.slice(0, 7).map((c) => ` $ ${cmd} ${c.command}`).join("\n")}`);
277
+ }
268
278
  }
269
279
 
270
- exports.WooksCli = WooksCli;
271
- exports.cliShortcuts = cliShortcuts;
272
- exports.createCliApp = createCliApp;
273
- exports.createCliContext = createCliContext;
274
- exports.useAutoHelp = useAutoHelp;
275
- exports.useCliContext = useCliContext;
276
- exports.useCliHelp = useCliHelp;
277
- exports.useCliOption = useCliOption;
278
- exports.useCliOptions = useCliOptions;
279
- exports.useCommandLookupHelp = useCommandLookupHelp;
280
+ //#endregion
281
+ exports.WooksCli = WooksCli
282
+ exports.cliShortcuts = cliShortcuts
283
+ exports.createCliApp = createCliApp
284
+ exports.createCliContext = createCliContext
285
+ exports.useAutoHelp = useAutoHelp
286
+ exports.useCliContext = useCliContext
287
+ exports.useCliHelp = useCliHelp
288
+ exports.useCliOption = useCliOption
289
+ exports.useCliOptions = useCliOptions
290
+ exports.useCommandLookupHelp = useCommandLookupHelp