mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:59:19 +08:00
refactor(license-server): cli重构成tui
This commit is contained in:
@@ -1,104 +0,0 @@
|
||||
import { confirm, input } from '@inquirer/prompts';
|
||||
|
||||
import { apiRequest } from '../api/client.js';
|
||||
import { getGlobalOpts, isInteractive } from '../context.js';
|
||||
import {
|
||||
printEmptyHint,
|
||||
printJson,
|
||||
printQuiet,
|
||||
printSuccess,
|
||||
printTable,
|
||||
} from '../ui/render.js';
|
||||
|
||||
interface Customer {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
status: number;
|
||||
contactName?: string;
|
||||
contactPhone?: string;
|
||||
}
|
||||
|
||||
interface PageResult<T> {
|
||||
items: T[];
|
||||
total: number;
|
||||
page: number;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export async function customerList(opts: { page?: number; size?: number }) {
|
||||
const global = getGlobalOpts();
|
||||
const page = opts.page || 1;
|
||||
const size = opts.size || 20;
|
||||
const data = await apiRequest<PageResult<Customer>>(
|
||||
'GET',
|
||||
`/customers?page=${page}&size=${size}`,
|
||||
);
|
||||
|
||||
if (global.json) {
|
||||
printJson(data);
|
||||
return;
|
||||
}
|
||||
if (!data.items.length) {
|
||||
printEmptyHint('运行 ecom-license customer create 创建客户');
|
||||
return;
|
||||
}
|
||||
|
||||
printTable(
|
||||
['ID', 'CODE', 'NAME', 'STATUS'],
|
||||
data.items.map((c) => [
|
||||
String(c.id),
|
||||
c.code,
|
||||
c.name,
|
||||
c.status === 1 ? '启用' : '禁用',
|
||||
]),
|
||||
);
|
||||
console.log(`共 ${data.total} 条 · 第 ${data.page}/${Math.ceil(data.total / data.size) || 1} 页`);
|
||||
}
|
||||
|
||||
export async function customerCreate(opts: {
|
||||
code?: string;
|
||||
name?: string;
|
||||
contactName?: string;
|
||||
contactPhone?: string;
|
||||
contactEmail?: string;
|
||||
}) {
|
||||
const global = getGlobalOpts();
|
||||
let payload = { ...opts };
|
||||
|
||||
if (isInteractive() && !opts.name) {
|
||||
payload.name = await input({ message: '公司名称', validate: (v) => !!v || '必填' });
|
||||
payload.contactName = await input({ message: '联系人', default: '' });
|
||||
payload.contactPhone = await input({ message: '联系电话', default: '' });
|
||||
payload.contactEmail = await input({ message: '联系邮箱', default: '' });
|
||||
payload.code = await input({ message: '客户编码(留空自动生成)', default: '' });
|
||||
if (!payload.code) delete payload.code;
|
||||
}
|
||||
|
||||
if (!payload.name) {
|
||||
console.error('请提供 --name');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const created = await apiRequest<Customer>('POST', '/customers', payload);
|
||||
if (global.json) printJson(created);
|
||||
else if (global.quiet) printQuiet(String(created.id));
|
||||
else printSuccess(`客户已创建: ${created.code} · ${created.name}`);
|
||||
}
|
||||
|
||||
export async function customerShow(id: number) {
|
||||
const global = getGlobalOpts();
|
||||
const customer = await apiRequest<Customer>('GET', `/customers/${id}`);
|
||||
if (global.json) printJson(customer);
|
||||
else printJson(customer);
|
||||
}
|
||||
|
||||
export async function customerDelete(id: number, yes?: boolean) {
|
||||
const global = getGlobalOpts();
|
||||
if (isInteractive() && !yes && !global.yes) {
|
||||
const ok = await confirm({ message: `确认删除客户 #${id}?`, default: false });
|
||||
if (!ok) return;
|
||||
}
|
||||
await apiRequest('DELETE', `/customers/${id}`);
|
||||
printSuccess(`客户 #${id} 已删除`);
|
||||
}
|
||||
@@ -1,257 +0,0 @@
|
||||
import { checkbox, confirm, input, search, select } from '@inquirer/prompts';
|
||||
|
||||
import { apiRequest, apiDownload } from '../api/client.js';
|
||||
import { getGlobalOpts, isInteractive } from '../context.js';
|
||||
import {
|
||||
printBox,
|
||||
printEmptyHint,
|
||||
printJson,
|
||||
printQuiet,
|
||||
printSuccess,
|
||||
printTable,
|
||||
} from '../ui/render.js';
|
||||
|
||||
interface Customer {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface License {
|
||||
id: number;
|
||||
jti: string;
|
||||
edition: string;
|
||||
machineFingerprint: string;
|
||||
status: string;
|
||||
expiresAt: string;
|
||||
licenseKey?: string;
|
||||
customer?: Customer;
|
||||
}
|
||||
|
||||
interface PageResult<T> {
|
||||
items: T[];
|
||||
total: number;
|
||||
page: number;
|
||||
size: number;
|
||||
}
|
||||
|
||||
interface GenerateResult {
|
||||
id: number;
|
||||
licenseKey: string;
|
||||
jti: string;
|
||||
edition: string;
|
||||
machineFingerprint: string;
|
||||
expiresAt: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export async function licenseList(opts: {
|
||||
page?: number;
|
||||
size?: number;
|
||||
customerId?: number;
|
||||
status?: string;
|
||||
}) {
|
||||
const global = getGlobalOpts();
|
||||
const params = new URLSearchParams();
|
||||
if (opts.page) params.set('page', String(opts.page));
|
||||
if (opts.size) params.set('size', String(opts.size));
|
||||
if (opts.customerId) params.set('customerId', String(opts.customerId));
|
||||
if (opts.status) params.set('status', opts.status);
|
||||
|
||||
const data = await apiRequest<PageResult<License>>(
|
||||
'GET',
|
||||
`/licenses?${params.toString()}`,
|
||||
);
|
||||
|
||||
if (global.json) {
|
||||
printJson(data);
|
||||
return;
|
||||
}
|
||||
if (!data.items.length) {
|
||||
printEmptyHint('运行 ecom-license license generate 签发许可证');
|
||||
return;
|
||||
}
|
||||
|
||||
printTable(
|
||||
['ID', 'JTI', 'EDITION', 'FINGERPRINT', 'STATUS', 'EXPIRES'],
|
||||
data.items.map((l) => [
|
||||
String(l.id),
|
||||
l.jti.slice(0, 8) + '...',
|
||||
l.edition,
|
||||
l.machineFingerprint.slice(0, 16) + (l.machineFingerprint.length > 16 ? '...' : ''),
|
||||
l.status,
|
||||
l.expiresAt?.slice(0, 10) || '-',
|
||||
]),
|
||||
);
|
||||
console.log(`共 ${data.total} 条`);
|
||||
}
|
||||
|
||||
export async function licenseShow(id: number) {
|
||||
const global = getGlobalOpts();
|
||||
const license = await apiRequest<License>('GET', `/licenses/${id}`);
|
||||
if (global.json) printJson(license);
|
||||
else printJson(license);
|
||||
}
|
||||
|
||||
export async function licenseGenerate(opts: {
|
||||
customerId?: number;
|
||||
company?: string;
|
||||
fingerprint?: string;
|
||||
edition?: string;
|
||||
expires?: string;
|
||||
features?: string;
|
||||
}) {
|
||||
const global = getGlobalOpts();
|
||||
let customerId = opts.customerId;
|
||||
let company = opts.company;
|
||||
let fingerprint = opts.fingerprint;
|
||||
let edition = opts.edition || 'enterprise';
|
||||
let expiresAt = opts.expires;
|
||||
let features = opts.features?.split(',').map((s) => s.trim()).filter(Boolean) || [
|
||||
'order-import',
|
||||
'order-create',
|
||||
];
|
||||
|
||||
if (isInteractive() && !customerId) {
|
||||
const customers = await apiRequest<PageResult<Customer>>('GET', '/customers?page=1&size=100');
|
||||
if (!customers.items.length) {
|
||||
console.error('暂无客户,请先 ecom-license customer create');
|
||||
process.exit(1);
|
||||
}
|
||||
customerId = await search({
|
||||
message: '选择客户',
|
||||
source: async (term) => {
|
||||
const q = (term || '').toLowerCase();
|
||||
return customers.items
|
||||
.filter(
|
||||
(c) =>
|
||||
!q ||
|
||||
c.name.toLowerCase().includes(q) ||
|
||||
c.code.toLowerCase().includes(q),
|
||||
)
|
||||
.map((c) => ({ name: `${c.code} · ${c.name}`, value: c.id }));
|
||||
},
|
||||
});
|
||||
const picked = customers.items.find((c) => c.id === customerId)!;
|
||||
company = await input({ message: '授权公司名', default: picked.name });
|
||||
const fpMode = await select({
|
||||
message: '机器指纹',
|
||||
choices: [
|
||||
{ name: '私有部署(输入 FP-xxx)', value: 'custom' },
|
||||
{ name: 'SaaS 不限指纹 (*)', value: '*' },
|
||||
],
|
||||
});
|
||||
fingerprint =
|
||||
fpMode === '*'
|
||||
? '*'
|
||||
: await input({
|
||||
message: '机器指纹',
|
||||
validate: (v) => v.startsWith('FP-') || v === '*' || '格式应为 FP-...',
|
||||
});
|
||||
edition = await select({
|
||||
message: '版本类型',
|
||||
choices: [
|
||||
{ name: 'trial · 试用', value: 'trial' },
|
||||
{ name: 'enterprise · 企业', value: 'enterprise' },
|
||||
{ name: 'unlimited · 无限', value: 'unlimited' },
|
||||
],
|
||||
});
|
||||
const expireChoice = await select({
|
||||
message: '有效期',
|
||||
choices: [
|
||||
{ name: '+30 天', value: '30d' },
|
||||
{ name: '+1 年', value: '1y' },
|
||||
{ name: '自定义日期', value: 'custom' },
|
||||
],
|
||||
});
|
||||
if (expireChoice === 'custom') {
|
||||
expiresAt = await input({
|
||||
message: '过期日期 (YYYY-MM-DD)',
|
||||
validate: (v) => /^\d{4}-\d{2}-\d{2}$/.test(v) || '格式 YYYY-MM-DD',
|
||||
});
|
||||
} else {
|
||||
const d = new Date();
|
||||
if (expireChoice === '30d') d.setDate(d.getDate() + 30);
|
||||
else d.setFullYear(d.getFullYear() + 1);
|
||||
expiresAt = d.toISOString().slice(0, 10);
|
||||
}
|
||||
features = await checkbox({
|
||||
message: '授权功能',
|
||||
choices: [
|
||||
{ name: 'order-import · 订单导入', value: 'order-import', checked: true },
|
||||
{ name: 'order-create · 创建订单', value: 'order-create', checked: true },
|
||||
],
|
||||
});
|
||||
const summary = [
|
||||
`客户 ID: ${customerId}`,
|
||||
`公司: ${company}`,
|
||||
`指纹: ${fingerprint}`,
|
||||
`版本: ${edition}`,
|
||||
`过期: ${expiresAt}`,
|
||||
`功能: ${features.join(', ')}`,
|
||||
].join('\n');
|
||||
const ok = await confirm({ message: `确认签发?\n${summary}`, default: true });
|
||||
if (!ok) return;
|
||||
}
|
||||
|
||||
if (!customerId || !company || !fingerprint || !expiresAt) {
|
||||
console.error('缺少参数,交互模式请直接运行 ecom-license license generate');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const result = await apiRequest<GenerateResult>('POST', '/licenses/generate', {
|
||||
customerId,
|
||||
company,
|
||||
machineFingerprint: fingerprint,
|
||||
edition,
|
||||
expiresAt: new Date(expiresAt).toISOString(),
|
||||
features,
|
||||
});
|
||||
|
||||
if (global.json) {
|
||||
printJson(result);
|
||||
return;
|
||||
}
|
||||
if (global.quiet) {
|
||||
printQuiet(result.licenseKey);
|
||||
return;
|
||||
}
|
||||
|
||||
printBox(
|
||||
'签发成功',
|
||||
[
|
||||
`ID: ${result.id}`,
|
||||
`JTI: ${result.jti}`,
|
||||
`过期: ${result.expiresAt?.slice(0, 10)}`,
|
||||
'',
|
||||
result.licenseKey,
|
||||
'',
|
||||
'提示: 使用 --quiet 仅输出 licenseKey',
|
||||
].join('\n'),
|
||||
'green',
|
||||
);
|
||||
}
|
||||
|
||||
export async function licenseRevoke(id: number, yes?: boolean) {
|
||||
const global = getGlobalOpts();
|
||||
const license = await apiRequest<License>('GET', `/licenses/${id}`);
|
||||
if (isInteractive() && !yes && !global.yes) {
|
||||
const ok = await confirm({
|
||||
message: `确认吊销?\nJTI: ${license.jti}\n指纹: ${license.machineFingerprint}`,
|
||||
default: false,
|
||||
});
|
||||
if (!ok) return;
|
||||
}
|
||||
const result = await apiRequest('POST', `/licenses/${id}/revoke`);
|
||||
if (global.json) printJson(result);
|
||||
else printSuccess(`许可证 #${id} 已吊销`);
|
||||
}
|
||||
|
||||
export async function licenseDownload(id: number, output?: string) {
|
||||
const global = getGlobalOpts();
|
||||
const outfile = output || `license-${id}.key`;
|
||||
const path = await apiDownload(`/licenses/${id}/download`, outfile);
|
||||
if (global.json) printJson({ path });
|
||||
else if (global.quiet) printQuiet(path);
|
||||
else printSuccess(`已保存到 ${path}`);
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import { loadConfig, resolveApiUrl } from '../config.js';
|
||||
import { getGlobalOpts } from '../context.js';
|
||||
import { printBox, printError, printJson, printQuiet } from '../ui/render.js';
|
||||
|
||||
export async function whoamiCommand() {
|
||||
const global = getGlobalOpts();
|
||||
const config = await loadConfig();
|
||||
const apiUrl = resolveApiUrl(global.url, config);
|
||||
|
||||
if (!config?.token && !global.token) {
|
||||
printError('未登录,请运行: ecom-license login');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const info = {
|
||||
apiUrl,
|
||||
username: config?.username,
|
||||
expiresAt: config?.expiresAt,
|
||||
loggedIn: Boolean(config?.token || global.token),
|
||||
};
|
||||
|
||||
if (global.json) {
|
||||
printJson(info);
|
||||
return;
|
||||
}
|
||||
if (global.quiet) {
|
||||
printQuiet(config?.username || '');
|
||||
return;
|
||||
}
|
||||
|
||||
printBox(
|
||||
'当前会话',
|
||||
[
|
||||
`API: ${apiUrl}`,
|
||||
`用户: ${config?.username || '(未知)'}`,
|
||||
`过期: ${config?.expiresAt || '-'}`,
|
||||
].join('\n'),
|
||||
);
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
/** 全局 CLI 运行上下文(由 commander 注入) */
|
||||
export interface GlobalOpts {
|
||||
url?: string;
|
||||
token?: string;
|
||||
json?: boolean;
|
||||
quiet?: boolean;
|
||||
yes?: boolean;
|
||||
verbose?: boolean;
|
||||
}
|
||||
|
||||
let globalOpts: GlobalOpts = {};
|
||||
|
||||
export function setGlobalOpts(opts: GlobalOpts) {
|
||||
globalOpts = opts;
|
||||
}
|
||||
|
||||
export function getGlobalOpts(): GlobalOpts {
|
||||
return globalOpts;
|
||||
}
|
||||
|
||||
/** TTY 交互模式检测 */
|
||||
export function isInteractive(): boolean {
|
||||
const opts = getGlobalOpts();
|
||||
return (
|
||||
Boolean(process.stdout.isTTY) &&
|
||||
!process.env.CI &&
|
||||
!opts.json &&
|
||||
!opts.quiet
|
||||
);
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
import { Command } from 'commander';
|
||||
|
||||
import { customerCreate, customerDelete, customerList, customerShow } from './commands/customer.js';
|
||||
import { licenseDownload, licenseGenerate, licenseList, licenseRevoke, licenseShow } from './commands/license.js';
|
||||
import { loginCommand } from './commands/login.js';
|
||||
import { logoutCommand } from './commands/logout.js';
|
||||
import { statsCommand } from './commands/stats.js';
|
||||
import { whoamiCommand } from './commands/whoami.js';
|
||||
import { setGlobalOpts } from './context.js';
|
||||
import { printBanner } from './ui/render.js';
|
||||
|
||||
function applyGlobals(cmd: Command) {
|
||||
return cmd
|
||||
.option('--url <base>', 'API 根地址')
|
||||
.option('--token <jwt>', 'Bearer Token')
|
||||
.option('--json', 'JSON 输出')
|
||||
.option('--quiet', '仅输出关键值')
|
||||
.option('--yes', '跳过确认')
|
||||
.option('--verbose', '显示详细错误')
|
||||
.hook('preAction', (thisCmd) => {
|
||||
const root = thisCmd.optsWithGlobals();
|
||||
setGlobalOpts({
|
||||
url: root.url,
|
||||
token: root.token,
|
||||
json: root.json,
|
||||
quiet: root.quiet,
|
||||
yes: root.yes,
|
||||
verbose: root.verbose,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const program = new Command();
|
||||
program.name('ecom-license').description('Ecom-DMB License 运营管理 CLI').version('0.1.0');
|
||||
|
||||
applyGlobals(program);
|
||||
|
||||
program
|
||||
.command('login')
|
||||
.description('登录 License 平台')
|
||||
.option('--username <name>')
|
||||
.option('--password <pwd>')
|
||||
.action((opts, cmd) => loginCommand({ ...opts, url: cmd.optsWithGlobals().url }));
|
||||
|
||||
program.command('logout').description('退出登录').action(logoutCommand);
|
||||
program.command('whoami').description('查看当前登录状态').action(whoamiCommand);
|
||||
program.command('stats').description('平台统计').action(statsCommand);
|
||||
|
||||
const customer = program.command('customer').description('客户管理');
|
||||
applyGlobals(customer);
|
||||
customer.command('list').option('--page <n>').option('--size <n>').action((opts) =>
|
||||
customerList({ page: Number(opts.page) || 1, size: Number(opts.size) || 20 }),
|
||||
);
|
||||
customer
|
||||
.command('create')
|
||||
.option('--code <code>')
|
||||
.option('--name <name>')
|
||||
.option('--contact-name <n>')
|
||||
.option('--contact-phone <p>')
|
||||
.option('--contact-email <e>')
|
||||
.action((opts) => customerCreate(opts));
|
||||
customer.command('show <id>').action((id) => customerShow(Number(id)));
|
||||
customer.command('delete <id>').action((id, opts, cmd) =>
|
||||
customerDelete(Number(id), cmd.optsWithGlobals().yes),
|
||||
);
|
||||
|
||||
const license = program.command('license').description('许可证管理');
|
||||
applyGlobals(license);
|
||||
license
|
||||
.command('list')
|
||||
.option('--page <n>')
|
||||
.option('--size <n>')
|
||||
.option('--customer-id <id>')
|
||||
.option('--status <s>')
|
||||
.action((opts) =>
|
||||
licenseList({
|
||||
page: Number(opts.page) || 1,
|
||||
size: Number(opts.size) || 20,
|
||||
customerId: opts.customerId ? Number(opts.customerId) : undefined,
|
||||
status: opts.status,
|
||||
}),
|
||||
);
|
||||
license.command('show <id>').action((id) => licenseShow(Number(id)));
|
||||
license
|
||||
.command('generate')
|
||||
.option('--customer-id <id>')
|
||||
.option('--company <name>')
|
||||
.option('--fingerprint <fp>')
|
||||
.option('--edition <e>')
|
||||
.option('--expires <date>')
|
||||
.option('--features <list>')
|
||||
.action((opts) => licenseGenerate(opts));
|
||||
license.command('revoke <id>').action((id, _o, cmd) =>
|
||||
licenseRevoke(Number(id), cmd.optsWithGlobals().yes),
|
||||
);
|
||||
license
|
||||
.command('download <id>')
|
||||
.option('-o, --output <file>')
|
||||
.action((id, opts) => licenseDownload(Number(id), opts.output));
|
||||
|
||||
// 无子命令时只展示引导,不输出冗长 --help
|
||||
program.action(() => {
|
||||
printBanner();
|
||||
console.log('常用命令:');
|
||||
console.log(' pnpm dev login # 开发模式登录');
|
||||
console.log(' pnpm dev customer create # 创建客户');
|
||||
console.log(' pnpm dev license generate # 签发 License');
|
||||
console.log(' pnpm start login # 使用构建产物');
|
||||
console.log('');
|
||||
console.log('完整帮助: pnpm dev -- --help');
|
||||
});
|
||||
|
||||
program.parseAsync(process.argv).catch((err) => {
|
||||
if (err?.name === 'ExitPromptError') process.exit(0);
|
||||
console.error(err?.message || err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,26 +1,19 @@
|
||||
{
|
||||
"name": "ecom-license-cli",
|
||||
"version": "0.1.0",
|
||||
"name": "ecom-license-tui",
|
||||
"version": "0.2.0",
|
||||
"private": true,
|
||||
"packageManager": "pnpm@10.32.0",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"ecom-license": "./dist/index.js"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"dev": "tsx src/index.ts",
|
||||
"start": "node dist/index.js",
|
||||
"login": "tsx src/index.ts login",
|
||||
"whoami": "tsx src/index.ts whoami",
|
||||
"stats": "tsx src/index.ts stats"
|
||||
"start": "node dist/index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@inquirer/prompts": "^7.2.0",
|
||||
"boxen": "^8.0.1",
|
||||
"chalk": "^5.4.1",
|
||||
"cli-table3": "^0.6.5",
|
||||
"commander": "^13.0.0",
|
||||
"gradient-string": "^3.0.0",
|
||||
"ora": "^8.1.1"
|
||||
},
|
||||
@@ -20,9 +20,6 @@ importers:
|
||||
cli-table3:
|
||||
specifier: ^0.6.5
|
||||
version: 0.6.5
|
||||
commander:
|
||||
specifier: ^13.0.0
|
||||
version: 13.1.0
|
||||
gradient-string:
|
||||
specifier: ^3.0.0
|
||||
version: 3.0.0
|
||||
@@ -403,10 +400,6 @@ packages:
|
||||
color-name@1.1.4:
|
||||
resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
|
||||
|
||||
commander@13.1.0:
|
||||
resolution: {integrity: sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
emoji-regex@10.6.0:
|
||||
resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==}
|
||||
|
||||
@@ -808,8 +801,6 @@ snapshots:
|
||||
|
||||
color-name@1.1.4: {}
|
||||
|
||||
commander@13.1.0: {}
|
||||
|
||||
emoji-regex@10.6.0: {}
|
||||
|
||||
emoji-regex@8.0.0: {}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { getGlobalOpts, isInteractive } from '../context.js';
|
||||
import { loadConfig, resolveApiUrl, resolveToken } from '../config.js';
|
||||
import { failSpinner, runSpinner } from '../ui/render.js';
|
||||
import { runSpinner } from '../ui/render.js';
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
@@ -28,10 +27,9 @@ export async function apiRequest<T>(
|
||||
body?: unknown,
|
||||
auth = true,
|
||||
): Promise<T> {
|
||||
const opts = getGlobalOpts();
|
||||
const config = await loadConfig();
|
||||
const baseUrl = resolveApiUrl(opts.url, config);
|
||||
const token = resolveToken(opts.token, config);
|
||||
const baseUrl = resolveApiUrl(undefined, config);
|
||||
const token = resolveToken(undefined, config);
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -58,24 +56,13 @@ export async function apiRequest<T>(
|
||||
return (await res.text()) as T;
|
||||
};
|
||||
|
||||
if (isInteractive() && !opts.quiet && !opts.json) {
|
||||
return runSpinner(doFetch, '请求中...');
|
||||
}
|
||||
try {
|
||||
return await doFetch();
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 401 && auth) {
|
||||
failSpinner('未登录或 Token 已过期,请运行: ecom-license login');
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return runSpinner(doFetch, '请求中...');
|
||||
}
|
||||
|
||||
export async function apiDownload(path: string, outfile: string): Promise<string> {
|
||||
const opts = getGlobalOpts();
|
||||
const config = await loadConfig();
|
||||
const baseUrl = resolveApiUrl(opts.url, config);
|
||||
const token = resolveToken(opts.token, config);
|
||||
const baseUrl = resolveApiUrl(undefined, config);
|
||||
const token = resolveToken(undefined, config);
|
||||
|
||||
const doFetch = async () => {
|
||||
const res = await fetch(`${baseUrl}/api${path}`, {
|
||||
@@ -88,8 +75,5 @@ export async function apiDownload(path: string, outfile: string): Promise<string
|
||||
return outfile;
|
||||
};
|
||||
|
||||
if (isInteractive()) {
|
||||
return runSpinner(doFetch, '正在下载...');
|
||||
}
|
||||
return doFetch();
|
||||
return runSpinner(doFetch, '正在下载...');
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { confirm, input, select } from '@inquirer/prompts';
|
||||
|
||||
import { apiRequest } from '../api/client.js';
|
||||
import { printEmptyHint, printSuccess, printTable } from '../ui/render.js';
|
||||
|
||||
async function pause() {
|
||||
await input({ message: '按 Enter 返回' });
|
||||
}
|
||||
|
||||
interface Customer {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
status: number;
|
||||
contactName?: string;
|
||||
contactPhone?: string;
|
||||
}
|
||||
|
||||
interface PageResult<T> {
|
||||
items: T[];
|
||||
total: number;
|
||||
page: number;
|
||||
size: number;
|
||||
}
|
||||
|
||||
async function customerList() {
|
||||
const data = await apiRequest<PageResult<Customer>>('GET', '/customers?page=1&size=20');
|
||||
|
||||
if (!data.items.length) {
|
||||
printEmptyHint('创建客户');
|
||||
return;
|
||||
}
|
||||
|
||||
printTable(
|
||||
['ID', 'CODE', 'NAME', 'STATUS'],
|
||||
data.items.map((c) => [
|
||||
String(c.id),
|
||||
c.code,
|
||||
c.name,
|
||||
c.status === 1 ? '启用' : '禁用',
|
||||
]),
|
||||
);
|
||||
const totalPages = Math.ceil(data.total / data.size) || 1;
|
||||
console.log(`共 ${data.total} 条 · 第 ${data.page}/${totalPages} 页`);
|
||||
}
|
||||
|
||||
async function customerCreate() {
|
||||
const name = await input({ message: '公司名称', validate: (v) => !!v || '必填' });
|
||||
const contactName = await input({ message: '联系人', default: '' });
|
||||
const contactPhone = await input({ message: '联系电话', default: '' });
|
||||
const contactEmail = await input({ message: '联系邮箱', default: '' });
|
||||
let code = await input({ message: '客户编码(留空自动生成)', default: '' });
|
||||
if (!code) code = undefined as any;
|
||||
|
||||
const created = await apiRequest<Customer>('POST', '/customers', {
|
||||
name,
|
||||
contactName,
|
||||
contactPhone,
|
||||
contactEmail,
|
||||
code,
|
||||
});
|
||||
printSuccess(`客户已创建: ${created.code} · ${created.name}`);
|
||||
}
|
||||
|
||||
async function customerShow() {
|
||||
const id = await input({ message: '客户 ID', validate: (v) => /^\d+$/.test(v) || '请输入数字' });
|
||||
const customer = await apiRequest<Customer>('GET', `/customers/${Number(id)}`);
|
||||
printTable(
|
||||
['ID', 'CODE', 'NAME', 'STATUS', '联系人', '电话'],
|
||||
[[
|
||||
String(customer.id),
|
||||
customer.code,
|
||||
customer.name,
|
||||
customer.status === 1 ? '启用' : '禁用',
|
||||
customer.contactName || '-',
|
||||
customer.contactPhone || '-',
|
||||
]],
|
||||
);
|
||||
}
|
||||
|
||||
async function customerDelete() {
|
||||
const id = await input({ message: '客户 ID', validate: (v) => /^\d+$/.test(v) || '请输入数字' });
|
||||
const ok = await confirm({ message: `确认删除客户 #${id}?`, default: false });
|
||||
if (!ok) return;
|
||||
await apiRequest('DELETE', `/customers/${Number(id)}`);
|
||||
printSuccess(`客户 #${id} 已删除`);
|
||||
}
|
||||
|
||||
export async function customerMenu() {
|
||||
console.clear();
|
||||
const action = await select({
|
||||
message: '客户管理',
|
||||
choices: [
|
||||
{ name: '列表', value: 'list' },
|
||||
{ name: '创建', value: 'create' },
|
||||
{ name: '查看', value: 'show' },
|
||||
{ name: '删除', value: 'delete' },
|
||||
{ name: '返回主菜单', value: 'back' },
|
||||
],
|
||||
});
|
||||
|
||||
switch (action) {
|
||||
case 'list':
|
||||
console.clear();
|
||||
await customerList();
|
||||
await pause();
|
||||
break;
|
||||
case 'create':
|
||||
console.clear();
|
||||
await customerCreate();
|
||||
await pause();
|
||||
break;
|
||||
case 'show':
|
||||
console.clear();
|
||||
await customerShow();
|
||||
await pause();
|
||||
break;
|
||||
case 'delete':
|
||||
console.clear();
|
||||
await customerDelete();
|
||||
await pause();
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
import { checkbox, confirm, input, search, select } from '@inquirer/prompts';
|
||||
|
||||
import { apiRequest, apiDownload } from '../api/client.js';
|
||||
import { printBox, printEmptyHint, printSuccess, printTable } from '../ui/render.js';
|
||||
|
||||
async function pause() {
|
||||
await input({ message: '按 Enter 返回' });
|
||||
}
|
||||
|
||||
interface Customer {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface License {
|
||||
id: number;
|
||||
jti: string;
|
||||
edition: string;
|
||||
machineFingerprint: string;
|
||||
status: string;
|
||||
expiresAt: string;
|
||||
licenseKey?: string;
|
||||
customer?: Customer;
|
||||
}
|
||||
|
||||
interface PageResult<T> {
|
||||
items: T[];
|
||||
total: number;
|
||||
page: number;
|
||||
size: number;
|
||||
}
|
||||
|
||||
interface GenerateResult {
|
||||
id: number;
|
||||
licenseKey: string;
|
||||
jti: string;
|
||||
edition: string;
|
||||
machineFingerprint: string;
|
||||
expiresAt: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
async function licenseList() {
|
||||
const data = await apiRequest<PageResult<License>>('GET', '/licenses?page=1&size=20');
|
||||
|
||||
if (!data.items.length) {
|
||||
printEmptyHint('签发许可证');
|
||||
return;
|
||||
}
|
||||
|
||||
printTable(
|
||||
['ID', 'JTI', 'EDITION', 'FINGERPRINT', 'STATUS', 'EXPIRES'],
|
||||
data.items.map((l) => [
|
||||
String(l.id),
|
||||
l.jti.slice(0, 8) + '...',
|
||||
l.edition,
|
||||
l.machineFingerprint.slice(0, 16) + (l.machineFingerprint.length > 16 ? '...' : ''),
|
||||
l.status,
|
||||
l.expiresAt?.slice(0, 10) || '-',
|
||||
]),
|
||||
);
|
||||
console.log(`共 ${data.total} 条`);
|
||||
}
|
||||
|
||||
async function licenseShow() {
|
||||
const id = await input({ message: '许可证 ID', validate: (v) => /^\d+$/.test(v) || '请输入数字' });
|
||||
const license = await apiRequest<License>('GET', `/licenses/${Number(id)}`);
|
||||
printBox(
|
||||
`许可证 #${license.id}`,
|
||||
[
|
||||
`JTI: ${license.jti}`,
|
||||
`版本: ${license.edition}`,
|
||||
`指纹: ${license.machineFingerprint}`,
|
||||
`状态: ${license.status}`,
|
||||
`过期: ${license.expiresAt?.slice(0, 10) || '-'}`,
|
||||
license.licenseKey ? `\n${license.licenseKey}` : '',
|
||||
].join('\n'),
|
||||
);
|
||||
}
|
||||
|
||||
async function licenseGenerate() {
|
||||
const customers = await apiRequest<PageResult<Customer>>('GET', '/customers?page=1&size=100');
|
||||
if (!customers.items.length) {
|
||||
console.error('暂无客户,请先创建客户');
|
||||
return;
|
||||
}
|
||||
|
||||
const customerId = await search({
|
||||
message: '选择客户',
|
||||
source: async (term) => {
|
||||
const q = (term || '').toLowerCase();
|
||||
return customers.items
|
||||
.filter((c) => !q || c.name.toLowerCase().includes(q) || c.code.toLowerCase().includes(q))
|
||||
.map((c) => ({ name: `${c.code} · ${c.name}`, value: c.id }));
|
||||
},
|
||||
});
|
||||
|
||||
const picked = customers.items.find((c) => c.id === customerId)!;
|
||||
const company = await input({ message: '授权公司名', default: picked.name });
|
||||
|
||||
const fpMode = await select({
|
||||
message: '机器指纹',
|
||||
choices: [
|
||||
{ name: '私有部署(输入 FP-xxx)', value: 'custom' },
|
||||
{ name: 'SaaS 不限指纹 (*)', value: '*' },
|
||||
],
|
||||
});
|
||||
const fingerprint =
|
||||
fpMode === '*'
|
||||
? '*'
|
||||
: await input({
|
||||
message: '机器指纹',
|
||||
validate: (v) => v.startsWith('FP-') || v === '*' || '格式应为 FP-...',
|
||||
});
|
||||
|
||||
const edition = await select({
|
||||
message: '版本类型',
|
||||
choices: [
|
||||
{ name: 'trial · 试用', value: 'trial' },
|
||||
{ name: 'enterprise · 企业', value: 'enterprise' },
|
||||
{ name: 'unlimited · 无限', value: 'unlimited' },
|
||||
],
|
||||
});
|
||||
|
||||
const expireChoice = await select({
|
||||
message: '有效期',
|
||||
choices: [
|
||||
{ name: '+30 天', value: '30d' },
|
||||
{ name: '+1 年', value: '1y' },
|
||||
{ name: '自定义日期', value: 'custom' },
|
||||
],
|
||||
});
|
||||
|
||||
let expiresAt: string;
|
||||
if (expireChoice === 'custom') {
|
||||
expiresAt = await input({
|
||||
message: '过期日期 (YYYY-MM-DD)',
|
||||
validate: (v) => /^\d{4}-\d{2}-\d{2}$/.test(v) || '格式 YYYY-MM-DD',
|
||||
});
|
||||
} else {
|
||||
const d = new Date();
|
||||
if (expireChoice === '30d') d.setDate(d.getDate() + 30);
|
||||
else d.setFullYear(d.getFullYear() + 1);
|
||||
expiresAt = d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
const features = await checkbox({
|
||||
message: '授权功能',
|
||||
choices: [
|
||||
{ name: 'order-import · 订单导入', value: 'order-import', checked: true },
|
||||
{ name: 'order-create · 创建订单', value: 'order-create', checked: true },
|
||||
],
|
||||
});
|
||||
|
||||
const summary = [
|
||||
`客户 ID: ${customerId}`,
|
||||
`公司: ${company}`,
|
||||
`指纹: ${fingerprint}`,
|
||||
`版本: ${edition}`,
|
||||
`过期: ${expiresAt}`,
|
||||
`功能: ${features.join(', ')}`,
|
||||
].join('\n');
|
||||
const ok = await confirm({ message: `确认签发?\n${summary}`, default: true });
|
||||
if (!ok) return;
|
||||
|
||||
const result = await apiRequest<GenerateResult>('POST', '/licenses/generate', {
|
||||
customerId,
|
||||
company,
|
||||
machineFingerprint: fingerprint,
|
||||
edition,
|
||||
expiresAt: new Date(expiresAt).toISOString(),
|
||||
features,
|
||||
});
|
||||
|
||||
printBox(
|
||||
'签发成功',
|
||||
[
|
||||
`ID: ${result.id}`,
|
||||
`JTI: ${result.jti}`,
|
||||
`过期: ${result.expiresAt?.slice(0, 10)}`,
|
||||
'',
|
||||
result.licenseKey,
|
||||
].join('\n'),
|
||||
'green',
|
||||
);
|
||||
}
|
||||
|
||||
async function licenseRevoke() {
|
||||
const id = await input({ message: '许可证 ID', validate: (v) => /^\d+$/.test(v) || '请输入数字' });
|
||||
const license = await apiRequest<License>('GET', `/licenses/${Number(id)}`);
|
||||
const ok = await confirm({
|
||||
message: `确认吊销?\nJTI: ${license.jti}\n指纹: ${license.machineFingerprint}`,
|
||||
default: false,
|
||||
});
|
||||
if (!ok) return;
|
||||
await apiRequest('POST', `/licenses/${id}/revoke`);
|
||||
printSuccess(`许可证 #${id} 已吊销`);
|
||||
}
|
||||
|
||||
async function licenseDownload() {
|
||||
const id = await input({ message: '许可证 ID', validate: (v) => /^\d+$/.test(v) || '请输入数字' });
|
||||
const outfile = `license-${id}.key`;
|
||||
const path = await apiDownload(`/licenses/${id}/download`, outfile);
|
||||
printSuccess(`已保存到 ${path}`);
|
||||
}
|
||||
|
||||
export async function licenseMenu() {
|
||||
console.clear();
|
||||
const action = await select({
|
||||
message: '许可证管理',
|
||||
choices: [
|
||||
{ name: '列表', value: 'list' },
|
||||
{ name: '查看', value: 'show' },
|
||||
{ name: '签发', value: 'generate' },
|
||||
{ name: '吊销', value: 'revoke' },
|
||||
{ name: '下载', value: 'download' },
|
||||
{ name: '返回主菜单', value: 'back' },
|
||||
],
|
||||
});
|
||||
|
||||
switch (action) {
|
||||
case 'list':
|
||||
console.clear();
|
||||
await licenseList();
|
||||
await pause();
|
||||
break;
|
||||
case 'show':
|
||||
console.clear();
|
||||
await licenseShow();
|
||||
await pause();
|
||||
break;
|
||||
case 'generate':
|
||||
console.clear();
|
||||
await licenseGenerate();
|
||||
await pause();
|
||||
break;
|
||||
case 'revoke':
|
||||
console.clear();
|
||||
await licenseRevoke();
|
||||
await pause();
|
||||
break;
|
||||
case 'download':
|
||||
console.clear();
|
||||
await licenseDownload();
|
||||
await pause();
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,7 @@ import { input, password } from '@inquirer/prompts';
|
||||
|
||||
import { apiRequest } from '../api/client.js';
|
||||
import { loadConfig, resolveApiUrl, saveConfig } from '../config.js';
|
||||
import { getGlobalOpts, isInteractive } from '../context.js';
|
||||
import { printBanner, printError, printJson, printSuccess } from '../ui/render.js';
|
||||
import { printError, printSuccess } from '../ui/render.js';
|
||||
|
||||
interface LoginResult {
|
||||
token: string;
|
||||
@@ -11,28 +10,23 @@ interface LoginResult {
|
||||
expiresAt: string | null;
|
||||
}
|
||||
|
||||
export async function loginCommand(opts: {
|
||||
url?: string;
|
||||
username?: string;
|
||||
password?: string;
|
||||
}) {
|
||||
const global = getGlobalOpts();
|
||||
export async function loginCommand(opts: { url?: string; username?: string; password?: string }) {
|
||||
const config = await loadConfig();
|
||||
const apiUrl = resolveApiUrl(opts.url || global.url, config);
|
||||
|
||||
if (isInteractive()) printBanner();
|
||||
const apiUrl = resolveApiUrl(opts.url, config);
|
||||
|
||||
let username = opts.username || process.env.ECOM_LICENSE_USERNAME;
|
||||
let pass = opts.password || process.env.ECOM_LICENSE_PASSWORD;
|
||||
|
||||
if (isInteractive()) {
|
||||
if (!username) {
|
||||
username = await input({ message: '用户名', default: username || 'admin' });
|
||||
}
|
||||
if (!pass) {
|
||||
pass = await password({ message: '密码', mask: '*' });
|
||||
}
|
||||
|
||||
if (!username || !pass) {
|
||||
printError('请提供用户名和密码');
|
||||
process.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -48,16 +42,11 @@ export async function loginCommand(opts: {
|
||||
username: result.username,
|
||||
expiresAt: result.expiresAt || undefined,
|
||||
});
|
||||
if (global.json) {
|
||||
printJson({ username: result.username, expiresAt: result.expiresAt, apiUrl });
|
||||
return;
|
||||
}
|
||||
printSuccess(
|
||||
`登录成功 · ${result.username}` +
|
||||
(result.expiresAt ? ` · Token 有效期至 ${result.expiresAt.slice(0, 10)}` : ''),
|
||||
);
|
||||
} catch (e: any) {
|
||||
printError(e?.message || '登录失败');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { apiRequest } from '../api/client.js';
|
||||
import { getGlobalOpts } from '../context.js';
|
||||
import { printBox, printJson, printQuiet } from '../ui/render.js';
|
||||
import { printBox } from '../ui/render.js';
|
||||
|
||||
interface Stats {
|
||||
customerCount: number;
|
||||
@@ -10,18 +9,8 @@ interface Stats {
|
||||
}
|
||||
|
||||
export async function statsCommand() {
|
||||
const global = getGlobalOpts();
|
||||
const stats = await apiRequest<Stats>('GET', '/dashboard/stats');
|
||||
|
||||
if (global.json) {
|
||||
printJson(stats);
|
||||
return;
|
||||
}
|
||||
if (global.quiet) {
|
||||
printQuiet(String(stats.activeLicenseCount));
|
||||
return;
|
||||
}
|
||||
|
||||
printBox(
|
||||
'平台概览',
|
||||
[
|
||||
@@ -0,0 +1,21 @@
|
||||
import { loadConfig, resolveApiUrl } from '../config.js';
|
||||
import { printBox, printError } from '../ui/render.js';
|
||||
|
||||
export async function whoamiCommand() {
|
||||
const config = await loadConfig();
|
||||
const apiUrl = resolveApiUrl(undefined, config);
|
||||
|
||||
if (!config?.token) {
|
||||
printError('未登录,请先登录');
|
||||
return;
|
||||
}
|
||||
|
||||
printBox(
|
||||
'当前会话',
|
||||
[
|
||||
`API: ${apiUrl}`,
|
||||
`用户: ${config?.username || '(未知)'}`,
|
||||
`过期: ${config?.expiresAt || '-'}`,
|
||||
].join('\n'),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function isInteractive(): boolean {
|
||||
return Boolean(process.stdout.isTTY) && !process.env.CI;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env node
|
||||
import { input, select } from '@inquirer/prompts';
|
||||
|
||||
import { customerMenu } from './commands/customer.js';
|
||||
import { licenseMenu } from './commands/license.js';
|
||||
import { loginCommand } from './commands/login.js';
|
||||
import { logoutCommand } from './commands/logout.js';
|
||||
import { statsCommand } from './commands/stats.js';
|
||||
import { whoamiCommand } from './commands/whoami.js';
|
||||
import { loadConfig } from './config.js';
|
||||
import { printBanner } from './ui/render.js';
|
||||
|
||||
async function mainMenu() {
|
||||
console.clear();
|
||||
printBanner();
|
||||
const config = await loadConfig();
|
||||
const isLoggedIn = Boolean(config?.token);
|
||||
|
||||
const choices: { name: string; value: string }[] = [];
|
||||
|
||||
if (!isLoggedIn) {
|
||||
choices.push({ name: '登录', value: 'login' });
|
||||
} else {
|
||||
choices.push(
|
||||
{ name: '当前会话', value: 'whoami' },
|
||||
{ name: '客户管理', value: 'customer' },
|
||||
{ name: '许可证管理', value: 'license' },
|
||||
{ name: '平台统计', value: 'stats' },
|
||||
{ name: '退出登录', value: 'logout' },
|
||||
);
|
||||
}
|
||||
choices.push({ name: '退出', value: 'exit' });
|
||||
|
||||
const action = await select({
|
||||
message: '主菜单',
|
||||
choices,
|
||||
pageSize: 10,
|
||||
});
|
||||
|
||||
switch (action) {
|
||||
case 'login':
|
||||
console.clear();
|
||||
await loginCommand({});
|
||||
await input({ message: '按 Enter 返回' });
|
||||
break;
|
||||
case 'whoami':
|
||||
console.clear();
|
||||
await whoamiCommand();
|
||||
await input({ message: '按 Enter 返回' });
|
||||
break;
|
||||
case 'customer':
|
||||
await customerMenu();
|
||||
break;
|
||||
case 'license':
|
||||
await licenseMenu();
|
||||
break;
|
||||
case 'stats':
|
||||
console.clear();
|
||||
await statsCommand();
|
||||
await input({ message: '按 Enter 返回' });
|
||||
break;
|
||||
case 'logout':
|
||||
console.clear();
|
||||
await logoutCommand();
|
||||
await input({ message: '按 Enter 返回' });
|
||||
break;
|
||||
case 'exit':
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
while (true) {
|
||||
try {
|
||||
await mainMenu();
|
||||
} catch (e: any) {
|
||||
if (e?.name === 'ExitPromptError') process.exit(0);
|
||||
console.error(e?.message || e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -4,11 +4,8 @@ import Table from 'cli-table3';
|
||||
import gradient from 'gradient-string';
|
||||
import ora, { type Ora } from 'ora';
|
||||
|
||||
import { getGlobalOpts, isInteractive } from '../context.js';
|
||||
|
||||
export function printBanner() {
|
||||
if (!isInteractive()) return;
|
||||
const title = gradient.pastel('Ecom License CLI');
|
||||
const title = gradient.pastel('Ecom License TUI');
|
||||
console.log(
|
||||
boxen(`${title}\n${chalk.gray('授权管理平台 · 运营端')}`, {
|
||||
padding: 1,
|
||||
@@ -18,34 +15,19 @@ export function printBanner() {
|
||||
);
|
||||
}
|
||||
|
||||
export function printJson(data: unknown) {
|
||||
console.log(JSON.stringify(data, null, getGlobalOpts().json ? 2 : 0));
|
||||
}
|
||||
|
||||
export function printQuiet(value: string) {
|
||||
console.log(value);
|
||||
}
|
||||
|
||||
export function printSuccess(msg: string) {
|
||||
if (getGlobalOpts().json || getGlobalOpts().quiet) return;
|
||||
console.log(chalk.green('✔'), msg);
|
||||
}
|
||||
|
||||
export function printError(msg: string) {
|
||||
if (getGlobalOpts().json) {
|
||||
printJson({ error: msg });
|
||||
return;
|
||||
}
|
||||
console.error(chalk.red('✖'), msg);
|
||||
}
|
||||
|
||||
export function printInfo(msg: string) {
|
||||
if (getGlobalOpts().json || getGlobalOpts().quiet) return;
|
||||
console.log(chalk.blue('ℹ'), msg);
|
||||
}
|
||||
|
||||
export function printBox(title: string, content: string, borderColor: 'green' | 'cyan' | 'yellow' = 'cyan') {
|
||||
if (!isInteractive()) return;
|
||||
console.log(
|
||||
boxen(content, {
|
||||
title: chalk.bold(title),
|
||||
@@ -56,22 +38,12 @@ export function printBox(title: string, content: string, borderColor: 'green' |
|
||||
}
|
||||
|
||||
export function printTable(headers: string[], rows: string[][]) {
|
||||
if (getGlobalOpts().json) {
|
||||
printJson(
|
||||
rows.map((row) =>
|
||||
Object.fromEntries(headers.map((h, i) => [h, row[i]])),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (getGlobalOpts().quiet) return;
|
||||
const table = new Table({ head: headers.map((h) => chalk.cyan(h)) });
|
||||
rows.forEach((r) => table.push(r));
|
||||
console.log(table.toString());
|
||||
}
|
||||
|
||||
export function printEmptyHint(hint: string) {
|
||||
if (getGlobalOpts().json || getGlobalOpts().quiet) return;
|
||||
console.log(chalk.yellow('暂无数据。'), chalk.gray(hint));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user