@aomex/console 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +21 -0
- package/dist/cli/bin.js.map +1 -0
- package/dist/cli/define-config.d.ts +9 -0
- package/dist/cli/define-config.js +6 -0
- package/dist/cli/define-config.js.map +1 -0
- package/dist/index.d.ts +113 -0
- package/dist/index.js +217 -0
- package/dist/index.js.map +1 -0
- package/package.json +50 -0
- package/src/cli/bin.ts +20 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 geekact
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/cli/bin.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
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"]}
|
|
@@ -0,0 +1 @@
|
|
|
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/dist/index.d.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { Chain, PureMiddlewareToken, Next, Middleware, Validator, GetValidatorType } from '@aomex/core';
|
|
2
|
+
import { NonReadonly } from '@aomex/helper';
|
|
3
|
+
import { Argv } from 'yargs';
|
|
4
|
+
import EventEmitter from 'node:events';
|
|
5
|
+
|
|
6
|
+
declare module '@aomex/core' {
|
|
7
|
+
interface ChainPlatform {
|
|
8
|
+
readonly console: ConsoleChain;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
type ConsoleMiddlewareToken<P extends object = object> = ConsoleChain<P> | ConsoleMiddleware<P> | PureMiddlewareToken<P>;
|
|
12
|
+
declare class ConsoleChain<Props extends object = object> extends Chain<Props> {
|
|
13
|
+
protected _console_chain_: 'console-chain';
|
|
14
|
+
mount: {
|
|
15
|
+
<P extends object>(middleware: ConsoleMiddlewareToken<P> | null): ConsoleChain<Props & P>;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
declare class ConsoleApp extends EventEmitter {
|
|
20
|
+
protected running: boolean;
|
|
21
|
+
protected readonly middlewareList: ConsoleMiddlewareToken[];
|
|
22
|
+
run(...commands: string[]): Promise<void>;
|
|
23
|
+
log(err: Error): void;
|
|
24
|
+
mount(middleware: ConsoleMiddlewareToken): void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
declare class ConsoleRequest {
|
|
28
|
+
readonly app: ConsoleApp;
|
|
29
|
+
readonly argv: string[];
|
|
30
|
+
readonly query: Record<string, unknown>;
|
|
31
|
+
readonly command: string;
|
|
32
|
+
constructor(app: ConsoleApp, argv: string[]);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
declare class ConsoleResponse {
|
|
36
|
+
readonly app: ConsoleApp;
|
|
37
|
+
commandMatched: boolean;
|
|
38
|
+
constructor(app: ConsoleApp);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
declare class ConsoleContext {
|
|
42
|
+
readonly app: ConsoleApp;
|
|
43
|
+
readonly request: ConsoleRequest;
|
|
44
|
+
readonly response: ConsoleResponse;
|
|
45
|
+
constructor(app: ConsoleApp, request: ConsoleRequest, response: ConsoleResponse);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface ShowHelp {
|
|
49
|
+
cli: {
|
|
50
|
+
status: 'show-all' | 'show-detail';
|
|
51
|
+
yargs: Argv;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
type YargsInstance = Argv;
|
|
56
|
+
declare module '@aomex/core' {
|
|
57
|
+
interface MiddlewarePlatform {
|
|
58
|
+
readonly console: <Props extends object = object>(fn: (ctx: NonReadonly<Props> & ConsoleContext, next: Next) => any) => ConsoleMiddleware<Props>;
|
|
59
|
+
readonly help: <Props extends object = object>(fn: (ctx: NonReadonly<Props> & ShowHelp & ConsoleContext, next: Next) => any) => HelpMiddleware<object>;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
declare class ConsoleMiddleware<Props extends object = object> extends Middleware<Props> {
|
|
63
|
+
protected _console_middleware_: 'console-middleware';
|
|
64
|
+
toHelp(yargs: YargsInstance): void;
|
|
65
|
+
}
|
|
66
|
+
declare class HelpMiddleware<Props extends object = object> extends ConsoleMiddleware<Props> {
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
declare const version = "{{#version}}";
|
|
70
|
+
|
|
71
|
+
declare class ConsoleOptionMiddleware<Props extends {
|
|
72
|
+
[key: string]: Validator;
|
|
73
|
+
}> extends ConsoleMiddleware<{
|
|
74
|
+
readonly options: {
|
|
75
|
+
[K in keyof Props]: GetValidatorType<Props[K]>;
|
|
76
|
+
};
|
|
77
|
+
}> {
|
|
78
|
+
protected readonly props: Props;
|
|
79
|
+
protected readonly alias?: {
|
|
80
|
+
[key: string]: string | string[];
|
|
81
|
+
} | undefined;
|
|
82
|
+
constructor(props: Props, alias?: {
|
|
83
|
+
[key: string]: string | string[];
|
|
84
|
+
} | undefined);
|
|
85
|
+
toHelp(yargs: YargsInstance): void;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* 验证控制台命令的传入参数,同时可以设置参数别名
|
|
89
|
+
*
|
|
90
|
+
* ```typescript
|
|
91
|
+
* export const commander = new Commander();
|
|
92
|
+
*
|
|
93
|
+
* commander.create('my/schedule', {
|
|
94
|
+
* slots: [
|
|
95
|
+
* options({
|
|
96
|
+
* id: rule.int(),
|
|
97
|
+
* date: rule.datetime('YYYY-MM-DD'),
|
|
98
|
+
* }, {
|
|
99
|
+
* date: ['d'], // 传参形式: --date=xxx 或者 -d=xxx
|
|
100
|
+
* });
|
|
101
|
+
* ],
|
|
102
|
+
* action: async (ctx) => {
|
|
103
|
+
* console.log(ctx.options);
|
|
104
|
+
* }
|
|
105
|
+
* });
|
|
106
|
+
* ```
|
|
107
|
+
*
|
|
108
|
+
*/
|
|
109
|
+
declare const options: <T extends {
|
|
110
|
+
[key: string]: P;
|
|
111
|
+
}, P extends Validator<unknown>, Alias extends keyof T>(fields: T, alias?: { [key in Alias]: string | string[]; } | undefined) => ConsoleOptionMiddleware<T>;
|
|
112
|
+
|
|
113
|
+
export { ConsoleApp, ConsoleChain, ConsoleContext, ConsoleMiddleware, ConsoleMiddlewareToken, ConsoleOptionMiddleware, ConsoleRequest, ConsoleResponse, HelpMiddleware, YargsInstance, options, version };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
// src/override/middleware.ts
|
|
2
|
+
import { Middleware } from "@aomex/core";
|
|
3
|
+
import assert from "node:assert";
|
|
4
|
+
var ConsoleMiddleware = class extends Middleware {
|
|
5
|
+
toHelp(yargs2) {
|
|
6
|
+
assert(yargs2);
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
var HelpMiddleware = class extends ConsoleMiddleware {
|
|
10
|
+
};
|
|
11
|
+
Middleware.register("console", ConsoleMiddleware);
|
|
12
|
+
Middleware.register("help", HelpMiddleware);
|
|
13
|
+
|
|
14
|
+
// src/override/chain.ts
|
|
15
|
+
import { Chain } from "@aomex/core";
|
|
16
|
+
var ConsoleChain = class extends Chain {
|
|
17
|
+
};
|
|
18
|
+
Chain.register("console", ConsoleChain);
|
|
19
|
+
|
|
20
|
+
// src/app/context.ts
|
|
21
|
+
var ConsoleContext = class {
|
|
22
|
+
constructor(app, request, response) {
|
|
23
|
+
this.app = app;
|
|
24
|
+
this.request = request;
|
|
25
|
+
this.response = response;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
// src/app/app.ts
|
|
30
|
+
import EventEmitter from "node:events";
|
|
31
|
+
import { EOL } from "node:os";
|
|
32
|
+
import { hideBin } from "yargs/helpers";
|
|
33
|
+
import { Chain as Chain2, compose as compose2 } from "@aomex/core";
|
|
34
|
+
|
|
35
|
+
// src/app/request.ts
|
|
36
|
+
import parse from "yargs-parser";
|
|
37
|
+
var ConsoleRequest = class {
|
|
38
|
+
constructor(app, argv) {
|
|
39
|
+
this.app = app;
|
|
40
|
+
this.argv = argv;
|
|
41
|
+
const { _: commands, ...query } = parse(argv);
|
|
42
|
+
this.query = query;
|
|
43
|
+
this.command = String(commands[0] || "");
|
|
44
|
+
}
|
|
45
|
+
query;
|
|
46
|
+
command;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
// src/app/response.ts
|
|
50
|
+
var ConsoleResponse = class {
|
|
51
|
+
constructor(app) {
|
|
52
|
+
this.app = app;
|
|
53
|
+
}
|
|
54
|
+
commandMatched = false;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// src/middleware/showHelp.ts
|
|
58
|
+
import { compose, middleware } from "@aomex/core";
|
|
59
|
+
import yargs from "yargs";
|
|
60
|
+
|
|
61
|
+
// src/version.ts
|
|
62
|
+
var version = "0.0.0";
|
|
63
|
+
|
|
64
|
+
// src/middleware/showHelp.ts
|
|
65
|
+
var scriptName = "aomex";
|
|
66
|
+
var showHelp = (middlewareList) => {
|
|
67
|
+
const composeFn = compose(middlewareList);
|
|
68
|
+
return middleware.console(async (ctx, next) => {
|
|
69
|
+
const {
|
|
70
|
+
request: { query: options2, command },
|
|
71
|
+
response
|
|
72
|
+
} = ctx;
|
|
73
|
+
if (command === "") {
|
|
74
|
+
response.commandMatched = true;
|
|
75
|
+
if (options2["version"] || options2["v"]) {
|
|
76
|
+
console.log(version);
|
|
77
|
+
} else {
|
|
78
|
+
const cli = yargs([]).scriptName(scriptName).usage(`${scriptName} [command] [options] [--help|-h]`).describe("version", `Show ${scriptName} version number`).alias("v", "version").alias("h", "help");
|
|
79
|
+
ctx.cli = { status: "show-all", yargs: cli };
|
|
80
|
+
await composeFn(ctx);
|
|
81
|
+
cli.showHelp("log");
|
|
82
|
+
}
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
if (options2["help"] || options2["h"]) {
|
|
86
|
+
const cli = yargs([]).scriptName(scriptName).version(false).help(false);
|
|
87
|
+
ctx.cli = { status: "show-detail", yargs: cli };
|
|
88
|
+
await composeFn(ctx);
|
|
89
|
+
if (!response.commandMatched) {
|
|
90
|
+
throw new Error(`Unable to find usage of command "${command}"`);
|
|
91
|
+
}
|
|
92
|
+
cli.alias("help", "h").describe("help", `Show help for command "${command}"`).showHelp("log");
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
return next();
|
|
96
|
+
});
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
// src/app/app.ts
|
|
100
|
+
import { color } from "@aomex/helper";
|
|
101
|
+
var ConsoleApp = class extends EventEmitter {
|
|
102
|
+
running = false;
|
|
103
|
+
middlewareList = [];
|
|
104
|
+
async run(...commands) {
|
|
105
|
+
if (this.running) {
|
|
106
|
+
throw new Error("Call app.run() multiple times at same time");
|
|
107
|
+
}
|
|
108
|
+
this.running = true;
|
|
109
|
+
const request = new ConsoleRequest(
|
|
110
|
+
this,
|
|
111
|
+
commands.length ? commands : hideBin(process.argv)
|
|
112
|
+
);
|
|
113
|
+
const response = new ConsoleResponse(this);
|
|
114
|
+
const ctx = new ConsoleContext(this, request, response);
|
|
115
|
+
if (!this.listenerCount("error")) {
|
|
116
|
+
this.on("error", this.log);
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
const middlewareList = this.middlewareList.reduce(
|
|
120
|
+
(carry, item) => carry.concat(Chain2.flatten(item)),
|
|
121
|
+
[]
|
|
122
|
+
);
|
|
123
|
+
await compose2([
|
|
124
|
+
showHelp(
|
|
125
|
+
middlewareList.filter((item) => item instanceof HelpMiddleware)
|
|
126
|
+
),
|
|
127
|
+
...this.middlewareList.filter(
|
|
128
|
+
(item) => !(item instanceof HelpMiddleware)
|
|
129
|
+
)
|
|
130
|
+
])(ctx);
|
|
131
|
+
if (!response.commandMatched) {
|
|
132
|
+
throw new Error(`Command "${request.command}" is not matched`);
|
|
133
|
+
}
|
|
134
|
+
} catch (e) {
|
|
135
|
+
this.emit("error", e);
|
|
136
|
+
throw e;
|
|
137
|
+
} finally {
|
|
138
|
+
this.running = false;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
log(err) {
|
|
142
|
+
const stack = (err.stack || err.toString()).split(EOL).map((item) => " " + item);
|
|
143
|
+
console.error(
|
|
144
|
+
["", color.red(stack.shift()), stack.join(EOL), ""].join(EOL)
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
mount(middleware2) {
|
|
148
|
+
this.middlewareList.push(middleware2);
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// src/middleware/options.ts
|
|
153
|
+
import parse2 from "yargs-parser";
|
|
154
|
+
import { validate, Validator } from "@aomex/core";
|
|
155
|
+
var ConsoleOptionMiddleware = class extends ConsoleMiddleware {
|
|
156
|
+
constructor(props, alias) {
|
|
157
|
+
super(async (ctx, next) => {
|
|
158
|
+
let options2 = ctx.request.options;
|
|
159
|
+
if (alias && Object.keys(alias).length) {
|
|
160
|
+
const { _, ...rawOptions } = parse2(ctx.request.argv, {
|
|
161
|
+
alias
|
|
162
|
+
});
|
|
163
|
+
options2 = rawOptions;
|
|
164
|
+
}
|
|
165
|
+
ctx.options = await validate(options2, props, { throwIfError: true });
|
|
166
|
+
return next();
|
|
167
|
+
});
|
|
168
|
+
this.props = props;
|
|
169
|
+
this.alias = alias;
|
|
170
|
+
}
|
|
171
|
+
toHelp(yargs2) {
|
|
172
|
+
const aliases = this.alias || {};
|
|
173
|
+
for (const [key, validator] of Object.entries(this.props)) {
|
|
174
|
+
const docs = Validator.toDocument(validator);
|
|
175
|
+
const schema = docs.schema;
|
|
176
|
+
const defaultValue = schema?.default;
|
|
177
|
+
let dateType;
|
|
178
|
+
switch (schema?.type) {
|
|
179
|
+
case "array":
|
|
180
|
+
dateType = "array";
|
|
181
|
+
break;
|
|
182
|
+
case "integer":
|
|
183
|
+
case "number":
|
|
184
|
+
dateType = "number";
|
|
185
|
+
break;
|
|
186
|
+
case "boolean":
|
|
187
|
+
dateType = "boolean";
|
|
188
|
+
break;
|
|
189
|
+
case "string":
|
|
190
|
+
case "object":
|
|
191
|
+
dateType = "string";
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
yargs2.option(key, {
|
|
195
|
+
alias: aliases[key],
|
|
196
|
+
description: docs.description,
|
|
197
|
+
default: defaultValue,
|
|
198
|
+
deprecated: docs.deprecated,
|
|
199
|
+
type: dateType
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
var options = (fields, alias) => new ConsoleOptionMiddleware(fields, alias);
|
|
205
|
+
export {
|
|
206
|
+
ConsoleApp,
|
|
207
|
+
ConsoleChain,
|
|
208
|
+
ConsoleContext,
|
|
209
|
+
ConsoleMiddleware,
|
|
210
|
+
ConsoleOptionMiddleware,
|
|
211
|
+
ConsoleRequest,
|
|
212
|
+
ConsoleResponse,
|
|
213
|
+
HelpMiddleware,
|
|
214
|
+
options,
|
|
215
|
+
version
|
|
216
|
+
};
|
|
217
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/override/middleware.ts","../src/override/chain.ts","../src/app/context.ts","../src/app/app.ts","../src/app/request.ts","../src/app/response.ts","../src/middleware/showHelp.ts","../src/version.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 type { ShowHelp } 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> & ShowHelp & 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 public toHelp(yargs: YargsInstance): void {\n assert(yargs);\n }\n}\n\nexport class HelpMiddleware<\n Props extends object = object,\n> extends ConsoleMiddleware<Props> {}\n\nMiddleware.register('console', ConsoleMiddleware);\nMiddleware.register('help', HelpMiddleware);\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, Middleware } 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 { color } from '@aomex/helper';\n\nexport class ConsoleApp extends EventEmitter {\n protected running: boolean = false;\n protected readonly middlewareList: ConsoleMiddlewareToken[] = [];\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\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 = this.middlewareList.reduce<Middleware[]>(\n (carry, item) => carry.concat(Chain.flatten(item)),\n [],\n );\n\n await compose([\n showHelp(\n middlewareList.filter((item) => item instanceof HelpMiddleware),\n ),\n ...this.middlewareList.filter(\n (item) => !(item instanceof HelpMiddleware),\n ),\n ])(ctx);\n if (!response.commandMatched) {\n throw new Error(`Command \"${request.command}\" is not matched`);\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\n console.error(\n ['', color.red(stack.shift()), stack.join(EOL), ''].join(EOL),\n );\n }\n\n public mount(middleware: ConsoleMiddlewareToken): void {\n this.middlewareList.push(middleware);\n }\n}\n","import parse from 'yargs-parser';\nimport type { ConsoleApp } from './app';\n\nexport class ConsoleRequest {\n public readonly query: 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.query = 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 { compose, Middleware, middleware } from '@aomex/core';\nimport yargs, { type Argv } from 'yargs';\n\nimport { version } from '../version';\n\nexport interface ShowHelp {\n cli: {\n status: 'show-all' | 'show-detail';\n yargs: Argv;\n };\n}\n\nconst scriptName = 'aomex';\n\nexport const showHelp = (middlewareList: Middleware[]) => {\n const composeFn = compose(middlewareList);\n\n return middleware.console<ShowHelp>(async (ctx, next) => {\n const {\n request: { query: 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 = { status: 'show-all', yargs: 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 = { status: 'show-detail', yargs: 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}}';\n","import type { Options as YargsOptions } from 'yargs';\nimport parse from 'yargs-parser';\nimport { validate, Validator, GetValidatorType, 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]: GetValidatorType<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: docs.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,kBAA6B;AACtC,OAAO,YAAY;AAsBZ,IAAM,oBAAN,cAEG,WAAkB;AAAA,EAGnB,OAAOA,QAA4B;AACxC,WAAOA,MAAK;AAAA,EACd;AACF;AAEO,IAAM,iBAAN,cAEG,kBAAyB;AAAC;AAEpC,WAAW,SAAS,WAAW,iBAAiB;AAChD,WAAW,SAAS,QAAQ,cAAc;;;ACtC1C,SAAS,aAAkC;AAcpC,IAAM,eAAN,cAA0D,MAAa;AAQ9E;AAEA,MAAM,SAAS,WAAW,YAAY;;;ACpB/B,IAAM,iBAAN,MAAqB;AAAA,EAC1B,YACkB,KACA,SACA,UAChB;AAHgB;AACA;AACA;AAAA,EACf;AACL;;;ACVA,OAAO,kBAAkB;AACzB,SAAS,WAAW;AACpB,SAAS,eAAe;AACxB,SAAS,SAAAC,QAAO,WAAAC,gBAA2B;;;ACH3C,OAAO,WAAW;AAGX,IAAM,iBAAN,MAAqB;AAAA,EAI1B,YAA4B,KAAiC,MAAgB;AAAjD;AAAiC;AAC3D,UAAM,EAAE,GAAG,UAAU,GAAG,MAAM,IAAI,MAAM,IAAI;AAC5C,SAAK,QAAQ;AACb,SAAK,UAAU,OAAO,SAAS,CAAC,KAAK,EAAE;AAAA,EACzC;AAAA,EAPgB;AAAA,EACA;AAOl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Y,KAAK;AAAA,QACjB,MAAM;AAAA,MACR,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAwBO,IAAM,UAAU,CAKrB,QACA,UACG,IAAI,wBAA2B,QAAQ,KAAK;","names":["yargs","Chain","compose","options","Chain","compose","middleware","parse","options","parse","yargs"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@aomex/console",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"import": "./dist/index.js"
|
|
11
|
+
},
|
|
12
|
+
"./config": {
|
|
13
|
+
"types": "./dist/cli/define-config.d.ts",
|
|
14
|
+
"import": "./dist/cli/define-config.js"
|
|
15
|
+
},
|
|
16
|
+
"./package.json": "./package.json"
|
|
17
|
+
},
|
|
18
|
+
"bin": {
|
|
19
|
+
"aomex": "dist/cli/bin.js"
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"LICENSE",
|
|
27
|
+
"package.json",
|
|
28
|
+
"README.md",
|
|
29
|
+
"CHANGELOG.md"
|
|
30
|
+
],
|
|
31
|
+
"keywords": [],
|
|
32
|
+
"author": "geekact",
|
|
33
|
+
"license": "MIT",
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"@aomex/core": "^0.0.0"
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@aomex/helper": "^0.0.0",
|
|
39
|
+
"cosmiconfig": "^8.0.0",
|
|
40
|
+
"yargs": "^17.6.2",
|
|
41
|
+
"yargs-parser": "^21.1.1"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@types/yargs": "^17.0.22",
|
|
45
|
+
"@types/yargs-parser": "^21.0.0",
|
|
46
|
+
"@aomex/core": "^0.0.0",
|
|
47
|
+
"read-pkg-up": "^9.1.0"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {}
|
|
50
|
+
}
|
package/src/cli/bin.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
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());
|