chore: 更新版本号至 0.1.1,并增强命令行参数解析功能,支持 JSON 和 key=value 格式

This commit is contained in:
2026-03-11 13:21:16 +08:00
parent 5bed882795
commit e18233fdcb
2 changed files with 16 additions and 6 deletions

View File

@@ -1,7 +1,7 @@
{ {
"$schema": "https://json.schemastore.org/package", "$schema": "https://json.schemastore.org/package",
"name": "@kevisual/router", "name": "@kevisual/router",
"version": "0.1.0", "version": "0.1.1",
"description": "", "description": "",
"type": "module", "type": "module",
"main": "./dist/router.js", "main": "./dist/router.js",

View File

@@ -22,8 +22,12 @@ export const parseArgs = (args: string) => {
for (const pair of pairs) { for (const pair of pairs) {
const idx = pair.indexOf('='); const idx = pair.indexOf('=');
const key = pair.slice(0, idx); const key = pair.slice(0, idx);
const value = pair.slice(idx + 1); const raw = pair.slice(idx + 1);
result[key] = value; let value: string | number | boolean = raw;
if (raw === 'true') value = true;
else if (raw === 'false') value = false;
else if (raw !== '' && !isNaN(Number(raw))) value = Number(raw);
result[key] = value as string;
} }
return result; return result;
} }
@@ -77,8 +81,9 @@ export const createCommand = (opts: { app: App, program: Command }) => {
const description = parseDescription(route); const description = parseDescription(route);
subProgram.command(route.key) subProgram.command(route.key)
.description(description || '') .description(description || '')
.option('--args <args>', 'JSON字符串参数传递给命令执行') .option('--args <args>', '命令参数,支持 JSON 格式或 key=value 形式,例如: --args \'{"a":1}\' 或 --args \'a=1 b=2\'')
.action(async (options) => { .argument('[args...]', '位置参数(推荐通过 -- 分隔传入),支持 JSON 或 key=value 格式,例如: -- a=1 b=2 或 -- \'{"a":1}\'')
.action(async (passedArgs: string[], options, _command) => {
const output = (data: any) => { const output = (data: any) => {
if (typeof data === 'object') { if (typeof data === 'object') {
process.stdout.write(JSON.stringify(data, null, 2) + '\n'); process.stdout.write(JSON.stringify(data, null, 2) + '\n');
@@ -87,7 +92,12 @@ export const createCommand = (opts: { app: App, program: Command }) => {
} }
} }
try { try {
const args = options.args ? parseArgs(options.args) : {}; let args: Record<string, any> = {};
if (options.args) {
args = parseArgs(options.args);
} else if (passedArgs.length > 0) {
args = parseArgs(passedArgs.join(' '));
}
// 这里可以添加实际的命令执行逻辑,例如调用对应的路由处理函数 // 这里可以添加实际的命令执行逻辑,例如调用对应的路由处理函数
const res = await app.run({ path, key: route.key, payload: args }, { appId: app.appId }); const res = await app.run({ path, key: route.key, payload: args }, { appId: app.appId });
if (res.code === 200) { if (res.code === 200) {