@aomex/console 0.0.5 → 0.0.7
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/CHANGELOG.md +13 -48
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +81 -0
- package/dist/bin.js.map +1 -0
- package/dist/index.d.ts +37 -11
- package/dist/index.js +50 -20
- package/dist/index.js.map +1 -1
- package/package.json +8 -11
- package/src/bin.ts +84 -0
- package/dist/cli/bin.d.ts +0 -2
- package/dist/cli/bin.js +0 -21
- package/dist/cli/bin.js.map +0 -1
- package/dist/cli/define-config.d.ts +0 -9
- package/dist/cli/define-config.js +0 -6
- package/dist/cli/define-config.js.map +0 -1
- package/src/cli/bin.ts +0 -20
package/CHANGELOG.md
CHANGED
|
@@ -1,61 +1,26 @@
|
|
|
1
1
|
# @aomex/console
|
|
2
2
|
|
|
3
|
-
## 0.0.
|
|
3
|
+
## 0.0.7
|
|
4
4
|
|
|
5
5
|
### Patch Changes
|
|
6
6
|
|
|
7
|
-
- [`
|
|
7
|
+
- [`01f90ab`](https://github.com/aomex/aomex/commit/01f90abec716427b7ccde3ab566067a4ba3293c8) Thanks [@geekact](https://github.com/geekact)! - fix(console): options.toHelp() use wrong description
|
|
8
8
|
|
|
9
|
-
- [`
|
|
9
|
+
- [`6c6cda2`](https://github.com/aomex/aomex/commit/6c6cda26522176c44761a738f2bc106a1889497b) Thanks [@geekact](https://github.com/geekact)! - chore(console): upgrade yargs from 17.6.2 to 17.7.1
|
|
10
10
|
|
|
11
|
-
- Updated dependencies [[`
|
|
12
|
-
- @aomex/
|
|
13
|
-
- @aomex/core@0.0.
|
|
11
|
+
- Updated dependencies [[`b7313d5`](https://github.com/aomex/aomex/commit/b7313d56bdb93cabde8dc5b872a94b590f45b655), [`c4bb0f4`](https://github.com/aomex/aomex/commit/c4bb0f424e7d2d2f8610583e106cbaef73077278)]:
|
|
12
|
+
- @aomex/file-parser@0.0.4
|
|
13
|
+
- @aomex/core@0.0.7
|
|
14
14
|
|
|
15
|
-
## 0.0.
|
|
15
|
+
## 0.0.6
|
|
16
16
|
|
|
17
17
|
### Patch Changes
|
|
18
18
|
|
|
19
|
-
- [`
|
|
19
|
+
- [`bbc8dda`](https://github.com/aomex/aomex/commit/bbc8dda9f0876c3402608133085350cc693def6f) Thanks [@geekact](https://github.com/geekact)! - refactor: rename package helper to utility
|
|
20
20
|
|
|
21
|
-
- [`
|
|
21
|
+
- [`9866b9e`](https://github.com/aomex/aomex/commit/9866b9e63abb71e1197ff8002c38bac04a36dd62) Thanks [@geekact](https://github.com/geekact)! - feat(console): run command parallel is supported
|
|
22
22
|
|
|
23
|
-
- [`
|
|
24
|
-
|
|
25
|
-
-
|
|
26
|
-
|
|
27
|
-
- [`6849b03`](https://github.com/aomex/aomex/commit/6849b03dc1e0dc9b707d89dfe98327c9f120dc7f) Thanks [@geekact](https://github.com/geekact)! - feat(middleware): chain.flatten 支持传入数组
|
|
28
|
-
|
|
29
|
-
- [`56a5e1f`](https://github.com/aomex/aomex/commit/56a5e1fffe3e1cec863e52c21d122979d121c630) Thanks [@geekact](https://github.com/geekact)! - fix(console): description 赋值错误
|
|
30
|
-
|
|
31
|
-
- Updated dependencies [[`956bba9`](https://github.com/aomex/aomex/commit/956bba9e5b954f34486ad5f2b45a5277c1f980c9), [`ee021e3`](https://github.com/aomex/aomex/commit/ee021e342814f12777e538c06a19971e1020f201)]:
|
|
32
|
-
- @aomex/helper@0.0.2
|
|
33
|
-
- @aomex/core@0.0.4
|
|
34
|
-
|
|
35
|
-
## 0.0.3
|
|
36
|
-
|
|
37
|
-
### Patch Changes
|
|
38
|
-
|
|
39
|
-
- [`ee5f8ca`](https://github.com/aomex/aomex/commit/ee5f8ca34df085ab9b5ef2a3525cf361ac46440a) Thanks [@geekact](https://github.com/geekact)! - request.query 重命名为 request.options
|
|
40
|
-
|
|
41
|
-
- [`d06c1c1`](https://github.com/aomex/aomex/commit/d06c1c1bdfee8657a74bbcbb06a2880263e85529) Thanks [@geekact](https://github.com/geekact)! - middleware 增加构造函数
|
|
42
|
-
|
|
43
|
-
- Updated dependencies []:
|
|
44
|
-
- @aomex/core@0.0.3
|
|
45
|
-
|
|
46
|
-
## 0.0.2
|
|
47
|
-
|
|
48
|
-
### Patch Changes
|
|
49
|
-
|
|
50
|
-
- [`f0b7c9a`](https://github.com/aomex/aomex/commit/f0b7c9a7ce70774080b645c4952ad9b1d0948cf5) Thanks [@geekact](https://github.com/geekact)! - 增加前置全局中间件概念
|
|
51
|
-
|
|
52
|
-
- Updated dependencies [[`d1ce4e2`](https://github.com/aomex/aomex/commit/d1ce4e2276f93c44e67ea06666d048917fa94e53)]:
|
|
53
|
-
- @aomex/core@0.0.2
|
|
54
|
-
|
|
55
|
-
## 0.0.1
|
|
56
|
-
|
|
57
|
-
### Patch Changes
|
|
58
|
-
|
|
59
|
-
- Updated dependencies [[`be095e9`](https://github.com/aomex/aomex/commit/be095e964ec136982581f4ea09024f716ff93a3d)]:
|
|
60
|
-
- @aomex/helper@0.0.1
|
|
61
|
-
- @aomex/core@0.0.1
|
|
23
|
+
- Updated dependencies [[`589243d`](https://github.com/aomex/aomex/commit/589243da955f3e4296d30fdfe05eac0c45714281), [`24d45f0`](https://github.com/aomex/aomex/commit/24d45f02966cfd936d493de5844bcae73caa6d10), [`cab01c6`](https://github.com/aomex/aomex/commit/cab01c63d60e73a7e24018e6872080d5656c29e2), [`bbc8dda`](https://github.com/aomex/aomex/commit/bbc8dda9f0876c3402608133085350cc693def6f)]:
|
|
24
|
+
- @aomex/file-parser@0.0.3
|
|
25
|
+
- @aomex/utility@0.0.4
|
|
26
|
+
- @aomex/core@0.0.6
|
package/dist/bin.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env -S ts-node-esm --transpileOnly --experimentalSpecifierResolution=node
|
package/dist/bin.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
#!/usr/bin/env -S ts-node-esm --transpileOnly --experimentalSpecifierResolution=node
|
|
2
|
+
|
|
3
|
+
// src/bin.ts
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { existsSync, statSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { hideBin } from "yargs/helpers";
|
|
8
|
+
import { fileToModules, pathToFiles } from "@aomex/file-parser";
|
|
9
|
+
import { chalk } from "@aomex/utility";
|
|
10
|
+
{
|
|
11
|
+
const defaultConfig = {
|
|
12
|
+
cliEntry: {
|
|
13
|
+
production: "./src/cli.js",
|
|
14
|
+
default: "./src/cli.ts"
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
const args = hideBin(process.argv);
|
|
18
|
+
if (args.length === 1 && args[0] === "--init") {
|
|
19
|
+
const file = path.resolve("aomex.config.ts");
|
|
20
|
+
if (existsSync(file)) {
|
|
21
|
+
console.warn(
|
|
22
|
+
chalk.yellow("Your configuration file had been generated already!")
|
|
23
|
+
);
|
|
24
|
+
process.exit(0);
|
|
25
|
+
}
|
|
26
|
+
writeFileSync(
|
|
27
|
+
file,
|
|
28
|
+
`import { defineConfig } from '@aomex/console';
|
|
29
|
+
|
|
30
|
+
export default defineConfig(${JSON.stringify(defaultConfig, null, 2)});
|
|
31
|
+
`
|
|
32
|
+
);
|
|
33
|
+
console.info(
|
|
34
|
+
"Configuration file has been generated successfully: " + chalk.blueBright(file)
|
|
35
|
+
);
|
|
36
|
+
process.exit(0);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
var env = process.env["NODE_ENV"] || "development";
|
|
40
|
+
var parseEnv = (config2) => {
|
|
41
|
+
if (!config2)
|
|
42
|
+
return null;
|
|
43
|
+
if (Object.hasOwn(config2, env))
|
|
44
|
+
return config2[env];
|
|
45
|
+
if (Object.hasOwn(config2, "default"))
|
|
46
|
+
return config2["default"];
|
|
47
|
+
return null;
|
|
48
|
+
};
|
|
49
|
+
var files = await pathToFiles("./aomex.config{.ts,.js}");
|
|
50
|
+
var config;
|
|
51
|
+
for (const file of files) {
|
|
52
|
+
const configs = await fileToModules(
|
|
53
|
+
[file],
|
|
54
|
+
(item) => typeof item === "object"
|
|
55
|
+
);
|
|
56
|
+
if (configs.length) {
|
|
57
|
+
config = configs[0];
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (!config) {
|
|
62
|
+
console.error(
|
|
63
|
+
`Aomex doesn't find a configuration file matched pattern "aomex.config.{ts|js}", would you please execute the initialize command below at first?
|
|
64
|
+
|
|
65
|
+
${chalk.greenBright(
|
|
66
|
+
"npx aomex --init"
|
|
67
|
+
)}
|
|
68
|
+
`
|
|
69
|
+
);
|
|
70
|
+
process.exit(1);
|
|
71
|
+
}
|
|
72
|
+
var cliEntry = parseEnv(config.cliEntry) || "";
|
|
73
|
+
if (cliEntry) {
|
|
74
|
+
cliEntry = path.resolve(cliEntry);
|
|
75
|
+
}
|
|
76
|
+
if (!cliEntry || !statSync(cliEntry).isFile()) {
|
|
77
|
+
console.error(`The given entry file "${cliEntry}" is not found`);
|
|
78
|
+
process.exit(1);
|
|
79
|
+
}
|
|
80
|
+
await import(pathToFileURL(cliEntry).toString());
|
|
81
|
+
//# sourceMappingURL=bin.js.map
|
package/dist/bin.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env -S ts-node-esm --transpileOnly --experimentalSpecifierResolution=node\n\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { existsSync, statSync, writeFileSync } from 'node:fs';\nimport { hideBin } from 'yargs/helpers';\nimport { fileToModules, pathToFiles } from '@aomex/file-parser';\nimport { chalk } from '@aomex/utility';\nimport type { Config } from './define-config';\n\n{\n const defaultConfig: Config = {\n cliEntry: {\n production: './src/cli.js',\n default: './src/cli.ts',\n },\n };\n\n const args = hideBin(process.argv);\n if (args.length === 1 && args[0] === '--init') {\n const file = path.resolve('aomex.config.ts');\n\n if (existsSync(file)) {\n console.warn(\n chalk.yellow('Your configuration file had been generated already!'),\n );\n process.exit(0);\n }\n\n writeFileSync(\n file,\n `import { defineConfig } from '@aomex/console';\n\nexport default defineConfig(${JSON.stringify(defaultConfig, null, 2)});\n`,\n );\n console.info(\n 'Configuration file has been generated successfully: ' +\n chalk.blueBright(file),\n );\n process.exit(0);\n }\n}\n\nconst env = process.env['NODE_ENV'] || 'development';\nconst parseEnv = (config: any) => {\n if (!config) return null;\n if (Object.hasOwn(config, env)) return config[env];\n if (Object.hasOwn(config, 'default')) return config['default'];\n return null;\n};\n\nconst files = await pathToFiles('./aomex.config{.ts,.js}');\nlet config: Config | undefined;\n\nfor (const file of files) {\n const configs = await fileToModules<Config>(\n [file],\n (item) => typeof item === 'object',\n );\n if (configs.length) {\n config = configs[0]!;\n break;\n }\n}\n\nif (!config) {\n console.error(\n `Aomex doesn't find a configuration file matched pattern \"aomex.config.{ts|js}\", would you please execute the initialize command below at first?\\n\\n${chalk.greenBright(\n 'npx aomex --init',\n )}\\n`,\n );\n process.exit(1);\n}\n\nlet cliEntry: string = parseEnv(config.cliEntry) || '';\nif (cliEntry) {\n cliEntry = path.resolve(cliEntry);\n}\nif (!cliEntry || !statSync(cliEntry).isFile()) {\n console.error(`The given entry file \"${cliEntry}\" is not found`);\n process.exit(1);\n}\nawait import(pathToFileURL(cliEntry).toString());\n"],"mappings":";;;AAEA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAC9B,SAAS,YAAY,UAAU,qBAAqB;AACpD,SAAS,eAAe;AACxB,SAAS,eAAe,mBAAmB;AAC3C,SAAS,aAAa;AAGtB;AACE,QAAM,gBAAwB;AAAA,IAC5B,UAAU;AAAA,MACR,YAAY;AAAA,MACZ,SAAS;AAAA,IACX;AAAA,EACF;AAEA,QAAM,OAAO,QAAQ,QAAQ,IAAI;AACjC,MAAI,KAAK,WAAW,KAAK,KAAK,CAAC,MAAM,UAAU;AAC7C,UAAM,OAAO,KAAK,QAAQ,iBAAiB;A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AAS;","names":["config"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Chain, PureMiddlewareToken, Next, Middleware, Validator } from '@aomex/core';
|
|
2
|
-
import { NonReadonly } from '@aomex/
|
|
2
|
+
import { NonReadonly } from '@aomex/utility';
|
|
3
3
|
import { Argv } from 'yargs';
|
|
4
4
|
import EventEmitter from 'node:events';
|
|
5
5
|
|
|
@@ -17,18 +17,21 @@ declare class ConsoleChain<Props extends object = object> extends Chain<Props> {
|
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
interface ConsoleAppOption {
|
|
20
|
+
silent?: boolean;
|
|
20
21
|
}
|
|
21
22
|
declare class ConsoleApp extends EventEmitter {
|
|
23
|
+
protected readonly options: ConsoleAppOption;
|
|
22
24
|
readonly chainPoints: string[];
|
|
23
|
-
protected
|
|
25
|
+
protected level: number;
|
|
24
26
|
protected readonly tokenList: ConsoleMiddlewareToken[];
|
|
25
|
-
constructor(
|
|
27
|
+
constructor(options?: ConsoleAppOption);
|
|
26
28
|
/**
|
|
27
|
-
*
|
|
29
|
+
* Run command. Builtin `process.argv` will be used by default until you input one or more arguments.
|
|
30
|
+
* @see process.argv
|
|
28
31
|
*/
|
|
29
32
|
run(...commands: string[]): Promise<void>;
|
|
30
33
|
log(err: Error): void;
|
|
31
|
-
mount(middleware: ConsoleMiddlewareToken): void;
|
|
34
|
+
mount(middleware: ConsoleMiddlewareToken | null): void;
|
|
32
35
|
}
|
|
33
36
|
|
|
34
37
|
declare class ConsoleRequest {
|
|
@@ -56,9 +59,16 @@ interface ShowHelpProps {
|
|
|
56
59
|
cli: ShowHelp;
|
|
57
60
|
}
|
|
58
61
|
declare class ShowHelp {
|
|
59
|
-
readonly
|
|
60
|
-
readonly
|
|
61
|
-
|
|
62
|
+
protected readonly ctx: ConsoleContext;
|
|
63
|
+
protected readonly status: 'all' | 'detail';
|
|
64
|
+
protected readonly yargs: Argv;
|
|
65
|
+
constructor(ctx: ConsoleContext, status: 'all' | 'detail', yargs: Argv);
|
|
66
|
+
config({ next, all, detail, detailCommand, }: {
|
|
67
|
+
all: (yargs: Argv) => Promise<void> | void;
|
|
68
|
+
detail: (yargs: Argv) => Promise<void> | void;
|
|
69
|
+
detailCommand: string | (() => boolean);
|
|
70
|
+
next: Next;
|
|
71
|
+
}): Promise<any>;
|
|
62
72
|
}
|
|
63
73
|
|
|
64
74
|
type YargsInstance = Argv;
|
|
@@ -97,7 +107,7 @@ declare class ConsoleOptionMiddleware<Props extends {
|
|
|
97
107
|
toHelp(yargs: YargsInstance): void;
|
|
98
108
|
}
|
|
99
109
|
/**
|
|
100
|
-
*
|
|
110
|
+
* Validate command-line options, and make type safe.
|
|
101
111
|
*
|
|
102
112
|
* ```typescript
|
|
103
113
|
* export const commander = new Commander();
|
|
@@ -108,7 +118,7 @@ declare class ConsoleOptionMiddleware<Props extends {
|
|
|
108
118
|
* id: rule.int(),
|
|
109
119
|
* date: rule.datetime('YYYY-MM-DD'),
|
|
110
120
|
* }, {
|
|
111
|
-
* date: ['d'], //
|
|
121
|
+
* date: ['d'], // alias --date or -d
|
|
112
122
|
* });
|
|
113
123
|
* ],
|
|
114
124
|
* action: async (ctx) => {
|
|
@@ -122,4 +132,20 @@ declare const options: <T extends {
|
|
|
122
132
|
[key: string]: P;
|
|
123
133
|
}, P extends Validator<unknown>, Alias extends keyof T>(fields: T, alias?: { [key in Alias]: string | string[]; } | undefined) => ConsoleOptionMiddleware<T>;
|
|
124
134
|
|
|
125
|
-
|
|
135
|
+
interface Config {
|
|
136
|
+
cliEntry: {
|
|
137
|
+
/**
|
|
138
|
+
* Entry file by each environment
|
|
139
|
+
* @see process.env.NODE_ENV
|
|
140
|
+
*/
|
|
141
|
+
[NODE_ENV: string]: string | undefined;
|
|
142
|
+
/**
|
|
143
|
+
* Fallback to `default` if NODE_ENV doesn't match specific file.
|
|
144
|
+
* @see process.env.NODE_ENV
|
|
145
|
+
*/
|
|
146
|
+
default?: string;
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
declare const defineConfig: (config: Config) => Config;
|
|
150
|
+
|
|
151
|
+
export { Config, ConsoleApp, ConsoleAppOption, ConsoleChain, ConsoleContext, ConsoleMiddleware, ConsoleMiddlewareToken, ConsoleOptionMiddleware, ConsoleRequest, ConsoleResponse, HelpMiddleware, YargsInstance, defineConfig, options, scriptName, version };
|
package/dist/index.js
CHANGED
|
@@ -6,16 +6,39 @@ import assert from "node:assert";
|
|
|
6
6
|
import { compose, middleware } from "@aomex/core";
|
|
7
7
|
import yargs from "yargs";
|
|
8
8
|
|
|
9
|
-
// src/
|
|
10
|
-
var version = "0.0.
|
|
9
|
+
// src/meta.ts
|
|
10
|
+
var version = "0.0.7";
|
|
11
11
|
var scriptName = "aomex";
|
|
12
12
|
|
|
13
13
|
// src/middleware/showHelp.ts
|
|
14
14
|
var ShowHelp = class {
|
|
15
|
-
constructor(status, yargs2) {
|
|
15
|
+
constructor(ctx, status, yargs2) {
|
|
16
|
+
this.ctx = ctx;
|
|
16
17
|
this.status = status;
|
|
17
18
|
this.yargs = yargs2;
|
|
18
19
|
}
|
|
20
|
+
async config({
|
|
21
|
+
next,
|
|
22
|
+
all,
|
|
23
|
+
detail,
|
|
24
|
+
detailCommand
|
|
25
|
+
}) {
|
|
26
|
+
if (this.status === "all") {
|
|
27
|
+
await all(this.yargs);
|
|
28
|
+
return next();
|
|
29
|
+
} else if (this.status === "detail") {
|
|
30
|
+
if (typeof detailCommand === "string") {
|
|
31
|
+
if (detailCommand !== this.ctx.request.command)
|
|
32
|
+
return next();
|
|
33
|
+
} else {
|
|
34
|
+
if (!detailCommand()) {
|
|
35
|
+
return next();
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
await detail(this.yargs);
|
|
39
|
+
this.ctx.response.commandMatched = true;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
19
42
|
};
|
|
20
43
|
var showHelp = (middlewareList) => {
|
|
21
44
|
const composeFn = compose(middlewareList);
|
|
@@ -30,7 +53,7 @@ var showHelp = (middlewareList) => {
|
|
|
30
53
|
console.log(version);
|
|
31
54
|
} else {
|
|
32
55
|
const cli = yargs([]).scriptName(scriptName).usage(`${scriptName} [command] [options] [--help|-h]`).describe("version", `Show ${scriptName} version number`).alias("v", "version").alias("h", "help");
|
|
33
|
-
ctx.cli = new ShowHelp("
|
|
56
|
+
ctx.cli = new ShowHelp(ctx, "all", cli);
|
|
34
57
|
await composeFn(ctx);
|
|
35
58
|
cli.showHelp("log");
|
|
36
59
|
}
|
|
@@ -38,7 +61,7 @@ var showHelp = (middlewareList) => {
|
|
|
38
61
|
}
|
|
39
62
|
if (options2["help"] || options2["h"]) {
|
|
40
63
|
const cli = yargs([]).scriptName(scriptName).version(false).help(false);
|
|
41
|
-
ctx.cli = new ShowHelp("
|
|
64
|
+
ctx.cli = new ShowHelp(ctx, "detail", cli);
|
|
42
65
|
await composeFn(ctx);
|
|
43
66
|
if (!response.commandMatched) {
|
|
44
67
|
throw new Error(`Unable to find usage of command "${command}"`);
|
|
@@ -113,22 +136,21 @@ var ConsoleResponse = class {
|
|
|
113
136
|
};
|
|
114
137
|
|
|
115
138
|
// src/app/app.ts
|
|
116
|
-
import { chalk } from "@aomex/
|
|
139
|
+
import { chalk } from "@aomex/utility";
|
|
117
140
|
var ConsoleApp = class extends EventEmitter {
|
|
118
|
-
|
|
119
|
-
running = false;
|
|
120
|
-
tokenList = [];
|
|
121
|
-
constructor(_options = {}) {
|
|
141
|
+
constructor(options2 = {}) {
|
|
122
142
|
super();
|
|
143
|
+
this.options = options2;
|
|
123
144
|
}
|
|
145
|
+
chainPoints = [];
|
|
146
|
+
level = 0;
|
|
147
|
+
tokenList = [];
|
|
124
148
|
/**
|
|
125
|
-
*
|
|
149
|
+
* Run command. Builtin `process.argv` will be used by default until you input one or more arguments.
|
|
150
|
+
* @see process.argv
|
|
126
151
|
*/
|
|
127
152
|
async run(...commands) {
|
|
128
|
-
|
|
129
|
-
throw new Error('Call "app.run()" multiple times at same time');
|
|
130
|
-
}
|
|
131
|
-
this.running = true;
|
|
153
|
+
const currentLevel = this.level++;
|
|
132
154
|
const request = new ConsoleRequest(
|
|
133
155
|
this,
|
|
134
156
|
commands.length ? commands : hideBin(process.argv)
|
|
@@ -136,7 +158,7 @@ var ConsoleApp = class extends EventEmitter {
|
|
|
136
158
|
const response = new ConsoleResponse(this);
|
|
137
159
|
const ctx = new ConsoleContext(this, request, response);
|
|
138
160
|
if (!this.listenerCount("error")) {
|
|
139
|
-
this.on("error", this.log);
|
|
161
|
+
this.on("error", this.log.bind(this));
|
|
140
162
|
}
|
|
141
163
|
try {
|
|
142
164
|
const middlewareList = Chain2.flatten(this.tokenList);
|
|
@@ -151,21 +173,25 @@ var ConsoleApp = class extends EventEmitter {
|
|
|
151
173
|
throw new Error(`Command "${request.command}" is not found`);
|
|
152
174
|
}
|
|
153
175
|
} catch (e) {
|
|
154
|
-
this.emit("error", e);
|
|
176
|
+
currentLevel === 0 && this.emit("error", e);
|
|
155
177
|
throw e;
|
|
156
178
|
} finally {
|
|
157
|
-
this.
|
|
179
|
+
--this.level;
|
|
158
180
|
}
|
|
159
181
|
}
|
|
160
182
|
log(err) {
|
|
183
|
+
if (this.options.silent)
|
|
184
|
+
return;
|
|
161
185
|
const stack = (err.stack || err.toString()).split(EOL).map((item) => " " + item);
|
|
162
186
|
console.error(
|
|
163
187
|
["", chalk.red(stack.shift()), stack.join(EOL), ""].join(EOL)
|
|
164
188
|
);
|
|
165
189
|
}
|
|
166
190
|
mount(middleware2) {
|
|
191
|
+
if (middleware2 === null)
|
|
192
|
+
return;
|
|
167
193
|
if (middleware2 instanceof Chain2) {
|
|
168
|
-
this.chainPoints.push(Chain2.
|
|
194
|
+
this.chainPoints.push(Chain2.createSplitPoint(middleware2));
|
|
169
195
|
}
|
|
170
196
|
this.tokenList.push(middleware2);
|
|
171
197
|
}
|
|
@@ -215,7 +241,7 @@ var ConsoleOptionMiddleware = class extends ConsoleMiddleware {
|
|
|
215
241
|
}
|
|
216
242
|
yargs2.option(key, {
|
|
217
243
|
alias: aliases[key],
|
|
218
|
-
description:
|
|
244
|
+
description: docs.description,
|
|
219
245
|
default: defaultValue,
|
|
220
246
|
deprecated: docs.deprecated,
|
|
221
247
|
type: dateType
|
|
@@ -224,6 +250,9 @@ var ConsoleOptionMiddleware = class extends ConsoleMiddleware {
|
|
|
224
250
|
}
|
|
225
251
|
};
|
|
226
252
|
var options = (fields, alias) => new ConsoleOptionMiddleware(fields, alias);
|
|
253
|
+
|
|
254
|
+
// src/define-config.ts
|
|
255
|
+
var defineConfig = (config) => config;
|
|
227
256
|
export {
|
|
228
257
|
ConsoleApp,
|
|
229
258
|
ConsoleChain,
|
|
@@ -233,6 +262,7 @@ export {
|
|
|
233
262
|
ConsoleRequest,
|
|
234
263
|
ConsoleResponse,
|
|
235
264
|
HelpMiddleware,
|
|
265
|
+
defineConfig,
|
|
236
266
|
options,
|
|
237
267
|
scriptName,
|
|
238
268
|
version
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/override/middleware.ts","../src/middleware/showHelp.ts","../src/info.ts","../src/override/chain.ts","../src/app/context.ts","../src/app/app.ts","../src/app/request.ts","../src/app/response.ts","../src/middleware/options.ts"],"sourcesContent":["import { Middleware, type Next } from '@aomex/core';\nimport assert from 'node:assert';\nimport type { NonReadonly } from '@aomex/helper';\nimport type { Argv } from 'yargs';\nimport type { ConsoleContext } from '../app/context';\nimport { ShowHelp, ShowHelpProps } from '../middleware/showHelp';\n\nexport type YargsInstance = Argv;\n\ndeclare module '@aomex/core' {\n export interface MiddlewarePlatform {\n readonly console: <Props extends object = object>(\n fn: (ctx: NonReadonly<Props> & ConsoleContext, next: Next) => any,\n ) => ConsoleMiddleware<Props>;\n readonly help: <Props extends object = object>(\n fn: (\n ctx: NonReadonly<Props> & ShowHelpProps & ConsoleContext,\n next: Next,\n ) => any,\n ) => HelpMiddleware<object>;\n }\n}\n\nexport class ConsoleMiddleware<\n Props extends object = object,\n> extends Middleware<Props> {\n protected declare _console_middleware_: 'console-middleware';\n\n constructor(\n fn: (ctx: NonReadonly<Props> & ConsoleContext, next: Next) => any,\n ) {\n super(fn);\n }\n\n public toHelp(yargs: YargsInstance): void {\n assert(yargs);\n }\n}\n\nexport class HelpMiddleware<\n Props extends object = object,\n> extends ConsoleMiddleware<Props> {\n constructor(\n fn: (\n ctx: NonReadonly<Props> & ShowHelpProps & ConsoleContext,\n next: Next,\n ) => any,\n ) {\n super((ctx, next) => {\n return (ctx as unknown as ShowHelpProps).cli instanceof ShowHelp\n ? fn(ctx as any, next)\n : next();\n });\n }\n}\n\nMiddleware.register('console', ConsoleMiddleware);\nMiddleware.register('help', HelpMiddleware);\n","import { compose, Middleware, middleware } from '@aomex/core';\nimport yargs, { type Argv } from 'yargs';\n\nimport { scriptName, version } from '../info';\n\nexport interface ShowHelpProps {\n cli: ShowHelp;\n}\n\nexport class ShowHelp {\n constructor(\n public readonly status: 'show-all' | 'show-detail',\n public readonly yargs: Argv,\n ) {}\n}\n\nexport const showHelp = (middlewareList: Middleware[]) => {\n const composeFn = compose(middlewareList);\n\n return middleware.console<ShowHelpProps>(async (ctx, next) => {\n const {\n request: { options, command },\n response,\n } = ctx;\n\n if (command === '') {\n response.commandMatched = true;\n if (options['version'] || options['v']) {\n console.log(version);\n } else {\n const cli = yargs([])\n .scriptName(scriptName)\n .usage(`${scriptName} [command] [options] [--help|-h]`)\n .describe('version', `Show ${scriptName} version number`)\n .alias('v', 'version')\n .alias('h', 'help');\n ctx.cli = new ShowHelp('show-all', cli);\n await composeFn(ctx);\n cli.showHelp('log');\n }\n return;\n }\n\n if (options['help'] || options['h']) {\n const cli = yargs([]).scriptName(scriptName).version(false).help(false);\n ctx.cli = new ShowHelp('show-detail', cli);\n\n await composeFn(ctx);\n\n if (!response.commandMatched) {\n throw new Error(`Unable to find usage of command \"${command}\"`);\n }\n\n cli\n .alias('help', 'h')\n .describe('help', `Show help for command \"${command}\"`)\n .showHelp('log');\n return;\n }\n\n return next();\n });\n};\n","export const version = '{{#version}}';\nexport const scriptName = 'aomex';\n","import { Chain, PureMiddlewareToken } from '@aomex/core';\nimport type { ConsoleMiddleware } from './middleware';\n\ndeclare module '@aomex/core' {\n export interface ChainPlatform {\n readonly console: ConsoleChain;\n }\n}\n\nexport type ConsoleMiddlewareToken<P extends object = object> =\n | ConsoleChain<P>\n | ConsoleMiddleware<P>\n | PureMiddlewareToken<P>;\n\nexport class ConsoleChain<Props extends object = object> extends Chain<Props> {\n protected declare _console_chain_: 'console-chain';\n\n declare mount: {\n <P extends object>(\n middleware: ConsoleMiddlewareToken<P> | null,\n ): ConsoleChain<Props & P>;\n };\n}\n\nChain.register('console', ConsoleChain);\n","import type { ConsoleApp } from './app';\nimport type { ConsoleRequest } from './request';\nimport type { ConsoleResponse } from './response';\n\nexport class ConsoleContext {\n constructor(\n public readonly app: ConsoleApp,\n public readonly request: ConsoleRequest,\n public readonly response: ConsoleResponse,\n ) {}\n}\n","import EventEmitter from 'node:events';\nimport { EOL } from 'node:os';\nimport { hideBin } from 'yargs/helpers';\nimport { Chain, compose } from '@aomex/core';\nimport { ConsoleRequest } from './request';\nimport { ConsoleResponse } from './response';\nimport { ConsoleContext } from './context';\nimport type { ConsoleMiddlewareToken } from '../override/chain';\nimport { showHelp } from '../middleware/showHelp';\nimport { HelpMiddleware } from '../override';\nimport { chalk } from '@aomex/helper';\n\nexport interface ConsoleAppOption {}\n\nexport class ConsoleApp extends EventEmitter {\n public readonly chainPoints: string[] = [];\n protected running: boolean = false;\n protected readonly tokenList: ConsoleMiddlewareToken[] = [];\n\n constructor(_options: ConsoleAppOption = {}) {\n super();\n }\n\n /**\n * 执行命令。如果不传参数,则自动从`process.argv`中获取\n */\n public async run(...commands: string[]): Promise<void> {\n if (this.running) {\n throw new Error('Call \"app.run()\" multiple times at same time');\n }\n\n this.running = true;\n const request = new ConsoleRequest(\n this,\n commands.length ? commands : hideBin(process.argv),\n );\n const response = new ConsoleResponse(this);\n const ctx = new ConsoleContext(this, request, response);\n\n if (!this.listenerCount('error')) {\n this.on('error', this.log);\n }\n\n try {\n const middlewareList = Chain.flatten(this.tokenList);\n const helps = middlewareList.filter(\n (item) => item instanceof HelpMiddleware,\n );\n const normals = middlewareList.filter(\n (item) => !(item instanceof HelpMiddleware),\n );\n\n await compose([showHelp(helps), ...normals])(ctx);\n if (!response.commandMatched) {\n throw new Error(`Command \"${request.command}\" is not found`);\n }\n } catch (e) {\n this.emit('error', e);\n throw e;\n } finally {\n this.running = false;\n }\n }\n\n public log(err: Error) {\n const stack = (err.stack || err.toString())\n .split(EOL)\n .map((item) => ' ' + item);\n console.error(\n ['', chalk.red(stack.shift()), stack.join(EOL), ''].join(EOL),\n );\n }\n\n public mount(middleware: ConsoleMiddlewareToken): void {\n if (middleware instanceof Chain) {\n this.chainPoints.push(Chain.createPoint(middleware));\n }\n this.tokenList.push(middleware);\n }\n}\n","import parse from 'yargs-parser';\nimport type { ConsoleApp } from './app';\n\nexport class ConsoleRequest {\n public readonly options: Record<string, unknown>;\n public readonly command: string;\n\n constructor(public readonly app: ConsoleApp, public readonly argv: string[]) {\n const { _: commands, ...query } = parse(argv);\n this.options = query;\n this.command = String(commands[0] || '');\n }\n}\n","import type { ConsoleApp } from './app';\n\nexport class ConsoleResponse {\n public commandMatched: boolean = false;\n\n constructor(public readonly app: ConsoleApp) {}\n}\n","import type { Options as YargsOptions } from 'yargs';\nimport parse from 'yargs-parser';\nimport { validate, Validator, OpenAPI } from '@aomex/core';\nimport { ConsoleMiddleware, YargsInstance } from '../override';\n\nexport class ConsoleOptionMiddleware<\n Props extends { [key: string]: Validator },\n> extends ConsoleMiddleware<{\n readonly options: { [K in keyof Props]: Validator.Infer<Props[K]> };\n}> {\n constructor(\n protected readonly props: Props,\n protected readonly alias?: { [key: string]: string | string[] },\n ) {\n super(async (ctx, next) => {\n let options = ctx.request.options;\n\n if (alias && Object.keys(alias).length) {\n const { _, ...rawOptions } = parse(ctx.request.argv, {\n alias,\n });\n options = rawOptions;\n }\n\n ctx.options = await validate(options, props, { throwIfError: true });\n return next();\n });\n }\n\n public override toHelp(yargs: YargsInstance): void {\n const aliases = this.alias || {};\n\n for (const [key, validator] of Object.entries(this.props)) {\n const docs = Validator.toDocument(validator);\n const schema = docs.schema as OpenAPI.SchemaObject | undefined;\n const defaultValue = schema?.default;\n let dateType: YargsOptions['type'];\n\n switch (schema?.type) {\n case 'array':\n dateType = 'array';\n break;\n case 'integer':\n case 'number':\n dateType = 'number';\n break;\n case 'boolean':\n dateType = 'boolean';\n break;\n case 'string':\n // 命令行只能传递字符串,因此如果有object的规则那也是需要指定`parseFromString()`\n case 'object':\n dateType = 'string';\n break;\n }\n\n yargs.option(key, {\n alias: aliases[key],\n description: schema?.description,\n default: defaultValue,\n deprecated: docs.deprecated,\n type: dateType,\n });\n }\n }\n}\n\n/**\n * 验证控制台命令的传入参数,同时可以设置参数别名\n *\n * ```typescript\n * export const commander = new Commander();\n *\n * commander.create('my/schedule', {\n * slots: [\n * options({\n * id: rule.int(),\n * date: rule.datetime('YYYY-MM-DD'),\n * }, {\n * date: ['d'], // 传参形式: --date=xxx 或者 -d=xxx\n * });\n * ],\n * action: async (ctx) => {\n * console.log(ctx.options);\n * }\n * });\n * ```\n *\n */\nexport const options = <\n T extends { [key: string]: P },\n P extends Validator,\n Alias extends keyof T,\n>(\n fields: T,\n alias?: { [key in Alias]: string | string[] },\n) => new ConsoleOptionMiddleware<T>(fields, alias);\n"],"mappings":";AAAA,SAAS,cAAAA,mBAA6B;AACtC,OAAO,YAAY;;;ACDnB,SAAS,SAAqB,kBAAkB;AAChD,OAAO,WAA0B;;;ACD1B,IAAM,UAAU;AAChB,IAAM,aAAa;;;ADQnB,IAAM,WAAN,MAAe;AAAA,EACpB,YACkB,QACAC,QAChB;AAFgB;AACA,iBAAAA;AAAA,EACf;AACL;AAEO,IAAM,WAAW,CAAC,mBAAiC;AACxD,QAAM,YAAY,QAAQ,cAA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,OAAO,KAAK,SAAS;AACzB,UAAIC,WAAU,IAAI,QAAQ;AAE1B,UAAI,SAAS,OAAO,KAAK,KAAK,EAAE,QAAQ;AACtC,cAAM,EAAE,GAAG,GAAG,WAAW,IAAIC,OAAM,IAAI,QAAQ,MAAM;AAAA,UACnD;AAAA,QACF,CAAC;AACD,QAAAD,WAAU;AAAA,MACZ;AAEA,UAAI,UAAU,MAAM,SAASA,UAAS,OAAO,EAAE,cAAc,KAAK,CAAC;AACnE,aAAO,KAAK;AAAA,IACd,CAAC;AAfkB;AACA;AAAA,EAerB;AAAA,EAEgB,OAAOE,QAA4B;AACjD,UAAM,UAAU,KAAK,SAAS,CAAC;AAE/B,eAAW,CAAC,KAAK,SAAS,KAAK,OAAO,QAAQ,KAAK,KAAK,GAAG;AACzD,YAAM,OAAO,UAAU,WAAW,SAAS;AAC3C,YAAM,SAAS,KAAK;AACpB,YAAM,eAAe,QAAQ;AAC7B,UAAI;AAEJ,cAAQ,QAAQ,MAAM;AAAA,QACpB,KAAK;AACH,qBAAW;AACX;AAAA,QACF,KAAK;AAAA,QACL,KAAK;AACH,qBAAW;AACX;AAAA,QACF,KAAK;AACH,qBAAW;AACX;AAAA,QACF,KAAK;AAAA,QAEL,KAAK;AACH,qBAAW;AACX;AAAA,MACJ;AAEA,MAAAA,OAAM,OAAO,KAAK;AAAA,QAChB,OAAO,QAAQ,GAAG;AAAA,QAClB,aAAa,QAAQ;AAAA,QACrB,SAAS;AAAA,QACT,YAAY,KAAK;AAAA,QACjB,MAAM;AAAA,MACR,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAwBO,IAAM,UAAU,CAKrB,QACA,UACG,IAAI,wBAA2B,QAAQ,KAAK;","names":["Middleware","yargs","options","Middleware","yargs","Chain","compose","Chain","compose","middleware","parse","options","parse","yargs"]}
|
|
1
|
+
{"version":3,"sources":["../src/override/middleware.ts","../src/middleware/showHelp.ts","../src/meta.ts","../src/override/chain.ts","../src/app/context.ts","../src/app/app.ts","../src/app/request.ts","../src/app/response.ts","../src/middleware/options.ts","../src/define-config.ts"],"sourcesContent":["import { Middleware, type Next } from '@aomex/core';\nimport assert from 'node:assert';\nimport type { NonReadonly } from '@aomex/utility';\nimport type { Argv } from 'yargs';\nimport type { ConsoleContext } from '../app/context';\nimport { ShowHelp, ShowHelpProps } from '../middleware/showHelp';\n\nexport type YargsInstance = Argv;\n\ndeclare module '@aomex/core' {\n export interface MiddlewarePlatform {\n readonly console: <Props extends object = object>(\n fn: (ctx: NonReadonly<Props> & ConsoleContext, next: Next) => any,\n ) => ConsoleMiddleware<Props>;\n readonly help: <Props extends object = object>(\n fn: (\n ctx: NonReadonly<Props> & ShowHelpProps & ConsoleContext,\n next: Next,\n ) => any,\n ) => HelpMiddleware<object>;\n }\n}\n\nexport class ConsoleMiddleware<\n Props extends object = object,\n> extends Middleware<Props> {\n protected declare _console_middleware_: 'console-middleware';\n\n constructor(\n fn: (ctx: NonReadonly<Props> & ConsoleContext, next: Next) => any,\n ) {\n super(fn);\n }\n\n public toHelp(yargs: YargsInstance): void {\n assert(yargs);\n }\n}\n\nexport class HelpMiddleware<\n Props extends object = object,\n> extends ConsoleMiddleware<Props> {\n constructor(\n fn: (\n ctx: NonReadonly<Props> & ShowHelpProps & ConsoleContext,\n next: Next,\n ) => any,\n ) {\n super((ctx, next) => {\n return (ctx as unknown as ShowHelpProps).cli instanceof ShowHelp\n ? fn(ctx as any, next)\n : next();\n });\n }\n}\n\nMiddleware.register('console', ConsoleMiddleware);\nMiddleware.register('help', HelpMiddleware);\n","import { compose, Middleware, middleware, Next } from '@aomex/core';\nimport yargs, { type Argv } from 'yargs';\nimport type { ConsoleContext } from '../app';\n\nimport { scriptName, version } from '../meta';\n\nexport interface ShowHelpProps {\n cli: ShowHelp;\n}\n\nexport class ShowHelp {\n constructor(\n protected readonly ctx: ConsoleContext,\n protected readonly status: 'all' | 'detail',\n protected readonly yargs: Argv,\n ) {}\n\n async config({\n next,\n all,\n detail,\n detailCommand,\n }: {\n all: (yargs: Argv) => Promise<void> | void;\n detail: (yargs: Argv) => Promise<void> | void;\n detailCommand: string | (() => boolean);\n next: Next;\n }) {\n if (this.status === 'all') {\n await all(this.yargs);\n return next();\n } else if (this.status === 'detail') {\n if (typeof detailCommand === 'string') {\n if (detailCommand !== this.ctx.request.command) return next();\n } else {\n if (!detailCommand()) {\n return next();\n }\n }\n\n await detail(this.yargs);\n this.ctx.response.commandMatched = true;\n }\n }\n}\n\nexport const showHelp = (middlewareList: Middleware[]) => {\n const composeFn = compose(middlewareList);\n\n return middleware.console<ShowHelpProps>(async (ctx, next) => {\n const {\n request: { options, command },\n response,\n } = ctx;\n\n if (command === '') {\n response.commandMatched = true;\n if (options['version'] || options['v']) {\n console.log(version);\n } else {\n const cli = yargs([])\n .scriptName(scriptName)\n .usage(`${scriptName} [command] [options] [--help|-h]`)\n .describe('version', `Show ${scriptName} version number`)\n .alias('v', 'version')\n .alias('h', 'help');\n ctx.cli = new ShowHelp(ctx, 'all', cli);\n await composeFn(ctx);\n cli.showHelp('log');\n }\n return;\n }\n\n if (options['help'] || options['h']) {\n const cli = yargs([]).scriptName(scriptName).version(false).help(false);\n ctx.cli = new ShowHelp(ctx, 'detail', cli);\n\n await composeFn(ctx);\n\n if (!response.commandMatched) {\n throw new Error(`Unable to find usage of command \"${command}\"`);\n }\n\n cli\n .alias('help', 'h')\n .describe('help', `Show help for command \"${command}\"`)\n .showHelp('log');\n return;\n }\n\n return next();\n });\n};\n","export const version = '{{#version}}';\nexport const scriptName = 'aomex';\n","import { Chain, PureMiddlewareToken } from '@aomex/core';\nimport type { ConsoleMiddleware } from './middleware';\n\ndeclare module '@aomex/core' {\n export interface ChainPlatform {\n readonly console: ConsoleChain;\n }\n}\n\nexport type ConsoleMiddlewareToken<P extends object = object> =\n | ConsoleChain<P>\n | ConsoleMiddleware<P>\n | PureMiddlewareToken<P>;\n\nexport class ConsoleChain<Props extends object = object> extends Chain<Props> {\n protected declare _console_chain_: 'console-chain';\n\n declare mount: {\n <P extends object>(\n middleware: ConsoleMiddlewareToken<P> | null,\n ): ConsoleChain<Props & P>;\n };\n}\n\nChain.register('console', ConsoleChain);\n","import type { ConsoleApp } from './app';\nimport type { ConsoleRequest } from './request';\nimport type { ConsoleResponse } from './response';\n\nexport class ConsoleContext {\n constructor(\n public readonly app: ConsoleApp,\n public readonly request: ConsoleRequest,\n public readonly response: ConsoleResponse,\n ) {}\n}\n","import EventEmitter from 'node:events';\nimport { EOL } from 'node:os';\nimport { hideBin } from 'yargs/helpers';\nimport { Chain, compose } from '@aomex/core';\nimport { ConsoleRequest } from './request';\nimport { ConsoleResponse } from './response';\nimport { ConsoleContext } from './context';\nimport type { ConsoleMiddlewareToken } from '../override/chain';\nimport { showHelp } from '../middleware/showHelp';\nimport { HelpMiddleware } from '../override';\nimport { chalk } from '@aomex/utility';\n\nexport interface ConsoleAppOption {\n silent?: boolean;\n}\n\nexport class ConsoleApp extends EventEmitter {\n public readonly chainPoints: string[] = [];\n protected level: number = 0;\n protected readonly tokenList: ConsoleMiddlewareToken[] = [];\n\n constructor(protected readonly options: ConsoleAppOption = {}) {\n super();\n }\n\n /**\n * Run command. Builtin `process.argv` will be used by default until you input one or more arguments.\n * @see process.argv\n */\n public async run(...commands: string[]): Promise<void> {\n const currentLevel = this.level++;\n const request = new ConsoleRequest(\n this,\n commands.length ? commands : hideBin(process.argv),\n );\n const response = new ConsoleResponse(this);\n const ctx = new ConsoleContext(this, request, response);\n\n // At least one listener is required before emit.\n if (!this.listenerCount('error')) {\n this.on('error', this.log.bind(this));\n }\n\n try {\n const middlewareList = Chain.flatten(this.tokenList);\n const helps = middlewareList.filter(\n (item) => item instanceof HelpMiddleware,\n );\n const normals = middlewareList.filter(\n (item) => !(item instanceof HelpMiddleware),\n );\n\n await compose([showHelp(helps), ...normals])(ctx);\n if (!response.commandMatched) {\n throw new Error(`Command \"${request.command}\" is not found`);\n }\n } catch (e) {\n currentLevel === 0 && this.emit('error', e);\n throw e;\n } finally {\n --this.level;\n }\n }\n\n public log(err: Error) {\n if (this.options.silent) return;\n const stack = (err.stack || err.toString())\n .split(EOL)\n .map((item) => ' ' + item);\n console.error(\n ['', chalk.red(stack.shift()), stack.join(EOL), ''].join(EOL),\n );\n }\n\n public mount(middleware: ConsoleMiddlewareToken | null): void {\n if (middleware === null) return;\n if (middleware instanceof Chain) {\n this.chainPoints.push(Chain.createSplitPoint(middleware));\n }\n this.tokenList.push(middleware);\n }\n}\n","import parse from 'yargs-parser';\nimport type { ConsoleApp } from './app';\n\nexport class ConsoleRequest {\n public readonly options: Record<string, unknown>;\n public readonly command: string;\n\n constructor(public readonly app: ConsoleApp, public readonly argv: string[]) {\n const { _: commands, ...query } = parse(argv);\n this.options = query;\n this.command = String(commands[0] || '');\n }\n}\n","import type { ConsoleApp } from './app';\n\nexport class ConsoleResponse {\n public commandMatched: boolean = false;\n\n constructor(public readonly app: ConsoleApp) {}\n}\n","import type { Options as YargsOptions } from 'yargs';\nimport parse from 'yargs-parser';\nimport { validate, Validator, OpenAPI } from '@aomex/core';\nimport { ConsoleMiddleware, YargsInstance } from '../override';\n\nexport class ConsoleOptionMiddleware<\n Props extends { [key: string]: Validator },\n> extends ConsoleMiddleware<{\n readonly options: { [K in keyof Props]: Validator.Infer<Props[K]> };\n}> {\n constructor(\n protected readonly props: Props,\n protected readonly alias?: { [key: string]: string | string[] },\n ) {\n super(async (ctx, next) => {\n let options = ctx.request.options;\n\n if (alias && Object.keys(alias).length) {\n const { _, ...rawOptions } = parse(ctx.request.argv, {\n alias,\n });\n options = rawOptions;\n }\n\n ctx.options = await validate(options, props, { throwIfError: true });\n return next();\n });\n }\n\n public override toHelp(yargs: YargsInstance): void {\n const aliases = this.alias || {};\n\n for (const [key, validator] of Object.entries(this.props)) {\n const docs = Validator.toDocument(validator);\n const schema = docs.schema as OpenAPI.SchemaObject | undefined;\n const defaultValue = schema?.default;\n let dateType: YargsOptions['type'];\n\n switch (schema?.type) {\n case 'array':\n dateType = 'array';\n break;\n case 'integer':\n case 'number':\n dateType = 'number';\n break;\n case 'boolean':\n dateType = 'boolean';\n break;\n case 'string':\n /**\n * Object can be only parsed from string on console.\n * @see ObjectValidator.parseFromString()\n */\n case 'object':\n dateType = 'string';\n break;\n }\n\n yargs.option(key, {\n alias: aliases[key],\n description: docs.description,\n default: defaultValue,\n deprecated: docs.deprecated,\n type: dateType,\n });\n }\n }\n}\n\n/**\n * Validate command-line options, and make type safe.\n *\n * ```typescript\n * export const commander = new Commander();\n *\n * commander.create('my/schedule', {\n * slots: [\n * options({\n * id: rule.int(),\n * date: rule.datetime('YYYY-MM-DD'),\n * }, {\n * date: ['d'], // alias --date or -d\n * });\n * ],\n * action: async (ctx) => {\n * console.log(ctx.options);\n * }\n * });\n * ```\n *\n */\nexport const options = <\n T extends { [key: string]: P },\n P extends Validator,\n Alias extends keyof T,\n>(\n fields: T,\n alias?: { [key in Alias]: string | string[] },\n) => new ConsoleOptionMiddleware<T>(fields, alias);\n","export interface Config {\n cliEntry: {\n /**\n * Entry file by each environment\n * @see process.env.NODE_ENV\n */\n [NODE_ENV: string]: string | undefined;\n /**\n * Fallback to `default` if NODE_ENV doesn't match specific file.\n * @see process.env.NODE_ENV\n */\n default?: string;\n };\n}\n\nexport const defineConfig = (config: Config) => config;\n"],"mappings":";AAAA,SAAS,cAAAA,mBAA6B;AACtC,OAAO,YAAY;;;ACDnB,SAAS,SAAqB,kBAAwB;AACtD,OAAO,WAA0B;;;ACD1B,IAAM,UAAU;AAChB,IAAM,aAAa;;;ADSnB,IAAM,WAAN,MAAe;AAAA,EACpB,YACqB,KACA,QACAC,QACnB;AAHmB;AACA;AACA,iBAAAA;AAAA,EAClB;AAAA,EAEH,MAAM,OAAO;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAKG;AACD,QAAI,KAAK,WAAW,OAAO;AACzB,YAAM,IAAI,KAAK,KAAK;AACpB,aAAO,KAAK;AAAA,IACd,WAAW,KAAK,WAAW,UAAU;AACnC,U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QAChB,OAAO,QAAQ,GAAG;AAAA,QAClB,aAAa,KAAK;AAAA,QAClB,SAAS;AAAA,QACT,YAAY,KAAK;AAAA,QACjB,MAAM;AAAA,MACR,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAwBO,IAAM,UAAU,CAKrB,QACA,UACG,IAAI,wBAA2B,QAAQ,KAAK;;;ACpF1C,IAAM,eAAe,CAAC,WAAmB;","names":["Middleware","yargs","options","Middleware","yargs","Chain","compose","options","Chain","compose","middleware","parse","options","parse","yargs"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aomex/console",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.7",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -9,14 +9,10 @@
|
|
|
9
9
|
"types": "./dist/index.d.ts",
|
|
10
10
|
"import": "./dist/index.js"
|
|
11
11
|
},
|
|
12
|
-
"./config": {
|
|
13
|
-
"types": "./dist/cli/define-config.d.ts",
|
|
14
|
-
"import": "./dist/cli/define-config.js"
|
|
15
|
-
},
|
|
16
12
|
"./package.json": "./package.json"
|
|
17
13
|
},
|
|
18
14
|
"bin": {
|
|
19
|
-
"aomex": "dist/
|
|
15
|
+
"aomex": "dist/bin.js"
|
|
20
16
|
},
|
|
21
17
|
"publishConfig": {
|
|
22
18
|
"access": "public"
|
|
@@ -33,16 +29,17 @@
|
|
|
33
29
|
"homepage": "https://aomex.js.org",
|
|
34
30
|
"license": "MIT",
|
|
35
31
|
"peerDependencies": {
|
|
36
|
-
"@aomex/core": "^0.0.
|
|
32
|
+
"@aomex/core": "^0.0.7"
|
|
37
33
|
},
|
|
38
34
|
"dependencies": {
|
|
39
|
-
"@aomex/
|
|
40
|
-
"
|
|
41
|
-
"
|
|
35
|
+
"@aomex/file-parser": "^0.0.4",
|
|
36
|
+
"@aomex/utility": "^0.0.4",
|
|
37
|
+
"ts-node": "^10.9.1",
|
|
38
|
+
"yargs": "^17.7.1",
|
|
42
39
|
"yargs-parser": "^21.1.1"
|
|
43
40
|
},
|
|
44
41
|
"devDependencies": {
|
|
45
|
-
"@aomex/core": "^0.0.
|
|
42
|
+
"@aomex/core": "^0.0.7",
|
|
46
43
|
"@types/yargs": "^17.0.22",
|
|
47
44
|
"@types/yargs-parser": "^21.0.0",
|
|
48
45
|
"read-pkg-up": "^9.1.0"
|
package/src/bin.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
#!/usr/bin/env -S ts-node-esm --transpileOnly --experimentalSpecifierResolution=node
|
|
2
|
+
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { existsSync, statSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { hideBin } from 'yargs/helpers';
|
|
7
|
+
import { fileToModules, pathToFiles } from '@aomex/file-parser';
|
|
8
|
+
import { chalk } from '@aomex/utility';
|
|
9
|
+
import type { Config } from './define-config';
|
|
10
|
+
|
|
11
|
+
{
|
|
12
|
+
const defaultConfig: Config = {
|
|
13
|
+
cliEntry: {
|
|
14
|
+
production: './src/cli.js',
|
|
15
|
+
default: './src/cli.ts',
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const args = hideBin(process.argv);
|
|
20
|
+
if (args.length === 1 && args[0] === '--init') {
|
|
21
|
+
const file = path.resolve('aomex.config.ts');
|
|
22
|
+
|
|
23
|
+
if (existsSync(file)) {
|
|
24
|
+
console.warn(
|
|
25
|
+
chalk.yellow('Your configuration file had been generated already!'),
|
|
26
|
+
);
|
|
27
|
+
process.exit(0);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
writeFileSync(
|
|
31
|
+
file,
|
|
32
|
+
`import { defineConfig } from '@aomex/console';
|
|
33
|
+
|
|
34
|
+
export default defineConfig(${JSON.stringify(defaultConfig, null, 2)});
|
|
35
|
+
`,
|
|
36
|
+
);
|
|
37
|
+
console.info(
|
|
38
|
+
'Configuration file has been generated successfully: ' +
|
|
39
|
+
chalk.blueBright(file),
|
|
40
|
+
);
|
|
41
|
+
process.exit(0);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const env = process.env['NODE_ENV'] || 'development';
|
|
46
|
+
const parseEnv = (config: any) => {
|
|
47
|
+
if (!config) return null;
|
|
48
|
+
if (Object.hasOwn(config, env)) return config[env];
|
|
49
|
+
if (Object.hasOwn(config, 'default')) return config['default'];
|
|
50
|
+
return null;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const files = await pathToFiles('./aomex.config{.ts,.js}');
|
|
54
|
+
let config: Config | undefined;
|
|
55
|
+
|
|
56
|
+
for (const file of files) {
|
|
57
|
+
const configs = await fileToModules<Config>(
|
|
58
|
+
[file],
|
|
59
|
+
(item) => typeof item === 'object',
|
|
60
|
+
);
|
|
61
|
+
if (configs.length) {
|
|
62
|
+
config = configs[0]!;
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (!config) {
|
|
68
|
+
console.error(
|
|
69
|
+
`Aomex doesn't find a configuration file matched pattern "aomex.config.{ts|js}", would you please execute the initialize command below at first?\n\n${chalk.greenBright(
|
|
70
|
+
'npx aomex --init',
|
|
71
|
+
)}\n`,
|
|
72
|
+
);
|
|
73
|
+
process.exit(1);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let cliEntry: string = parseEnv(config.cliEntry) || '';
|
|
77
|
+
if (cliEntry) {
|
|
78
|
+
cliEntry = path.resolve(cliEntry);
|
|
79
|
+
}
|
|
80
|
+
if (!cliEntry || !statSync(cliEntry).isFile()) {
|
|
81
|
+
console.error(`The given entry file "${cliEntry}" is not found`);
|
|
82
|
+
process.exit(1);
|
|
83
|
+
}
|
|
84
|
+
await import(pathToFileURL(cliEntry).toString());
|
package/dist/cli/bin.d.ts
DELETED
package/dist/cli/bin.js
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
// src/cli/bin.ts
|
|
2
|
-
import { cosmiconfigSync } from "cosmiconfig";
|
|
3
|
-
import { pathToFileURL } from "url";
|
|
4
|
-
var env = process.env["NODE_ENV"] || "development";
|
|
5
|
-
var parseEnv = (config2) => {
|
|
6
|
-
if (!config2)
|
|
7
|
-
return null;
|
|
8
|
-
if (Object.hasOwn(config2, env))
|
|
9
|
-
return config2[env];
|
|
10
|
-
if (Object.hasOwn(config2, "default"))
|
|
11
|
-
return config2["default"];
|
|
12
|
-
return null;
|
|
13
|
-
};
|
|
14
|
-
var explorer = cosmiconfigSync("aomex");
|
|
15
|
-
var result = explorer.search() || {
|
|
16
|
-
config: {}
|
|
17
|
-
};
|
|
18
|
-
var config = result.config;
|
|
19
|
-
var cliEntry = parseEnv(config.cliEntry);
|
|
20
|
-
await import(pathToFileURL(cliEntry).toString());
|
|
21
|
-
//# sourceMappingURL=bin.js.map
|
package/dist/cli/bin.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/bin.ts"],"sourcesContent":["import { cosmiconfigSync } from 'cosmiconfig';\nimport { pathToFileURL } from 'url';\nimport type { Config } from './define-config';\n\nconst env = process.env['NODE_ENV'] || 'development';\nconst parseEnv = (config: any) => {\n if (!config) return null;\n if (Object.hasOwn(config, env)) return config[env];\n if (Object.hasOwn(config, 'default')) return config['default'];\n return null;\n};\n\nconst explorer = cosmiconfigSync('aomex');\nconst result = explorer.search() || {\n config: {},\n};\nconst config: Config = result.config;\n\nconst cliEntry: string = parseEnv(config.cliEntry);\nawait import(pathToFileURL(cliEntry).toString());\n"],"mappings":";AAAA,SAAS,uBAAuB;AAChC,SAAS,qBAAqB;AAG9B,IAAM,MAAM,QAAQ,IAAI,UAAU,KAAK;AACvC,IAAM,WAAW,CAACA,YAAgB;AAChC,MAAI,CAACA;AAAQ,WAAO;AACpB,MAAI,OAAO,OAAOA,SAAQ,GAAG;AAAG,WAAOA,QAAO,GAAG;AACjD,MAAI,OAAO,OAAOA,SAAQ,SAAS;AAAG,WAAOA,QAAO,SAAS;AAC7D,SAAO;AACT;AAEA,IAAM,WAAW,gBAAgB,OAAO;AACxC,IAAM,SAAS,SAAS,OAAO,KAAK;AAAA,EAClC,QAAQ,CAAC;AACX;AACA,IAAM,SAAiB,OAAO;AAE9B,IAAM,WAAmB,SAAS,OAAO,QAAQ;AACjD,MAAM,OAAO,cAAc,QAAQ,EAAE,SAAS;","names":["config"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/define-config.ts"],"sourcesContent":["export interface Config {\n cliEntry: {\n [NODE_ENV: string]: string | undefined;\n default?: string;\n };\n}\n\nexport const defineConfig = (config: Config) => config;\n"],"mappings":";AAOO,IAAM,eAAe,CAAC,WAAmB;","names":[]}
|
package/src/cli/bin.ts
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { cosmiconfigSync } from 'cosmiconfig';
|
|
2
|
-
import { pathToFileURL } from 'url';
|
|
3
|
-
import type { Config } from './define-config';
|
|
4
|
-
|
|
5
|
-
const env = process.env['NODE_ENV'] || 'development';
|
|
6
|
-
const parseEnv = (config: any) => {
|
|
7
|
-
if (!config) return null;
|
|
8
|
-
if (Object.hasOwn(config, env)) return config[env];
|
|
9
|
-
if (Object.hasOwn(config, 'default')) return config['default'];
|
|
10
|
-
return null;
|
|
11
|
-
};
|
|
12
|
-
|
|
13
|
-
const explorer = cosmiconfigSync('aomex');
|
|
14
|
-
const result = explorer.search() || {
|
|
15
|
-
config: {},
|
|
16
|
-
};
|
|
17
|
-
const config: Config = result.config;
|
|
18
|
-
|
|
19
|
-
const cliEntry: string = parseEnv(config.cliEntry);
|
|
20
|
-
await import(pathToFileURL(cliEntry).toString());
|