@aomex/console 3.30.7 → 3.30.8-alpha.131cf1c.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/dist/index.js CHANGED
@@ -1,790 +1,782 @@
1
+ import { createRequire } from "node:module";
2
+ import { I18n, Middleware, compose, createI18n, ensureI18nLanguage, internalDestroyServices, middleware, toDocument, validate } from "@aomex/common";
3
+ import { stripVTControlCharacters, styleText } from "node:util";
4
+ import symbols from "log-symbols";
5
+ import ansi from "ansi-escapes";
6
+ import { createLogUpdate } from "log-update";
7
+ import isUnicodeSupported from "is-unicode-supported";
8
+ import EventEmitter from "node:events";
9
+ import { hideBin } from "yargs/helpers";
10
+ import parse from "yargs-parser";
11
+ import yargs from "yargs";
12
+ import { toArray } from "@aomex/internal-tools";
13
+ import { getFileValues, pathToFiles } from "@aomex/internal-file-import";
1
14
  // src/utils/meta.ts
2
- var version = "3.30.7";
3
- var scriptName = "aomex";
4
-
15
+ const version = "3.30.8-alpha.131cf1c.0";
16
+ const scriptName = "aomex";
5
17
  // src/override/console-middleware.ts
6
- import { Middleware } from "@aomex/common";
7
18
  var ConsoleMiddleware = class extends Middleware {
8
- helpInjector;
9
- constructor(args) {
10
- const { fn, help = {} } = typeof args === "function" ? { fn: args } : args;
11
- super(fn);
12
- this.helpInjector = help;
13
- }
14
- help() {
15
- return this.helpInjector;
16
- }
19
+ helpInjector;
20
+ constructor(args) {
21
+ const { fn, help = {} } = typeof args === "function" ? { fn: args } : args;
22
+ super(fn);
23
+ this.helpInjector = help;
24
+ }
25
+ help() {
26
+ return this.helpInjector;
27
+ }
17
28
  };
18
29
  Middleware.register("console", ConsoleMiddleware);
19
-
20
30
  // src/utils/collect-console-document.ts
