@vitex/tcm-cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,60 @@
1
+ import { pick, post, string, array, pageNum, pageSize, id, appendFile } from './common.js'
2
+
3
+ export default {
4
+ summary: '素材',
5
+ commands: {
6
+ list: {
7
+ summary: '分页查询素材',
8
+ params: {
9
+ keyword: string('关键词'),
10
+ type: string('类型:IMAGE / EMOJI'),
11
+ tags: array('标签'),
12
+ pageNum: pageNum(1),
13
+ pageSize: pageSize(20),
14
+ },
15
+ build: (p) => post('/api/comment/material/page', pick(p, ['keyword', 'type', 'tags', 'pageNum', 'pageSize'])),
16
+ },
17
+ get: {
18
+ summary: '素材详情',
19
+ params: { id: id('素材 ID') },
20
+ build: (p) => post('/api/comment/material/detail', pick(p, ['id'])),
21
+ },
22
+ create: {
23
+ summary: '通过 URL 创建素材',
24
+ params: {
25
+ url: string('素材 URL', { required: true }),
26
+ name: string('名称'),
27
+ description: string('描述'),
28
+ tags: array('标签'),
29
+ },
30
+ build: (p) => post('/api/comment/material/create', pick(p, ['url', 'name', 'description', 'tags'])),
31
+ },
32
+ update: {
33
+ summary: '编辑素材',
34
+ params: {
35
+ id: id('素材 ID'),
36
+ name: string('名称'),
37
+ description: string('描述'),
38
+ tags: array('标签'),
39
+ },
40
+ build: (p) => post('/api/comment/material/update', pick(p, ['id', 'name', 'description', 'tags'])),
41
+ },
42
+ upload: {
43
+ summary: '上传素材文件(multipart)',
44
+ params: {
45
+ file: string('本地文件路径', { required: true }),
46
+ name: string('名称'),
47
+ description: string('描述'),
48
+ tags: array('标签'),
49
+ },
50
+ build: async (p) => {
51
+ const formData = new FormData()
52
+ if (p.name !== undefined) formData.append('name', p.name)
53
+ if (p.description !== undefined) formData.append('description', p.description)
54
+ formData.append('tags', JSON.stringify(p.tags || []))
55
+ await appendFile(formData, 'file', p.file)
56
+ return { method: 'POST', path: '/api/comment/material/upload', formData }
57
+ },
58
+ },
59
+ },
60
+ }
@@ -0,0 +1,55 @@
1
+ import { pick, post, get, string, array, pageNum, pageSize, id } from './common.js'
2
+
3
+ export default {
4
+ summary: '用户',
5
+ commands: {
6
+ list: {
7
+ summary: '分页查询用户(管理员)',
8
+ params: {
9
+ keyword: string('关键词'),
10
+ pageNum: pageNum(1),
11
+ pageSize: pageSize(20),
12
+ },
13
+ build: (p) => post('/api/user/page', pick(p, ['keyword', 'pageNum', 'pageSize'])),
14
+ },
15
+ me: {
16
+ summary: '当前登录用户',
17
+ params: {},
18
+ build: () => get('/api/user/me'),
19
+ },
20
+ create: {
21
+ summary: '新建用户(返回仅此一次可见的明文密码)',
22
+ params: {
23
+ name: string('用户名', { required: true }),
24
+ description: string('备注'),
25
+ roles: array('角色,例如 ADMIN', { items: 'string' }),
26
+ },
27
+ build: (p) => post('/api/user/create', pick(p, ['name', 'description', 'roles'])),
28
+ },
29
+ update: {
30
+ summary: '编辑用户',
31
+ params: {
32
+ id: id('用户 ID'),
33
+ name: string('用户名', { required: true }),
34
+ description: string('备注'),
35
+ roles: array('角色,例如 ADMIN', { items: 'string' }),
36
+ },
37
+ build: (p) => post('/api/user/update', pick(p, ['id', 'name', 'description', 'roles'])),
38
+ },
39
+ 'reset-password': {
40
+ summary: '重置用户密码(返回仅此一次可见的明文密码)',
41
+ params: { id: id('用户 ID') },
42
+ build: (p) => post('/api/user/resetpassword', pick(p, ['id'])),
43
+ },
44
+ 'api-key': {
45
+ summary: '获取当前用户 API Key(旧 Key 立即失效)',
46
+ params: {},
47
+ build: () => post('/api/user/apikey'),
48
+ },
49
+ 'change-password': {
50
+ summary: '修改当前用户密码',
51
+ params: { password: string('新密码', { required: true }) },
52
+ build: (p) => post('/api/user/changepassword', pick(p, ['password'])),
53
+ },
54
+ },
55
+ }
@@ -0,0 +1,43 @@
1
+ import { pick, post, date, string, array } from './common.js'
2
+
3
+ const period = () => ({
4
+ startDate: date('开始日期'),
5
+ endDate: date('结束日期'),
6
+ })
7
+
8
+ const taskPeriod = () => ({
9
+ ...period(),
10
+ types: array('任务类型多选,例如 EXEC,AWEMES'),
11
+ status: string('任务状态单选,例如 SUCCESS'),
12
+ })
13
+
14
+ /** endpoint 是后端路径(必须与命令名一致),summary 是中文说明。 */
15
+ const metric = (endpoint, summary, paramsFactory = period) => ({
16
+ summary,
17
+ params: paramsFactory(),
18
+ build: (p) =>
19
+ post(`/api/workbench/${endpoint}`, pick(p, ['startDate', 'endDate', 'types', 'status'])),
20
+ })
21
+
22
+ export default {
23
+ summary: '工作台统计',
24
+ commands: {
25
+ 'account-cards': metric('account-cards', '账号卡片', () => ({})),
26
+ 'machine-cards': metric('machine-cards', '机器卡片', () => ({})),
27
+ accounts: metric('accounts', '账号数量'),
28
+ comments: metric('comments', '评论数量'),
29
+ awemes: metric('awemes', '作品数量'),
30
+ 'comment-records': metric('comment-records', '评论记录数量'),
31
+ 'comment-candidates': metric('comment-candidates', '评论候选数量'),
32
+ 'comment-likes': metric('comment-likes', '评论点赞数量'),
33
+ 'comment-overview-trend': metric('comment-overview-trend', '评论概览趋势'),
34
+ 'top-comments': metric('top-comments', '热门评论'),
35
+ tasks: metric('tasks', '任务数量', taskPeriod),
36
+ 'task-success-rate': metric('task-success-rate', '任务成功率', taskPeriod),
37
+ 'task-type-trend': metric('task-type-trend', '任务类型趋势', taskPeriod),
38
+ 'task-status-trend': metric('task-status-trend', '任务状态趋势', taskPeriod),
39
+ 'task-type-share': metric('task-type-share', '任务类型分布', taskPeriod),
40
+ 'task-status-share': metric('task-status-share', '任务状态分布', taskPeriod),
41
+ 'task-error-top': metric('task-error-top', '任务错误 Top', taskPeriod),
42
+ },
43
+ }
package/src/config.js ADDED
@@ -0,0 +1,8 @@
1
+ import { createRequire } from 'node:module'
2
+
3
+ const require = createRequire(import.meta.url)
4
+ const pkg = require('../package.json')
5
+
6
+ export const VERSION = pkg.version
7
+ export const DEFAULT_SERVER = process.env.TCM_SERVER_URL || 'https://tcm.58corp.com/'
8
+ export const DEFAULT_TIMEOUT_MS = 30000
package/src/http.js ADDED
@@ -0,0 +1,97 @@
1
+ export class ApiError extends Error {
2
+ constructor(message, { code = 0, status = 0, data = null } = {}) {
3
+ super(message)
4
+ this.name = 'ApiError'
5
+ this.code = code
6
+ this.status = status
7
+ this.data = data
8
+ }
9
+ }
10
+
11
+ function messageForStatus(status) {
12
+ if (status === 401 || status === 403) return '未登录或用户 Key 已失效'
13
+ if (status === 404) return '请求的内容不存在'
14
+ if (status >= 500) return '服务暂时不可用,请稍后重试'
15
+ if (status >= 400) return '请求参数有误'
16
+ return '请求失败'
17
+ }
18
+
19
+ /**
20
+ * 调用后端接口并拆解统一的 ApiResponse 包装。
21
+ * 成功返回 data;HTTP 非 2xx 或 code !== 1 抛出 ApiError。
22
+ */
23
+ export async function request({
24
+ serverUrl,
25
+ apiKey,
26
+ method = 'POST',
27
+ path,
28
+ json,
29
+ formData,
30
+ timeoutMs = 30000,
31
+ }) {
32
+ const base = String(serverUrl || '').replace(/\/+$/, '')
33
+ if (!base) throw new ApiError('缺少服务端地址(serverUrl)')
34
+ const url = `${base}${path}`
35
+
36
+ const headers = { Accept: 'application/json' }
37
+ if (apiKey) headers.Authorization = `ApiKey ${apiKey}`
38
+
39
+ let body
40
+ if (formData) {
41
+ body = formData
42
+ } else if (json !== undefined) {
43
+ headers['Content-Type'] = 'application/json'
44
+ body = JSON.stringify(json)
45
+ }
46
+
47
+ const controller = new AbortController()
48
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
49
+ let response
50
+ try {
51
+ response = await fetch(url, { method, headers, body, signal: controller.signal })
52
+ } catch (cause) {
53
+ const reason = cause?.name === 'AbortError' ? `请求超时(${timeoutMs}ms)` : cause?.message || '网络请求失败'
54
+ throw new ApiError(`无法连接后端服务(${url}):${reason}`, {
55
+ data: { cause: cause?.message || null },
56
+ })
57
+ } finally {
58
+ clearTimeout(timer)
59
+ }
60
+
61
+ const text = await response.text().catch(() => '')
62
+ let payload = null
63
+ if (text.trim()) {
64
+ try {
65
+ payload = JSON.parse(text)
66
+ } catch {
67
+ payload = text
68
+ }
69
+ }
70
+
71
+ const envelope = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : null
72
+ const businessCode = envelope?.code
73
+ const failed = !response.ok || (businessCode !== undefined && businessCode !== 1)
74
+
75
+ if (failed) {
76
+ const message =
77
+ (typeof payload === 'string' ? payload.trim() : '') ||
78
+ envelope?.message ||
79
+ messageForStatus(response.status)
80
+ let data = envelope?.data ?? envelope ?? null
81
+ if (response.status === 429) {
82
+ const retryAfterSeconds = Number(response.headers.get('retry-after'))
83
+ const retryAfterMs =
84
+ Number.isFinite(retryAfterSeconds) && retryAfterSeconds > 0
85
+ ? Math.round(retryAfterSeconds * 1000)
86
+ : null
87
+ data = { ...(data && typeof data === 'object' ? data : {}), retryAfterMs }
88
+ }
89
+ throw new ApiError(message, {
90
+ code: businessCode ?? response.status,
91
+ status: response.status,
92
+ data,
93
+ })
94
+ }
95
+
96
+ return businessCode !== undefined ? envelope.data ?? null : payload
97
+ }
package/src/index.js ADDED
@@ -0,0 +1,287 @@
1
+ import { request, ApiError } from './http.js'
2
+ import { readAuth, resolveAuthFile } from './auth.js'
3
+ import { DEFAULT_SERVER, DEFAULT_TIMEOUT_MS, VERSION } from './config.js'
4
+ import {
5
+ UsageError,
6
+ buildParamValues,
7
+ parseCommandArgs,
8
+ } from './args.js'
9
+ import { groups, topCommands } from './commands/index.js'
10
+
11
+ const GLOBAL_OPTIONS = {
12
+ help: { type: 'boolean', short: 'h' },
13
+ version: { type: 'boolean', short: 'V' },
14
+ server: { type: 'string' },
15
+ key: { type: 'string' },
16
+ 'auth-file': { type: 'string' },
17
+ timeout: { type: 'string' },
18
+ compact: { type: 'boolean' },
19
+ }
20
+
21
+ const GLOBAL_HELP = [
22
+ ['--server <url>', '覆盖服务端地址'],
23
+ ['--key <key>', '覆盖用户 Key'],
24
+ ['--auth-file <path>', '授权文件路径(默认 ~/.tmc/auth.json)'],
25
+ ['--timeout <ms>', '请求超时毫秒数(默认 30000)'],
26
+ ['--compact', '紧凑 JSON 输出(单行)'],
27
+ ['--version, -V', '显示版本号'],
28
+ ['--help, -h', '显示帮助'],
29
+ ]
30
+
31
+ const VALUE_FLAGS = new Set(['--server', '--key', '--auth-file', '--timeout'])
32
+ const TOP_LEVEL = new Set(['login', 'logout', 'status', 'help', 'version'])
33
+
34
+ /** 从 argv 中剥离命令词,剩余参数交给 parseArgs。 */
35
+ function splitArgs(argv) {
36
+ const command = []
37
+ const rest = []
38
+ for (let i = 0; i < argv.length; i += 1) {
39
+ const token = argv[i]
40
+ const isFirst = command.length === 0
41
+ const isSecond = command.length === 1 && !TOP_LEVEL.has(command[0])
42
+ if ((isFirst || isSecond) && !token.startsWith('-')) {
43
+ command.push(token)
44
+ continue
45
+ }
46
+ rest.push(token)
47
+ const next = argv[i + 1]
48
+ if (!token.includes('=') && VALUE_FLAGS.has(token) && next !== undefined && (next === '-' || !next.startsWith('-'))) {
49
+ rest.push(next)
50
+ i += 1
51
+ }
52
+ }
53
+ return { command, rest }
54
+ }
55
+
56
+ function pickGlobal(values) {
57
+ return {
58
+ server: values.server,
59
+ key: values.key,
60
+ authFile: values['auth-file'],
61
+ timeout: values.timeout,
62
+ compact: Boolean(values.compact),
63
+ }
64
+ }
65
+
66
+ function resolveContext(global) {
67
+ const file = resolveAuthFile(global.authFile)
68
+ const stored = readAuth(file) || {}
69
+ const serverUrl = String(
70
+ global.server || process.env.TCM_SERVER_URL || stored.serverUrl || DEFAULT_SERVER,
71
+ ).replace(/\/+$/, '')
72
+ const apiKey = global.key || process.env.TCM_API_KEY || stored.apiKey || ''
73
+ return { file, stored, serverUrl, apiKey }
74
+ }
75
+
76
+ function parseTimeout(raw) {
77
+ if (raw === undefined) return DEFAULT_TIMEOUT_MS
78
+ const value = Number(raw)
79
+ if (!Number.isFinite(value) || value <= 0) {
80
+ throw new UsageError('--timeout 需要是正整数(毫秒)')
81
+ }
82
+ return value
83
+ }
84
+
85
+ function emit(value, compact) {
86
+ const text = compact ? JSON.stringify(value ?? null) : JSON.stringify(value ?? null, null, 2)
87
+ process.stdout.write(`${text}\n`)
88
+ }
89
+
90
+ async function runCommand(command, rest, meta) {
91
+ const { values, positionals } = parseCommandArgs(command, rest, GLOBAL_OPTIONS)
92
+ if (values.help) {
93
+ printCommandHelp(meta, command)
94
+ return 0
95
+ }
96
+ if (values.version) {
97
+ process.stdout.write(`${VERSION}\n`)
98
+ return 0
99
+ }
100
+ const global = pickGlobal(values)
101
+
102
+ if (command.run) {
103
+ const result = await command.run({ values, positionals, global, request, resolveContext })
104
+ emit(result, global.compact)
105
+ return 0
106
+ }
107
+
108
+ const ctx = resolveContext(global)
109
+ if (command.auth !== false && !ctx.apiKey) {
110
+ throw new ApiError('未登录,请先运行:tcm login --key <userKey>', { code: 401, status: 401 })
111
+ }
112
+
113
+ const params = buildParamValues(command, values)
114
+ const spec = await command.build(params, ctx)
115
+ const result = await request({
116
+ serverUrl: ctx.serverUrl,
117
+ apiKey: ctx.apiKey,
118
+ method: spec.method,
119
+ path: spec.path,
120
+ json: spec.json,
121
+ formData: spec.formData,
122
+ timeoutMs: parseTimeout(global.timeout),
123
+ })
124
+ emit(result, global.compact)
125
+ return 0
126
+ }
127
+
128
+ function handleError(error, compact) {
129
+ let type = 'Error'
130
+ let exitCode = 1
131
+ let body = { message: error?.message || String(error) }
132
+
133
+ if (error instanceof UsageError) {
134
+ type = 'UsageError'
135
+ exitCode = 2
136
+ } else if (error instanceof ApiError) {
137
+ type = 'ApiError'
138
+ body = { message: error.message, code: error.code, status: error.status, data: error.data }
139
+ }
140
+
141
+ const output = { error: { type, ...body } }
142
+ const text = compact ? JSON.stringify(output) : JSON.stringify(output, null, 2)
143
+ process.stderr.write(`${text}\n`)
144
+ return exitCode
145
+ }
146
+
147
+ function typeLabel(spec) {
148
+ const base =
149
+ { string: 'string', number: 'number', boolean: 'boolean', array: 'array', json: 'json' }[spec.type] ||
150
+ 'string'
151
+ return spec.type === 'array' ? `${base}(可重复/逗号分隔)` : base
152
+ }
153
+
154
+ function paramLines(params = {}) {
155
+ const entries = Object.entries(params)
156
+ if (entries.length === 0) return [' (无参数)']
157
+ const width = Math.max(...entries.map(([name]) => `--${name}`.length))
158
+ return entries.map(([name, spec]) => {
159
+ const flag = `--${name}`.padEnd(width)
160
+ const bits = [typeLabel(spec)]
161
+ if (spec.required) bits.push('必填')
162
+ if (spec.default !== undefined) bits.push(`默认 ${JSON.stringify(spec.default)}`)
163
+ const extras = bits.join(',')
164
+ return ` ${flag} ${spec.desc || ''}${spec.desc ? ' ' : ''}(${extras})`
165
+ })
166
+ }
167
+
168
+ function printGlobalOptions() {
169
+ const width = Math.max(...GLOBAL_HELP.map(([flag]) => flag.length))
170
+ const lines = ['全局选项:']
171
+ for (const [flag, desc] of GLOBAL_HELP) lines.push(` ${flag.padEnd(width)} ${desc}`)
172
+ return lines
173
+ }
174
+
175
+ function printRootHelp() {
176
+ const lines = [
177
+ `TCM CLI v${VERSION}`,
178
+ '',
179
+ '面向 agent 的命令行工具:业务输出为 JSON(stdout),错误为 JSON(stderr)。',
180
+ '',
181
+ '用法:',
182
+ ' tcm <资源> <操作> [选项]',
183
+ ' tcm <命令> [选项]',
184
+ '',
185
+ '通用命令:',
186
+ ]
187
+ const topWidth = Math.max(...Object.keys(topCommands).map((name) => name.length))
188
+ for (const [name, command] of Object.entries(topCommands)) {
189
+ lines.push(` ${name.padEnd(topWidth)} ${command.summary}`)
190
+ }
191
+ lines.push('', '资源命令:')
192
+ const groupWidth = Math.max(...Object.keys(groups).map((name) => name.length))
193
+ for (const [name, group] of Object.entries(groups)) {
194
+ lines.push(` ${name.padEnd(groupWidth)} ${group.summary}`)
195
+ }
196
+ lines.push('', ...printGlobalOptions())
197
+ lines.push('', '运行 tcm help <资源> 查看资源的操作;运行 tcm <资源> <操作> --help 查看参数。')
198
+ process.stdout.write(`${lines.join('\n')}\n`)
199
+ }
200
+
201
+ function printGroupHelp(name, group) {
202
+ const lines = [`用法: tcm ${name} <操作> [选项]`, '', group.summary, '', '操作:']
203
+ const width = Math.max(...Object.keys(group.commands).map((action) => action.length))
204
+ for (const [action, command] of Object.entries(group.commands)) {
205
+ lines.push(` ${action.padEnd(width)} ${command.summary}`)
206
+ }
207
+ lines.push('', `运行 tcm ${name} <操作> --help 查看参数。`)
208
+ process.stdout.write(`${lines.join('\n')}\n`)
209
+ }
210
+
211
+ function printCommandHelp(meta, command) {
212
+ const lines = [`用法: tcm ${meta.name} [选项]`, '', command.summary, '', '参数:', ...paramLines(command.params)]
213
+ lines.push('', ...printGlobalOptions())
214
+ if (command.examples?.length) {
215
+ lines.push('', '示例:')
216
+ for (const example of command.examples) lines.push(` ${example}`)
217
+ }
218
+ process.stdout.write(`${lines.join('\n')}\n`)
219
+ }
220
+
221
+ function runHelp(rest) {
222
+ const parts = rest.filter((token) => !token.startsWith('-'))
223
+ if (parts.length === 0) {
224
+ printRootHelp()
225
+ return 0
226
+ }
227
+ const [groupName, actionName] = parts
228
+ const group = groups[groupName]
229
+ if (!group) {
230
+ printRootHelp()
231
+ return 0
232
+ }
233
+ if (!actionName) {
234
+ printGroupHelp(groupName, group)
235
+ return 0
236
+ }
237
+ const command = group.commands[actionName]
238
+ if (!command) {
239
+ printGroupHelp(groupName, group)
240
+ return 0
241
+ }
242
+ printCommandHelp({ name: `${groupName} ${actionName}` }, command)
243
+ return 0
244
+ }
245
+
246
+ export async function main(argv) {
247
+ const { command, rest } = splitArgs(argv)
248
+ const compact = argv.includes('--compact')
249
+
250
+ try {
251
+ if (command.length === 0) {
252
+ if (argv.includes('--version') || argv.includes('-V')) {
253
+ process.stdout.write(`${VERSION}\n`)
254
+ return 0
255
+ }
256
+ printRootHelp()
257
+ return 0
258
+ }
259
+
260
+ const first = command[0]
261
+ if (first === 'version') {
262
+ process.stdout.write(`${VERSION}\n`)
263
+ return 0
264
+ }
265
+ if (first === 'help') return runHelp(rest)
266
+
267
+ if (topCommands[first]) {
268
+ return await runCommand(topCommands[first], rest, { name: first })
269
+ }
270
+
271
+ const group = groups[first]
272
+ if (!group) throw new UsageError(`未知命令:${first}(运行 tcm help 查看可用命令)`)
273
+ if (command.length < 2) {
274
+ printGroupHelp(first, group)
275
+ return 0
276
+ }
277
+
278
+ const actionName = command[1]
279
+ const action = group.commands[actionName]
280
+ if (!action) {
281
+ throw new UsageError(`未知操作:${first} ${actionName}(运行 tcm help ${first} 查看可用操作)`)
282
+ }
283
+ return await runCommand(action, rest, { name: `${first} ${actionName}` })
284
+ } catch (error) {
285
+ return handleError(error, compact)
286
+ }
287
+ }