21
- var collectConsoleDocument = async (data) => {
22
- const { document, middlewareList, app } = data;
23
- const hooks = {};
24
- const onDocumentLoop = async (middlewareList2) => {
25
- const injectors = middlewareList2.map((middleware7) => {
26
- return middleware7 instanceof ConsoleMiddleware ? middleware7["help"]() : {};
27
- });
28
- await Promise.all(
29
- injectors.map((injector) => {
30
- return injector.onDocument?.(document, {
31
- app,
32
- children: onDocumentLoop,
33
- collectCommand(commandName, middlewareList3) {
34
- hooks[commandName] = middlewareList3;
35
- }
36
- });
37
- })
38
- );
39
- };
40
- await onDocumentLoop(middlewareList);
41
- const onDocumentItemLoop = async (commandName, middlewareList2) => {
42
- if (!commandName || !document[commandName]) return;
43
- const injectors = middlewareList2.map((middleware7) => {
44
- return middleware7 instanceof ConsoleMiddleware ? middleware7["help"]() : {};
45
- });
46
- await Promise.all(
47
- injectors.map((injector) => {
48
- return injector.onCommandItem?.(document[commandName], {
49
- commandName,
50
- doc: document,
51
- app,
52
- children: onDocumentItemLoop.bind(null, commandName)
53
- });
54
- })
55
- );
56
- };
57
- await Promise.all(
58
- Object.entries(hooks).map(([commandName, middlewareList2]) => {
59
- return onDocumentItemLoop(commandName, middlewareList2);
60
- })
61
- );
62
- const postDocumentItemLoop = async (commandName, middlewareList2) => {
63
- if (!commandName || !document[commandName]) return;
64
- const injectors = [...middlewareList2].reverse().map((middleware7) => {
65
- return middleware7 instanceof ConsoleMiddleware ? middleware7["help"]() : {};
66
- });
67
- await Promise.all(
68
- injectors.map((injector) => {
69
- return injector.postCommandItem?.(document[commandName], {
70
- commandName,
71
- doc: document,
72
- app,
73
- children: postDocumentItemLoop.bind(null, commandName)
74
- });
75
- })
76
- );
77
- };
78
- await Promise.all(
79
- Object.entries(hooks).map(([commandName, middlewareList2]) => {
80
- return postDocumentItemLoop(commandName, middlewareList2);
81
- })
82
- );
83
- const postDocumentLoop = async (middlewareList2) => {
84
- const injectors = [...middlewareList2].reverse().map((middleware7) => {
85
- return middleware7 instanceof ConsoleMiddleware ? middleware7["help"]() : {};
86
- });
87
- await Promise.all(
88
- injectors.map((injector) => {
89
- return injector.postDocument?.(document, { app, children: postDocumentLoop });
90
- })
91
- );
92
- };
93
- await postDocumentLoop(middlewareList);
94
- return document;
31
+ const collectConsoleDocument = async (data) => {
32
+ const { document, middlewareList, app } = data;
33
+ const hooks = {};
34
+ const onDocumentLoop = async (middlewareList) => {
35
+ const injectors = middlewareList.map((middleware) => {
36
+ return middleware instanceof ConsoleMiddleware ? middleware["help"]() : {};
37
+ });
38
+ await Promise.all(injectors.map((injector) => {
39
+ return injector.onDocument?.(document, {
40
+ app,
41
+ children: onDocumentLoop,
42
+ collectCommand(commandName, middlewareList) {
43
+ hooks[commandName] = middlewareList;
44
+ }
45
+ });
46
+ }));
47
+ };
48
+ await onDocumentLoop(middlewareList);
49
+ const onDocumentItemLoop = async (commandName, middlewareList) => {
50
+ if (!commandName || !document[commandName]) return;
51
+ const injectors = middlewareList.map((middleware) => {
52
+ return middleware instanceof ConsoleMiddleware ? middleware["help"]() : {};
53
+ });
54
+ await Promise.all(injectors.map((injector) => {
55
+ return injector.onCommandItem?.(document[commandName], {
56
+ commandName,
57
+ doc: document,
58
+ app,
59
+ children: onDocumentItemLoop.bind(null, commandName)
60
+ });
61
+ }));
62
+ };
63
+ await Promise.all(Object.entries(hooks).map(([commandName, middlewareList]) => {
64
+ return onDocumentItemLoop(commandName, middlewareList);
65
+ }));
66
+ const postDocumentItemLoop = async (commandName, middlewareList) => {
67
+ if (!commandName || !document[commandName]) return;
68
+ const injectors = [...middlewareList].reverse().map((middleware) => {
69
+ return middleware instanceof ConsoleMiddleware ? middleware["help"]() : {};
70
+ });
71
+ await Promise.all(injectors.map((injector) => {
72
+ return injector.postCommandItem?.(document[commandName], {
73
+ commandName,
74
+ doc: document,
75
+ app,
76
+ children: postDocumentItemLoop.bind(null, commandName)
77
+ });
78
+ }));
79
+ };
80
+ await Promise.all(Object.entries(hooks).map(([commandName, middlewareList]) => {
81
+ return postDocumentItemLoop(commandName, middlewareList);
82
+ }));
83
+ const postDocumentLoop = async (middlewareList) => {
84
+ const injectors = [...middlewareList].reverse().map((middleware) => {
85
+ return middleware instanceof ConsoleMiddleware ? middleware["help"]() : {};
86
+ });
87
+ await Promise.all(injectors.map((injector) => {
88
+ return injector.postDocument?.(document, {
89
+ app,
90
+ children: postDocumentLoop
91
+ });
92
+ }));
93
+ };
94
+ await postDocumentLoop(middlewareList);
95
+ return document;
95
96
  };
96
-
97
97
  // src/utils/terminal.ts
98
- import { styleText } from "util";
99
- import symbols from "log-symbols";
100
- import ansi from "ansi-escapes";
101
- import { createLogUpdate } from "log-update";
102
- import isUnicodeSupported from "is-unicode-supported";
103
- import { stripVTControlCharacters } from "util";
104
- import { createRequire } from "module";
105
- var requireCJS = createRequire(import.meta.url);
98
+ const requireCJS = createRequire(import.meta.url);
99
+ /**
100
+ * 终端输出实用函数
101
+ */
106
102
  var Terminal = class {
107
- /**
108
- * 打印文字,同`console.log`
109
- */
110
- print(...messages) {
111
- console.log(...messages);
112
- }
113
- /**
114
- * 打印黄色警告信息,开头显示小图标 ⚠
115
- */
116
- printWarning(...messages) {
117
- console.warn(
118
- symbols.warning,
119
- ...messages.map((message) => this.style("yellow", String(message)))
120
- );
121
- }
122
- /**
123
- * 打印红色错误信息,开头显示小图标 ✖️
124
- */
125
- printError(...messages) {
126
- console.error(
127
- symbols.error,
128
- ...messages.map((message) => this.style("red", String(message)))
129
- );
130
- }
131
- /**
132
- * 打印绿色成功信息,开头显示小图标 ✔
133
- */
134
- printSuccess(...messages) {
135
- console.log(
136
- symbols.success,
137
- ...messages.map((message) => this.style("green", String(message)))
138
- );
139
- }
140
- /**
141
- * 打印二维数组,呈现形式为表格
142
- * ```typescript
143
- * terminal.table([
144
- * ['编号', '姓名', '性别'],
145
- * [1, '张三', '男'],
146
- * [2, '李四', '男'],
147
- * [3, '翠花', '女'],
148
- * ]);
149
- * ```
150
- * @link https://www.npmjs.com/package/table
151
- */
152
- printTable(data, config) {
153
- this.print(this.generateTable(data, config));
154
- }
155
- /**
156
- * 使用二维数组生成表格字符串
157
- * ```typescript
158
- * const table = terminal.generateTable([
159
- * ['编号', '姓名', '性别'],
160
- * [1, '张三', '男'],
161
- * [2, '李四', '男'],
162
- * [3, '翠花', '女'],
163
- * ]);
164
- * ```
165
- * @link https://www.npmjs.com/package/table
166
- */
167
- generateTable(data, config) {
168
- const { table } = requireCJS("table");
169
- return table(data, config).replace(/\n$/, "");
170
- }
171
- /**
172
- * 清除终端屏幕文字,鼠标移到第一行开头
173
- */
174
- clearScreen() {
175
- process.stdout.write(ansi.clearScreen);
176
- }
177
- /**
178
- * 持续刷新终端文字。
179
- *
180
- * 文字可包含一些内置的占位符:
181
- * - `%loading%` 加载动画
182
- * - `%prepare%` 灰色准备小图标 ◼
183
- * - `%success%` 绿色成功小图标 ✔
184
- * - `%info%` 蓝色信息小图标 ℹ
185
- * - `%warning%` 黄色警告小图标 ⚠
186
- * - `%error%` 红色错误小图标 ✖️
187
- * - `%skip%` 灰色跳过小图标 ↓
188
- *
189
- * ```typescript
190
- * const session = terminal.applySession();
191
- *
192
- * session.update('%loading% 加载中\n 猜猜我是谁');
193
- * await sleep(1000);
194
- * session.update('%success% 成功\n 猜中了');
195
- * session.commit();
196
- * ```
197
- */
198
- createSession() {
199
- const supportUnicode = isUnicodeSupported();
200
- const logSession = createLogUpdate(process.stdout);
201
- const loadingFrames = supportUnicode ? ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"] : ["-", "\\", "|", "/"];
202
- const skipSymbol = this.style("gray", supportUnicode ? "\u2193" : "-");
203
- const prepareSymbol = this.style(["gray", "dim"], supportUnicode ? "\u25FC" : ".");
204
- let loadingFrameIndex = 0;
205
- let cacheText = "";
206
- let timer;
207
- const replaceText = () => {
208
- return cacheText.replaceAll("%loading%", loadingFrames[loadingFrameIndex]);
209
- };
210
- const reset = () => {
211
- clearInterval(timer);
212
- timer = void 0;
213
- loadingFrameIndex = 0;
214
- };
215
- let prevText = "";
216
- return {
217
- /**
218
- * 替换当前输出的文字
219
- */
220
- update: (text) => {
221
- if (prevText === text) return;
222
- prevText = text;
223
- cacheText = text.replaceAll("%success%", symbols.success).replaceAll("%error%", symbols.error).replaceAll("%warning%", symbols.warning).replaceAll("%info%", symbols.info).replaceAll("%skip%", skipSymbol).replaceAll("%prepare%", prepareSymbol);
224
- logSession(replaceText());
225
- if (text.includes("%loading%")) {
226
- timer ||= setInterval(() => {
227
- loadingFrameIndex += 1;
228
- if (loadingFrameIndex === loadingFrames.length) {
229
- loadingFrameIndex = 0;
230
- }
231
- logSession(replaceText());
232
- }, 80);
233
- } else {
234
- reset();
235
- }
236
- },
237
- /**
238
- * 持久化已经输出的文字,进入下一个session
239
- */
240
- commit: () => {
241
- reset();
242
- logSession.done();
243
- }
244
- };
245
- }
246
- async runTasks(_tasks, opts = {}) {
247
- const { concurrent = false } = opts;
248
- const log = this.createSession();
249
- const tasks = _tasks.map((task) => {
250
- return { ...task, suffix: "", status: "prepare" };
251
- });
252
- const reRender = () => {
253
- log.update(
254
- tasks.map((task) => {
255
- const suffix = task.status === "skip" ? this.style("gray", `[skipped]`) : task.suffix;
256
- return `%${task.status}% ${task.title}${suffix ? " " + suffix : ""}`;
257
- }).join("\n")
258
- );
259
- };
260
- reRender();
261
- const timer = setInterval(reRender, 16);
262
- const handleTask = async (ctx, task) => {
263
- const skipped = typeof task.skip === "function" ? await task.skip(ctx) : task.skip === true;
264
- if (skipped) {
265
- task.status = "skip";
266
- return { error: null };
267
- }
268
- try {
269
- task.status = "loading";
270
- let statusChanged = false;
271
- await task.task(ctx, {
272
- get status() {
273
- return task.status;
274
- },
275
- set status(status) {
276
- task.status = status;
277
- statusChanged = true;
278
- },
279
- get title() {
280
- return task.title;
281
- },
282
- set title(t) {
283
- task.title = t;
284
- },
285
- get suffix() {
286
- return task.suffix;
287
- },
288
- set suffix(s) {
289
- task.suffix = s;
290
- }
291
- });
292
- if (!statusChanged) {
293
- task.status = "success";
294
- }
295
- } catch (e) {
296
- task.status = "error";
297
- task.suffix = this.style("red", e.message);
298
- return { error: e };
299
- }
300
- return { error: null };
301
- };
302
- try {
303
- const ctx = {};
304
- if (concurrent) {
305
- const result = await Promise.allSettled(
306
- tasks.map((task) => handleTask(ctx, task))
307
- );
308
- const errors = [];
309
- for (const item of result) {
310
- if (item.status === "fulfilled" && item.value.error !== null) {
311
- errors.push(item.value.error);
312
- }
313
- }
314
- if (errors.length) return { errors, context: ctx };
315
- } else {
316
- for (const task of tasks) {
317
- const { error } = await handleTask(ctx, task);
318
- if (error) return { error, context: ctx };
319
- }
320
- }
321
- return { context: ctx, error: null };
322
- } finally {
323
- clearInterval(timer);
324
- reRender();
325
- log.commit();
326
- }
327
- }
328
- /**
329
- * 为字符串设置样式:
330
- * - 文字颜色、背景色
331
- * - 粗体、斜体
332
- * - 下划线、删除线、上划线、双下划线
333
- *
334
- * ```typescript
335
- * const errorMsg = terminal.style('red', '一些错误的内容');
336
- * const warnMsg = terminal.style(['yellow', 'bold'], '严重警告文字');
337
- * ```
338
- */
339
- style(color, string) {
340
- return styleText(color, string);
341
- }
342
- /**
343
- * 去除ansi字符
344
- * ```typescript
345
- * terminal.stripStyle('\u001B[4mUnicorn\u001B[0m'); // Unicorn
346
- * ```
347
- */
348
- stripStyle(string) {
349
- return stripVTControlCharacters(string);
350
- }
103
+ /**
104
+ * 打印文字,同`console.log`
105
+ */
106
+ print(...messages) {
107
+ console.log(...messages);
108
+ }
109
+ /**
110
+ * 打印黄色警告信息,开头显示小图标 ⚠
111
+ */
112
+ printWarning(...messages) {
113
+ console.warn(symbols.warning, ...messages.map((message) => this.style("yellow", String(message))));
114
+ }
115
+ /**
116
+ * 打印红色错误信息,开头显示小图标 ✖️
117
+ */
118
+ printError(...messages) {
119
+ console.error(symbols.error, ...messages.map((message) => this.style("red", String(message))));
120
+ }
121
+ /**
122
+ * 打印绿色成功信息,开头显示小图标 ✔
123
+ */
124
+ printSuccess(...messages) {
125
+ console.log(symbols.success, ...messages.map((message) => this.style("green", String(message))));
126
+ }
127
+ /**
128
+ * 打印二维数组,呈现形式为表格
129
+ * ```typescript
130
+ * terminal.table([
131
+ * ['编号', '姓名', '性别'],
132
+ * [1, '张三', '男'],
133
+ * [2, '李四', '男'],
134
+ * [3, '翠花', '女'],
135
+ * ]);
136
+ * ```
137
+ * @link https://www.npmjs.com/package/table
138
+ */
139
+ printTable(data, config) {
140
+ this.print(this.generateTable(data, config));
141
+ }
142
+ /**
143
+ * 使用二维数组生成表格字符串
144
+ * ```typescript
145
+ * const table = terminal.generateTable([
146
+ * ['编号', '姓名', '性别'],
147
+ * [1, '张三', '男'],
148
+ * [2, '李四', '男'],
149
+ * [3, '翠花', '女'],
150
+ * ]);
151
+ * ```
152
+ * @link https://www.npmjs.com/package/table
153
+ */
154
+ generateTable(data, config) {
155
+ const { table } = requireCJS("table");
156
+ return table(data, config).replace(/\n$/, "");
157
+ }
158
+ /**
159
+ * 清除终端屏幕文字,鼠标移到第一行开头
160
+ */
161
+ clearScreen() {
162
+ process.stdout.write(ansi.clearScreen);
163
+ }
164
+ /**
165
+ * 持续刷新终端文字。
166
+ *
167
+ * 文字可包含一些内置的占位符:
168
+ * - `%loading%` 加载动画
169
+ * - `%prepare%` 灰色准备小图标 ◼
170
+ * - `%success%` 绿色成功小图标 ✔
171
+ * - `%info%` 蓝色信息小图标 ℹ
172
+ * - `%warning%` 黄色警告小图标 ⚠
173
+ * - `%error%` 红色错误小图标 ✖️
174
+ * - `%skip%` 灰色跳过小图标 ↓
175
+ *
176
+ * ```typescript
177
+ * const session = terminal.applySession();
178
+ *
179
+ * session.update('%loading% 加载中\n 猜猜我是谁');
180
+ * await sleep(1000);
181
+ * session.update('%success% 成功\n 猜中了');
182
+ * session.commit();
183
+ * ```
184
+ */
185
+ createSession() {
186
+ const supportUnicode = isUnicodeSupported();
187
+ const logSession = createLogUpdate(process.stdout);
188
+ const loadingFrames = supportUnicode ? [
189
+ "⠋",
190
+ "⠙",
191
+ "⠹",
192
+ "⠸",
193
+ "⠼",
194
+ "⠴",
195
+ "⠦",
196
+ "⠧",
197
+ "⠇",
198
+ "⠏"
199
+ ] : [
200
+ "-",
201
+ "\\",
202
+ "|",
203
+ "/"
204
+ ];
205
+ const skipSymbol = this.style("gray", supportUnicode ? "↓" : "-");
206
+ const prepareSymbol = this.style(["gray", "dim"], supportUnicode ? "◼" : ".");
207
+ let loadingFrameIndex = 0;
208
+ let cacheText = "";
209
+ let timer;
210
+ const replaceText = () => {
211
+ return cacheText.replaceAll("%loading%", loadingFrames[loadingFrameIndex]);
212
+ };
213
+ const reset = () => {
214
+ clearInterval(timer);
215
+ timer = void 0;
216
+ loadingFrameIndex = 0;
217
+ };
218
+ let prevText = "";
219
+ return {
220
+ /**
221
+ * 替换当前输出的文字
222
+ */
223
+ update: (text) => {
224
+ if (prevText === text) return;
225
+ prevText = text;
226
+ cacheText = text.replaceAll("%success%", symbols.success).replaceAll("%error%", symbols.error).replaceAll("%warning%", symbols.warning).replaceAll("%info%", symbols.info).replaceAll("%skip%", skipSymbol).replaceAll("%prepare%", prepareSymbol);
227
+ logSession(replaceText());
228
+ if (text.includes("%loading%")) timer ||= setInterval(() => {
229
+ loadingFrameIndex += 1;
230
+ if (loadingFrameIndex === loadingFrames.length) loadingFrameIndex = 0;
231
+ logSession(replaceText());
232
+ }, 80);
233
+ else reset();
234
+ },
235
+ /**
236
+ * 持久化已经输出的文字,进入下一个session
237
+ */
238
+ commit: () => {
239
+ reset();
240
+ logSession.done();
241
+ }
242
+ };
243
+ }
244
+ async runTasks(_tasks, opts = {}) {
245
+ const { concurrent = false } = opts;
246
+ const log = this.createSession();
247
+ const tasks = _tasks.map((task) => {
248
+ return {
249
+ ...task,
250
+ suffix: "",
251
+ status: "prepare"
252
+ };
253
+ });
254
+ const reRender = () => {
255
+ log.update(tasks.map((task) => {
256
+ const suffix = task.status === "skip" ? this.style("gray", `[skipped]`) : task.suffix;
257
+ return `%${task.status}% ${task.title}${suffix ? " " + suffix : ""}`;
258
+ }).join("\n"));
259
+ };
260
+ reRender();
261
+ const timer = setInterval(reRender, 16);
262
+ const handleTask = async (ctx, task) => {
263
+ if (typeof task.skip === "function" ? await task.skip(ctx) : task.skip === true) {
264
+ task.status = "skip";
265
+ return { error: null };
266
+ }
267
+ try {
268
+ task.status = "loading";
269
+ let statusChanged = false;
270
+ await task.task(ctx, {
271
+ get status() {
272
+ return task.status;
273
+ },
274
+ set status(status) {
275
+ task.status = status;
276
+ statusChanged = true;
277
+ },
278
+ get title() {
279
+ return task.title;
280
+ },
281
+ set title(t) {
282
+ task.title = t;
283
+ },
284
+ get suffix() {
285
+ return task.suffix;
286
+ },
287
+ set suffix(s) {
288
+ task.suffix = s;
289
+ }
290
+ });
291
+ if (!statusChanged) task.status = "success";
292
+ } catch (e) {
293
+ task.status = "error";
294
+ task.suffix = this.style("red", e.message);
295
+ return { error: e };
296
+ }
297
+ return { error: null };
298
+ };
299
+ try {
300
+ const ctx = {};
301
+ if (concurrent) {
302
+ const result = await Promise.allSettled(tasks.map((task) => handleTask(ctx, task)));
303
+ const errors = [];
304
+ for (const item of result) if (item.status === "fulfilled" && item.value.error !== null) errors.push(item.value.error);
305
+ if (errors.length) return {
306
+ errors,
307
+ context: ctx
308
+ };
309
+ } else for (const task of tasks) {
310
+ const { error } = await handleTask(ctx, task);
311
+ if (error) return {
312
+ error,
313
+ context: ctx
314
+ };
315
+ }
316
+ return {
317
+ context: ctx,
318
+ error: null
319
+ };
320
+ } finally {
321
+ clearInterval(timer);
322
+ reRender();
323
+ log.commit();
324
+ }
325
+ }
326
+ /**
327
+ * 为字符串设置样式:
328
+ * - 文字颜色、背景色
329
+ * - 粗体、斜体
330
+ * - 下划线、删除线、上划线、双下划线
331
+ *
332
+ * ```typescript
333
+ * const errorMsg = terminal.style('red', '一些错误的内容');
334
+ * const warnMsg = terminal.style(['yellow', 'bold'], '严重警告文字');
335
+ * ```
336
+ */
337
+ style(color, string) {
338
+ return styleText(color, string);
339
+ }
340
+ /**
341
+ * 去除ansi字符
342
+ * ```typescript
343
+ * terminal.stripStyle('\u001B[4mUnicorn\u001B[0m'); // Unicorn
344
+ * ```
345
+ */
346
+ stripStyle(string) {
347
+ return stripVTControlCharacters(string);
348
+ }
349
+ };
350
+ const terminal = new Terminal();
351
+ // src/utils/console-error.ts
352
+ /**
353
+ * CLI 指令异常。`app.on('error')` 收到的均为本类实例。
354
+ *
355
+ * 业务侧用 `new ConsoleError` 创建;其它错误经 {@link ConsoleError.from} 转换。
356
+ */
357
+ var ConsoleError = class ConsoleError extends Error {
358
+ code;
359
+ constructor(message, properties) {
360
+ const { cause, code } = properties ?? {};
361
+ super(message ?? "Error", cause !== void 0 ? { cause } : void 0);
362
+ this.name = "ConsoleError";
363
+ if (code !== void 0) this.code = code;
364
+ Error.captureStackTrace?.(this, new.target);
365
+ }
366
+ /** 是否为自制 {@link ConsoleError}(覆盖 `Error.isError`,类型收窄为本类) */
367
+ static isError(value) {
368
+ return value instanceof ConsoleError;
369
+ }
370
+ /**
371
+ * 将任意错误转为自制 {@link ConsoleError}。
372
+ *
373
+ * - 已是本类实例:原样返回
374
+ * - `Error`:迁移 `message` / `cause` / `name` / `stack`,以及字符串 `code`(Node `ErrnoException`)
375
+ * - 其余(含 plain object):不猜测字段,落成默认实例或仅用字符串 message
376
+ */
377
+ static from(error) {
378
+ if (ConsoleError.isError(error)) return error;
379
+ if (error == null) return new ConsoleError();
380
+ if (typeof error === "string") return new ConsoleError(error);
381
+ if (!Error.isError(error)) return new ConsoleError();
382
+ const code = error.code;
383
+ const err = new ConsoleError(error.message || void 0, {
384
+ code: typeof code === "string" ? code : void 0,
385
+ cause: error.cause
386
+ });
387
+ if (error.name && error.name !== "Error") err.name = error.name;
388
+ if (error.stack) err.stack = error.stack;
389
+ return err;
390
+ }
351
391
  };
352
- var terminal = new Terminal();
353
-
354
- // src/cli/app.ts
355
- import EventEmitter from "events";
356
- import { EOL } from "os";
357
- import { styleText as styleText3 } from "util";
358
- import { hideBin } from "yargs/helpers";
359
- import { I18n as I18n4, compose, middleware as middleware2 } from "@aomex/common";
360
-
361
392
  // src/cli/input.ts
362
- import parse from "yargs-parser";
363
393
  var ConsoleInput = class {
364
- constructor(app, argv) {
365
- this.app = app;
366
- this.argv = argv;
367
- const { _: commands, ...rawOptions } = parse(argv, {
368
- configuration: { "parse-numbers": false }
369
- });
370
- this.options = rawOptions;
371
- this.command = String(commands[0] || "");
372
- }
373
- options;
374
- command;
375
- parseArgv(alias) {
376
- const { _: commands, ...rawOptions } = parse(this.argv, {
377
- alias,
378
- configuration: { "parse-numbers": false }
379
- });
380
- return rawOptions;
381
- }
394
+ app;
395
+ argv;
396
+ options;
397
+ command;
398
+ constructor(app, argv) {
399
+ this.app = app;
400
+ this.argv = argv;
401
+ const { _: commands, ...rawOptions } = parse(argv, { configuration: { "parse-numbers": false } });
402
+ this.options = rawOptions;
403
+ this.command = String(commands[0] || "");
404
+ }
405
+ parseArgv(alias) {
406
+ const { _: commands, ...rawOptions } = parse(this.argv, {
407
+ alias,
408
+ configuration: { "parse-numbers": false }
409
+ });
410
+ return rawOptions;
411
+ }
382
412
  };
383
-
384
413
  // src/cli/context.ts
385
414
  var ConsoleContext = class {
386
- constructor(app, input) {
387
- this.app = app;
388
- this.input = input;
389
- }
390
- commandMatched = false;
415
+ app;
416
+ input;
417
+ commandMatched = false;
418
+ constructor(app, input) {
419
+ this.app = app;
420
+ this.input = input;
421
+ }
422
+ /** 与构造时传入的 `logger` 相同,取自 app */
423
+ get logger() {
424
+ return this.app["logger"];
425
+ }
391
426
  };
427
+ // src/utils/get-distance.ts
428
+ /**
429
+ Copyright (c) 2011 Andrei Mackenzie
392
430
 
393
- // src/middleware/help-logger.ts
394
- import { middleware } from "@aomex/common";
395
- import yargs from "yargs";
396
- import { styleText as styleText2 } from "util";
431
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
432
+ this software and associated documentation files (the "Software"), to deal in
433
+ the Software without restriction, including without limitation the rights to
434
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
435
+ the Software, and to permit persons to whom the Software is furnished to do so,
436
+ subject to the following conditions:
397
437
 
398
- // src/utils/get-distance.ts
399
- var getDistance = (a, b) => {
400
- if (a.length === 0) return b.length;
401
- if (b.length === 0) return a.length;
402
- const matrix = [];
403
- let i;
404
- for (i = 0; i <= b.length; i++) {
405
- matrix[i] = [i];
406
- }
407
- let j;
408
- for (j = 0; j <= a.length; j++) {
409
- matrix[0][j] = j;
410
- }
411
- for (i = 1; i <= b.length; i++) {
412
- for (j = 1; j <= a.length; j++) {
413
- if (b.charAt(i - 1) === a.charAt(j - 1)) {
414
- matrix[i][j] = matrix[i - 1][j - 1];
415
- } else if (i > 1 && j > 1 && b.charAt(i - 2) === a.charAt(j - 1) && b.charAt(i - 1) === a.charAt(j - 2)) {
416
- matrix[i][j] = matrix[i - 2][j - 2] + 1;
417
- } else {
418
- matrix[i][j] = Math.min(
419
- matrix[i - 1][j - 1] + 1,
420
- // substitution
421
- Math.min(
422
- matrix[i][j - 1] + 1,
423
- // insertion
424
- matrix[i - 1][j] + 1
425
- )
426
- );
427
- }
428
- }
429
- }
430
- return matrix[b.length][a.length];
431
- };
438
+ The above copyright notice and this permission notice shall be included in all
439
+ copies or substantial portions of the Software.
432
440
 
433
- // src/i18n/index.ts
434
- import { I18n as I18n3 } from "@aomex/common";
441
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
442
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
443
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
444
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
445
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
446
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
435
447
 
448
+ @link https://gist.github.com/andrei-m/982927
449
+ @link https://github.com/yargs/yargs/blob/main/lib/utils/levenshtein.ts
450
+ */
451
+ const getDistance = (a, b) => {
452
+ if (a.length === 0) return b.length;
453
+ if (b.length === 0) return a.length;
454
+ const matrix = [];
455
+ let i = 0;
456
+ for (; i <= b.length; i++) matrix[i] = [i];
457
+ let j = 0;
458
+ for (; j <= a.length; j++) matrix[0][j] = j;
459
+ for (i = 1; i <= b.length; i++) for (j = 1; j <= a.length; j++) if (b.charAt(i - 1) === a.charAt(j - 1)) matrix[i][j] = matrix[i - 1][j - 1];
460
+ else if (i > 1 && j > 1 && b.charAt(i - 2) === a.charAt(j - 1) && b.charAt(i - 1) === a.charAt(j - 2)) matrix[i][j] = matrix[i - 2][j - 2] + 1;
461
+ else matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
462
+ return matrix[b.length][a.length];
463
+ };
436
464
  // src/i18n/locales/zh-cn.ts
437
- import { I18n } from "@aomex/common";
438
- var zh = I18n.define({
439
- command_not_found: '\u6307\u4EE4 "{{command}}" \u4E0D\u5B58\u5728',
440
- command_found_recommended: '\u6307\u4EE4 "{{command}}" \u4E0D\u5B58\u5728\uFF0C\u4F60\u662F\u8BF4 "aomex {{recommended}}" \u5417\uFF1F',
441
- help: {
442
- command: "[\u6307\u4EE4]",
443
- option: "[\u9009\u9879]",
444
- version: "\u663E\u793A{{scriptName}}\u7248\u672C\u53F7",
445
- no_usage: '\u627E\u4E0D\u5230\u5173\u4E8E\u6307\u4EE4 "{{command}}" \u7684\u7528\u6CD5'
446
- }
465
+ const zh = I18n.define({
466
+ command_not_found: "命令「{{command}}」不存在",
467
+ command_found_recommended: "命令「{{command}}」不存在,你是说「aomex {{recommended}}」吗?",
468
+ help: {
469
+ command: "[命令]",
470
+ option: "[选项]",
471
+ version: "显示 {{scriptName}} 的版本号",
472
+ no_usage: "找不到命令「{{command}}」的用法"
473
+ }
447
474
  });
448
-
449
475
  // src/i18n/locales/en-us.ts
450
- import { I18n as I18n2 } from "@aomex/common";
451
- var en = I18n2.satisfies(zh).define({
452
- command_not_found: 'command "{{command}}" not found',
453
- command_found_recommended: 'command "{{command}}" not found, did you mean "aomex {{recommended}}"?',
454
- help: {
455
- command: "[command]",
456
- option: "[options]",
457
- version: "show version of {{scriptName}}",
458
- no_usage: 'no usage of command "{{command}}"'
459
- }
476
+ const en = I18n.satisfies(zh).define({
477
+ command_not_found: "Command \"{{command}}\" does not exist",
478
+ command_found_recommended: "Command \"{{command}}\" does not exist. Did you mean \"aomex {{recommended}}\"?",
479
+ help: {
480
+ command: "[command]",
481
+ option: "[options]",
482
+ version: "Show the version of {{scriptName}}",
483
+ no_usage: "No usage found for command \"{{command}}\""
484
+ }
460
485
  });
461
-
462
- // src/i18n/locales/index.ts
463
- var locales = {
464
- zh_CN: zh,
465
- en_US: en
466
- };
467
-
468
486
  // src/i18n/index.ts
469
- var i18n = new I18n3({
470
- resources: locales,
471
- defaultLanguage: "zh_CN"
487
+ const i18n = createI18n({
488
+ zh,
489
+ en,
490
+ load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href)
472
491
  });
473
-
474
492
  // src/middleware/help-logger.ts
475
- var helpLogger = (middlewareList) => {
476
- return middleware.console(async (ctx, next) => {
477
- const {
478
- input: { options: options2, command }
479
- } = ctx;
480
- if (command === "") {
481
- ctx.commandMatched = true;
482
- if (options2["version"] || options2["v"]) {
483
- console.log(version);
484
- } else {
485
- const cli = yargs([]).locale(i18n.language).scriptName(scriptName).usage(`${scriptName} ${i18n.t("help.command")} ${i18n.t("help.option")}`).describe("version", i18n.t("help.version", { scriptName })).alias("v", "version").alias("h", "help");
486
- const document = {};
487
- await collectConsoleDocument({
488
- document,
489
- middlewareList,
490
- app: ctx.app
491
- });
492
- Object.entries(document).forEach(([commandName, commandItem]) => {
493
- if (commandItem.showInHelp === false) return;
494
- cli.command(styleText2("yellow", commandName), commandItem.summary || "");
495
- });
496
- cli.showHelp("log");
497
- }
498
- return;
499
- }
500
- if (options2["help"] || options2["h"]) {
501
- ctx.commandMatched = true;
502
- const document = {};
503
- await collectConsoleDocument({ document, middlewareList, app: ctx.app });
504
- const commandItem = document[command];
505
- if (!commandItem || commandItem.showInHelp === false) {
506
- throw new Error(i18n.t("help.no_usage", { command }));
507
- }
508
- const cli = yargs([]).locale(i18n.language).scriptName(scriptName).version(false).help(false);
509
- const { description, parameters = [] } = commandItem;
510
- cli.usage(
511
- `${scriptName} ${command} ${i18n.t("help.option")}${description ? "\n\n" + styleText2("bold", description) : ""}`
512
- );
513
- parameters.forEach((parameter) => {
514
- cli.option(parameter.name, {
515
- alias: parameter.alias,
516
- description: parameter.description,
517
- deprecated: parameter.deprecated,
518
- type: parameter.type,
519
- default: parameter.defaultValue
520
- });
521
- });
522
- cli.showHelp("log");
523
- return;
524
- }
525
- await next();
526
- if (!ctx.commandMatched) {
527
- const recommendCommand = Object.entries(
528
- await collectConsoleDocument({
529
- document: {},
530
- middlewareList,
531
- app: ctx.app
532
- })
533
- ).map(([commandName]) => [commandName, getDistance(command, commandName)]).filter((item) => item[1] <= 3).sort((a, b) => a[1] - b[1])[0];
534
- throw new Error(
535
- recommendCommand ? i18n.t("command_found_recommended", {
536
- command,
537
- recommended: recommendCommand[0]
538
- }) : i18n.t("command_not_found", { command })
539
- );
540
- }
541
- });
493
+ /** 规范码 → yargs/y18n 文件名;其余把 `-` 换成 `_`,由 y18n 自行回退到语种前缀。 */
494
+ function yargsLocale(language) {
495
+ if (language === "zh-HK") return "zh_TW";
496
+ return language.replaceAll("-", "_");
497
+ }
498
+ const helpLogger = (middlewareList) => {
499
+ return middleware.console(async (ctx, next) => {
500
+ const { input: { options, command } } = ctx;
501
+ if (command === "") {
502
+ ctx.commandMatched = true;
503
+ if (options["version"] || options["v"]) console.log(version);
504
+ else {
505
+ const cli = yargs([]).locale(yargsLocale(i18n.language)).scriptName(scriptName).usage(`${scriptName} ${i18n.t("help.command")} ${i18n.t("help.option")}`).describe("version", i18n.t("help.version", { scriptName })).alias("v", "version").alias("h", "help");
506
+ const document = {};
507
+ await collectConsoleDocument({
508
+ document,
509
+ middlewareList,
510
+ app: ctx.app
511
+ });
512
+ Object.entries(document).forEach(([commandName, commandItem]) => {
513
+ if (commandItem.showInHelp === false) return;
514
+ cli.command(styleText("yellow", commandName), commandItem.summary || "");
515
+ });
516
+ cli.showHelp("log");
517
+ }
518
+ return;
519
+ }
520
+ if (options["help"] || options["h"]) {
521
+ ctx.commandMatched = true;
522
+ const document = {};
523
+ await collectConsoleDocument({
524
+ document,
525
+ middlewareList,
526
+ app: ctx.app
527
+ });
528
+ const commandItem = document[command];
529
+ if (!commandItem || commandItem.showInHelp === false) throw new ConsoleError(i18n.t("help.no_usage", { command }), { code: "NO_USAGE" });
530
+ const cli = yargs([]).locale(yargsLocale(i18n.language)).scriptName(scriptName).version(false).help(false);
531
+ const { description, parameters = [] } = commandItem;
532
+ cli.usage(`${scriptName} ${command} ${i18n.t("help.option")}${description ? "\n\n" + styleText("bold", description) : ""}`);
533
+ parameters.forEach((parameter) => {
534
+ cli.option(parameter.name, {
535
+ alias: parameter.alias,
536
+ description: parameter.description,
537
+ deprecated: parameter.deprecated,
538
+ type: parameter.type,
539
+ default: parameter.defaultValue
540
+ });
541
+ });
542
+ cli.showHelp("log");
543
+ return;
544
+ }
545
+ await next();
546
+ if (!ctx.commandMatched) {
547
+ const recommendCommand = Object.entries(await collectConsoleDocument({
548
+ document: {},
549
+ middlewareList,
550
+ app: ctx.app
551
+ })).map(([commandName]) => [commandName, getDistance(command, commandName)]).filter((item) => item[1] <= 3).sort((a, b) => a[1] - b[1])[0];
552
+ throw new ConsoleError(recommendCommand ? i18n.t("command_found_recommended", {
553
+ command,
554
+ recommended: recommendCommand[0]
555
+ }) : i18n.t("command_not_found", { command }), { code: "COMMAND_NOT_FOUND" });
556
+ }
557
+ });
542
558
  };
543
-
544
559
  // src/cli/app.ts
545
560
  var ConsoleApp = class extends EventEmitter {
546
- constructor(options2 = {}) {
547
- super();
548
- this.options = options2;
549
- this.middlewareList = options2.mount || [];
550
- }
551
- level = 0;
552
- point;
553
- middlewareList;
554
- /**
555
- * 执行指令。如果不传参数,则使用内置的`process.argv`
556
- * ```typescript
557
- * app.run('schedule:a')
558
- * app.run('schedule:a', '-f', '--type', 'all')
559
- * ```
560
- */
561
- async run(...commands) {
562
- const currentLevel = this.level++;
563
- const input = new ConsoleInput(
564
- this,
565
- commands.length ? commands : hideBin(process.argv)
566
- );
567
- const ctx = new ConsoleContext(this, input);
568
- if (!this.listenerCount("error")) {
569
- this.on("error", this.log.bind(this));
570
- }
571
- try {
572
- await compose([
573
- middleware2.mixin((_, next) => {
574
- return this.options.language ? I18n4.provider(this.options.language, next) : next();
575
- }),
576
- helpLogger(this.middlewareList),
577
- ...this.middlewareList
578
- ])(ctx);
579
- return 0;
580
- } catch (e) {
581
- this.emit("error", e, ctx, currentLevel);
582
- return 1;
583
- } finally {
584
- --this.level;
585
- }
586
- }
587
- log(err) {
588
- const stack = (err.stack || err.toString()).split(EOL).map((item) => " " + item);
589
- console.error([styleText3("red", stack.shift() || ""), stack.join(EOL)].join(EOL));
590
- }
561
+ options;
562
+ level = 0;
563
+ middlewareList;
564
+ logger;
565
+ constructor(options) {
566
+ super();
567
+ this.options = options;
568
+ this.middlewareList = options.mount || [];
569
+ this.logger = options.logger;
570
+ this.bindServicesShutdown(toArray(options.services));
571
+ }
572
+ bindServicesShutdown(services) {
573
+ process.once("beforeExit", () => {
574
+ internalDestroyServices(services);
575
+ });
576
+ const onSignal = () => {
577
+ internalDestroyServices(services).finally(() => {
578
+ process.exit(0);
579
+ });
580
+ };
581
+ process.once("SIGTERM", onSignal);
582
+ process.once("SIGINT", onSignal);
583
+ }
584
+ /**
585
+ * 执行指令。如果不传参数,则使用内置的`process.argv`
586
+ * ```typescript
587
+ * app.run('schedule:a')
588
+ * app.run('schedule:a', '-f', '--type', 'all')
589
+ * ```
590
+ */
591
+ async run(...commands) {
592
+ const currentLevel = this.level++;
593
+ const input = new ConsoleInput(this, commands.length ? commands : hideBin(process.argv));
594
+ const ctx = new ConsoleContext(this, input);
595
+ if (!this.listenerCount("error")) this.on("error", (err) => {
596
+ this.logger.error(err);
597
+ });
598
+ try {
599
+ await compose([
600
+ middleware.mixin(async (_, next) => {
601
+ const language = this.options.language;
602
+ await ensureI18nLanguage(language);
603
+ return I18n.provider(language, next);
604
+ }),
605
+ helpLogger(this.middlewareList),
606
+ ...this.middlewareList
607
+ ])(ctx);
608
+ return 0;
609
+ } catch (e) {
610
+ const err = ConsoleError.from(e);
611
+ this.emit("error", err, ctx, currentLevel);
612
+ return 1;
613
+ } finally {
614
+ --this.level;
615
+ }
616
+ }
591
617
  };
592
-
593
618
  // src/middleware/options.ts
594
- import { validate, Validator, middleware as middleware3 } from "@aomex/common";
595
- import { toArray } from "@aomex/internal-tools";
596
- var options = (fields, aliasList) => {
597
- return middleware3.console({
598
- fn: async (ctx, next) => {
599
- let options2 = ctx.input.options;
600
- if (aliasList && Object.keys(aliasList).length) {
601
- options2 = ctx.input.parseArgv(aliasList);
602
- }
603
- ctx.options = await validate(options2, fields);
604
- return next();
605
- },
606
- help: {
607
- onCommandItem(commandItem) {
608
- for (const [key, validator] of Object.entries(fields)) {
609
- const docs = Validator.toDocument(validator);
610
- const schema = docs.schema;
611
- let dateType;
612
- switch (schema?.type) {
613
- case "array":
614
- dateType = "array";
615
- break;
616
- case "integer":
617
- case "number":
618
- dateType = "number";
619
- break;
620
- case "boolean":
621
- dateType = "boolean";
622
- break;
623
- case "string":
624
- /**
625
- * 命令行无法输入对象
626
- * @see ObjectValidator.parseFromString()
627
- */
628
- case "object":
629
- dateType = "string";
630
- break;
631
- }
632
- const alias = aliasList?.[key];
633
- commandItem.parameters ||= [];
634
- commandItem.parameters.push({
635
- name: key,
636
- alias: alias && toArray(alias),
637
- type: dateType,
638
- description: docs.description,
639
- defaultValue: schema?.default,
640
- deprecated: docs.deprecated
641
- });
642
- }
643
- }
644
- }
645
- });
619
+ /**
620
+ * 接收并验证命令行的选项,并且保证类型安全
621
+ *
622
+ * ```typescript
623
+ * export const commander = new Commander();
624
+ *
625
+ * commander.create('my/schedule', {
626
+ * mount: [
627
+ * options({
628
+ * id: rule.int(),
629
+ * date: rule.date('YYYY-MM-DD'),
630
+ * }, {
631
+ * date: ['d'], // alias --date or -d
632
+ * });
633
+ * ],
634
+ * action: async (ctx) => {
635
+ * console.log(ctx.options);
636
+ * }
637
+ * });
638
+ * ```
639
+ *
640
+ */
641
+ const options = (fields, aliasList) => {
642
+ return middleware.console({
643
+ fn: async (ctx, next) => {
644
+ let options = ctx.input.options;
645
+ if (aliasList && Object.keys(aliasList).length) options = ctx.input.parseArgv(aliasList);
646
+ ctx.options = await validate(options, fields);
647
+ return next();
648
+ },
649
+ help: { onCommandItem(commandItem) {
650
+ for (const [key, validator] of Object.entries(fields)) {
651
+ const docs = toDocument(validator);
652
+ const schema = docs.schema;
653
+ let dateType;
654
+ switch (schema?.type) {
655
+ case "array":
656
+ dateType = "array";
657
+ break;
658
+ case "integer":
659
+ case "number":
660
+ dateType = "number";
661
+ break;
662
+ case "boolean":
663
+ dateType = "boolean";
664
+ break;
665
+ case "string":
666
+ /**
667
+ * 命令行无法输入对象
668
+ * @see ObjectValidator.parseFromString()
669
+ */
670
+ case "object": dateType = "string";
671
+ }
672
+ const alias = aliasList?.[key];
673
+ commandItem.parameters ||= [];
674
+ commandItem.parameters.push({
675
+ name: key,
676
+ alias: alias && toArray(alias),
677
+ type: dateType,
678
+ description: docs.description,
679
+ defaultValue: schema?.default,
680
+ deprecated: docs.deprecated
681
+ });
682
+ }
683
+ } }
684
+ });
646
685
  };
647
-
648
- // src/commander/commanders.ts
649
- import { compose as compose3, middleware as middleware6 } from "@aomex/common";
650
- import {
651
- pathToFiles,
652
- getFileValues
653
- } from "@aomex/internal-file-import";
654
-
655
- // src/commander/commander.ts
656
- import { compose as compose2, middleware as middleware5 } from "@aomex/common";
657
- import { toArray as toArray2 } from "@aomex/internal-tools";
658
-
659
686
  // src/commander/builder.ts
660
- import { middleware as middleware4 } from "@aomex/common";
661
687
  var Builder = class {
662
- docs;
663
- commands;
664
- middlewareList;
665
- constructor(prefix, commands, options2) {
666
- this.docs = options2.docs || {};
667
- this.docs.showInHelp ??= true;
668
- this.commands = commands.map((item) => prefix + item);
669
- this.middlewareList = [
670
- ...options2.mount || [],
671
- middleware4.console((ctx, _) => options2.action(ctx))
672
- ];
673
- }
674
- match(command) {
675
- return this.commands.includes(command);
676
- }
688
+ docs;
689
+ commands;
690
+ middlewareList;
691
+ constructor(prefix, commands, options) {
692
+ this.docs = options.docs || {};
693
+ this.docs.showInHelp ??= true;
694
+ this.commands = commands.map((item) => prefix + item);
695
+ this.middlewareList = [...options.mount || [], middleware.console((ctx, _) => options.action(ctx))];
696
+ }
697
+ match(command) {
698
+ return this.commands.includes(command);
699
+ }
677
700
  };
678
-
679
701
  // src/commander/commander.ts
680
702
  var Commander = class {
681
- constructor(opts = {}) {
682
- this.opts = opts;
683
- this.prefix = opts.prefix || "";
684
- this.middlewareList = opts.mount || [];
685
- }
686
- middlewareList;
687
- prefix;
688
- builders = [];
689
- create(commandName, options2) {
690
- const builder = new Builder(this.prefix, toArray2(commandName), options2);
691
- options2.disable !== true && this.builders.push(builder);
692
- return void 0;
693
- }
694
- toMiddleware() {
695
- const builders = [...this.builders];
696
- const buildersLength = builders.length;
697
- const commandFn = builders.map((builder) => {
698
- return compose2(this.middlewareList.concat(builder["middlewareList"]));
699
- });
700
- return middleware5.console({
701
- fn: (ctx, next) => {
702
- const { input } = ctx;
703
- const { command } = input;
704
- for (let i = 0; i < buildersLength; ++i) {
705
- if (builders[i].match(command)) {
706
- ctx.commandMatched = true;
707
- return commandFn[i](ctx, next);
708
- }
709
- }
710
- return next();
711
- },
712
- help: {
713
- onDocument: async (doc, { children, collectCommand }) => {
714
- for (const builder of builders) {
715
- for (const commandName of builder.commands) {
716
- doc[commandName] = { ...builder.docs };
717
- collectCommand(
718
- commandName,
719
- this.middlewareList.concat(builder["middlewareList"])
720
- );
721
- }
722
- }
723
- const totalMiddlewareList = [...this.middlewareList];
724
- for (const builder of builders) {
725
- totalMiddlewareList.push(...builder["middlewareList"]);
726
- }
727
- await children(totalMiddlewareList);
728
- },
729
- postDocument: async (_, { children }) => {
730
- const totalMiddlewareList = [...this.middlewareList];
731
- for (const builder of builders) {
732
- totalMiddlewareList.push(...builder["middlewareList"]);
733
- }
734
- await children(totalMiddlewareList);
735
- }
736
- }
737
- });
738
- }
703
+ opts;
704
+ middlewareList;
705
+ prefix;
706
+ builders = [];
707
+ constructor(opts = {}) {
708
+ this.opts = opts;
709
+ this.prefix = opts.prefix || "";
710
+ this.middlewareList = opts.mount || [];
711
+ }
712
+ create(commandName, options) {
713
+ const builder = new Builder(this.prefix, toArray(commandName), options);
714
+ options.disabled !== true && this.builders.push(builder);
715
+ }
716
+ toMiddleware() {
717
+ const builders = [...this.builders];
718
+ const buildersLength = builders.length;
719
+ const commandFn = builders.map((builder) => {
720
+ return compose(this.middlewareList.concat(builder["middlewareList"]));
721
+ });
722
+ return middleware.console({
723
+ fn: (ctx, next) => {
724
+ const { input } = ctx;
725
+ const { command } = input;
726
+ for (let i = 0; i < buildersLength; ++i) if (builders[i].match(command)) {
727
+ ctx.commandMatched = true;
728
+ return commandFn[i](ctx, next);
729
+ }
730
+ return next();
731
+ },
732
+ help: {
733
+ onDocument: async (doc, { children, collectCommand }) => {
734
+ for (const builder of builders) for (const commandName of builder.commands) {
735
+ doc[commandName] = { ...builder.docs };
736
+ collectCommand(commandName, this.middlewareList.concat(builder["middlewareList"]));
737
+ }
738
+ const totalMiddlewareList = [...this.middlewareList];
739
+ for (const builder of builders) totalMiddlewareList.push(...builder["middlewareList"]);
740
+ await children(totalMiddlewareList);
741
+ },
742
+ postDocument: async (_, { children }) => {
743
+ const totalMiddlewareList = [...this.middlewareList];
744
+ for (const builder of builders) totalMiddlewareList.push(...builder["middlewareList"]);
745
+ await children(totalMiddlewareList);
746
+ }
747
+ }
748
+ });
749
+ }
739
750
  };
740
-
741
751
  // src/commander/commanders.ts
742
- var commanders = (options2) => {
743
- let composeFn;
744
- let commanders2;
745
- let promise = Promise.resolve();
746
- if (isCommanders(options2)) {
747
- commanders2 = options2;
748
- } else {
749
- promise = pathToFiles(options2).then(async (files) => {
750
- commanders2 = await getFileValues(
751
- files,
752
- (item) => !!item && item instanceof Commander
753
- );
754
- });
755
- }
756
- return middleware6.console({
757
- fn: async (ctx, next) => {
758
- if (!commanders2) await promise;
759
- composeFn ||= compose3(commanders2.map((commander) => commander["toMiddleware"]()));
760
- return composeFn(ctx, next);
761
- },
762
- help: {
763
- async onDocument(_, { children }) {
764
- await promise;
765
- await children(commanders2.map((commander) => commander["toMiddleware"]()));
766
- },
767
- async postDocument(_, { children }) {
768
- await children(commanders2.map((commander) => commander["toMiddleware"]()));
769
- }
770
- }
771
- });
752
+ const commanders = (options) => {
753
+ let composeFn;
754
+ let commanders;
755
+ let promise = Promise.resolve();
756
+ if (isCommanders(options)) commanders = options;
757
+ else promise = pathToFiles(options).then(async (files) => {
758
+ commanders = await getFileValues(files, (item) => !!item && item instanceof Commander);
759
+ });
760
+ return middleware.console({
761
+ fn: async (ctx, next) => {
762
+ if (!commanders) await promise;
763
+ composeFn ||= compose(commanders.map((commander) => commander["toMiddleware"]()));
764
+ return composeFn(ctx, next);
765
+ },
766
+ help: {
767
+ async onDocument(_, { children }) {
768
+ await promise;
769
+ await children(commanders.map((commander) => commander["toMiddleware"]()));
770
+ },
771
+ async postDocument(_, { children }) {
772
+ await children(commanders.map((commander) => commander["toMiddleware"]()));
773
+ }
774
+ }
775
+ });
772
776
  };
773
- var isCommanders = (options2) => {
774
- return Array.isArray(options2) && options2.some((item) => item instanceof Commander);
775
- };
776
- export {
777
- Builder,
778
- Commander,
779
- ConsoleApp,
780
- ConsoleContext,
781
- ConsoleInput,
782
- ConsoleMiddleware,
783
- collectConsoleDocument,
784
- commanders,
785
- options,
786
- scriptName,
787
- terminal,
788
- version
777
+ const isCommanders = (options) => {
778
+ return Array.isArray(options) && options.some((item) => item instanceof Commander);
789
779
  };
780
+ export { Builder, Commander, ConsoleApp, ConsoleContext, ConsoleError, ConsoleInput, ConsoleMiddleware, collectConsoleDocument, commanders, options, scriptName, terminal, version };
781
+
790
782
  //# sourceMappingURL=index.js.map