dsh-task-board-tapd 0.0.0-stage → 0.5.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/INSTALL.md +137 -0
- package/README.md +139 -2
- package/client.js +699 -0
- package/cordis.patch.yml +19 -0
- package/icon.svg +6 -0
- package/index.js +30 -0
- package/install.ps1 +19 -0
- package/install.sh +19 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +41 -3
- package/src/host/config.js +24 -0
- package/src/host/routes.js +53 -0
- package/src/host/service.js +354 -0
- package/src/host/tapd.js +176 -0
- package/src/host/tools.js +60 -0
- package/src/host/version.js +138 -0
package/src/host/tapd.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process'
|
|
2
|
+
|
|
3
|
+
const DEFAULT_ENDPOINT = 'https://api.tapd.cn'
|
|
4
|
+
|
|
5
|
+
function firstWorkspace(value) {
|
|
6
|
+
return String(value || '').split(',').map(v => v.trim()).find(Boolean) || ''
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function listWorkspaces(config) {
|
|
10
|
+
const configured = config.workspaceIds || config.workspaceId
|
|
11
|
+
const envList = process.env.TAPD_WORKSPACE_IDS || readUserEnv('TAPD_WORKSPACE_IDS')
|
|
12
|
+
const envSingle = process.env.TAPD_WORKSPACE_ID || readUserEnv('TAPD_WORKSPACE_ID')
|
|
13
|
+
const raw = configured || envList || envSingle || ''
|
|
14
|
+
const ids = String(raw).split(',').map(v => v.trim()).filter(Boolean)
|
|
15
|
+
// 去重保序
|
|
16
|
+
return [...new Set(ids)]
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function readUserEnv(name) {
|
|
20
|
+
if (process.platform !== 'win32') return undefined
|
|
21
|
+
try {
|
|
22
|
+
const output = execFileSync('reg', ['query', 'HKCU\\Environment', '/v', name], { encoding: 'utf8', windowsHide: true })
|
|
23
|
+
const line = output.split(/\r?\n/).find(item => item.includes(name))
|
|
24
|
+
if (!line) return undefined
|
|
25
|
+
return line.replace(/^.*?\s+REG_\w+\s+/, '').trim() || undefined
|
|
26
|
+
} catch {
|
|
27
|
+
return undefined
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function tokenFrom(config) {
|
|
32
|
+
const name = config.tokenEnv || 'TAPD_TOKEN'
|
|
33
|
+
return config.token || process.env[name] || readUserEnv(name)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function entityPath(type) {
|
|
37
|
+
return type === 'bug' ? 'bugs' : type === 'task' ? 'tasks' : 'stories'
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 把一个 TAPD 403 权限错误转成可操作的中文提示。 */
|
|
41
|
+
function permissionMessage(path, body, workspaceId) {
|
|
42
|
+
const raw = String(body?.info || '')
|
|
43
|
+
const match = raw.match(/([\w.:]+)::(\w+)/)
|
|
44
|
+
const permission = match ? `${match[1]}::${match[2]}` : ''
|
|
45
|
+
// 说明是写操作(update/status/comment)还是读权限
|
|
46
|
+
const action = /update|status|delete|cancel/i.test(permission)
|
|
47
|
+
? '写操作'
|
|
48
|
+
: /comment/i.test(permission) ? '评论'
|
|
49
|
+
: '读操作'
|
|
50
|
+
const apiHint = permission || (path || '').replace(/^\//, '')
|
|
51
|
+
return `TAPD 权限不足:当前 Token 未获授权(${action} ${apiHint},工作区 ${workspaceId || '-'})。请在 TAPD 开放平台为该应用开通对应接口权限,或在插件配置中更换具备写权限的 Token / tokenEnv。`
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function unwrap(type, row) {
|
|
55
|
+
return row?.[type === 'bug' ? 'Bug' : type === 'task' ? 'Task' : 'Story'] || row || {}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export class TapdClient {
|
|
59
|
+
constructor(config = {}) {
|
|
60
|
+
this.config = config
|
|
61
|
+
this.endpoint = DEFAULT_ENDPOINT
|
|
62
|
+
this.workspaceIds = []
|
|
63
|
+
this.workspaceId = ''
|
|
64
|
+
this.tokenEnv = 'TAPD_TOKEN'
|
|
65
|
+
this.applyConfig(config)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
applyConfig(config = this.config) {
|
|
69
|
+
this.config = config
|
|
70
|
+
this.endpoint = String(config.endpoint || process.env.TAPD_API_ENDPOINT || DEFAULT_ENDPOINT).replace(/\/$/, '')
|
|
71
|
+
this.workspaceIds = listWorkspaces(config)
|
|
72
|
+
const configuredFirst = firstWorkspace(config.workspaceIds)
|
|
73
|
+
const envList = process.env.TAPD_WORKSPACE_IDS || readUserEnv('TAPD_WORKSPACE_IDS')
|
|
74
|
+
const envSingle = process.env.TAPD_WORKSPACE_ID || readUserEnv('TAPD_WORKSPACE_ID')
|
|
75
|
+
const next = String(config.workspaceId || configuredFirst || firstWorkspace(envList) || firstWorkspace(envSingle) || this.workspaceIds[0] || '')
|
|
76
|
+
this.workspaceId = this.workspaceIds.includes(this.workspaceId) ? this.workspaceId : next
|
|
77
|
+
this.tokenEnv = config.tokenEnv || 'TAPD_TOKEN'
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
setWorkspaceId(id) {
|
|
81
|
+
const next = String(id || '').trim()
|
|
82
|
+
if (!next) throw new Error('工作区 ID 不能为空')
|
|
83
|
+
if (this.workspaceIds.length && !this.workspaceIds.includes(next)) {
|
|
84
|
+
throw new Error(`未知工作区:${next}(可用:${this.workspaceIds.join('、')})`)
|
|
85
|
+
}
|
|
86
|
+
this.workspaceId = next
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
token() {
|
|
90
|
+
const token = tokenFrom({ ...this.config, tokenEnv: this.tokenEnv })
|
|
91
|
+
if (!token) throw new Error(`缺少 TAPD Token:请配置环境变量 ${this.tokenEnv}`)
|
|
92
|
+
return token
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async request(method, path, params = {}) {
|
|
96
|
+
const headers = { Authorization: `Bearer ${this.token()}`, Accept: 'application/json' }
|
|
97
|
+
let url = `${this.endpoint}${path}`
|
|
98
|
+
const init = { method, headers }
|
|
99
|
+
if (method === 'GET') {
|
|
100
|
+
const query = new URLSearchParams(Object.entries(params).filter(([, v]) => v !== undefined && v !== null && v !== ''))
|
|
101
|
+
if (query.toString()) url += `?${query}`
|
|
102
|
+
} else {
|
|
103
|
+
headers['content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
|
|
104
|
+
init.body = new URLSearchParams(Object.entries(params).filter(([, v]) => v !== undefined && v !== null && v !== ''))
|
|
105
|
+
}
|
|
106
|
+
const response = await fetch(url, init)
|
|
107
|
+
const text = await response.text()
|
|
108
|
+
let body
|
|
109
|
+
try { body = JSON.parse(text) } catch { throw new Error(`TAPD 返回非 JSON(HTTP ${response.status})`) }
|
|
110
|
+
if (response.status === 403 || /doesn't have permission/i.test(String(body?.info || ''))) {
|
|
111
|
+
throw new Error(permissionMessage(path, body, this.workspaceId))
|
|
112
|
+
}
|
|
113
|
+
if (!response.ok || body.status !== 1) throw new Error(body.info || `TAPD 请求失败(HTTP ${response.status})`)
|
|
114
|
+
return body.data
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async list(type, limit = 200, owner) {
|
|
118
|
+
const fields = type === 'bug'
|
|
119
|
+
? 'id,title,status,reporter,current_owner,created,modified,priority,severity,module,iteration_id,description'
|
|
120
|
+
: 'id,name,status,owner,creator,created,modified,begin,due,priority,priority_label,iteration_id,label,progress,workitem_type_id,description'
|
|
121
|
+
const params = { workspace_id: this.workspaceId, limit, fields }
|
|
122
|
+
if (owner) {
|
|
123
|
+
// TAPD 服务端按处理人过滤:stories/tasks 用 owner,bugs 用 current_owner
|
|
124
|
+
params[type === 'bug' ? 'current_owner' : 'owner'] = owner
|
|
125
|
+
}
|
|
126
|
+
const data = await this.request('GET', `/${entityPath(type)}`, params)
|
|
127
|
+
return Array.isArray(data) ? data.map(row => unwrap(type, row)) : []
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async detail(type, id) {
|
|
131
|
+
const data = await this.request('GET', `/${entityPath(type)}`, { workspace_id: this.workspaceId, id })
|
|
132
|
+
const rows = Array.isArray(data) ? data : []
|
|
133
|
+
return rows.length ? unwrap(type, rows[0]) : undefined
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async fields(type) {
|
|
137
|
+
// TAPD 的 OpenAPI 字段配置接口为 get_fields_info(/fields 会被权限拒绝)
|
|
138
|
+
const data = await this.request('GET', `/${entityPath(type)}/get_fields_info`, { workspace_id: this.workspaceId })
|
|
139
|
+
const field = data?.status || (Array.isArray(data) ? data.find(x => x?.name === 'status') : undefined)
|
|
140
|
+
return field?.options && typeof field.options === 'object' ? field.options : {}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async userInfo() {
|
|
144
|
+
return this.request('GET', '/users/info')
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async update(type, id, patch) {
|
|
148
|
+
// TAPD 的保存/更新语义:POST /{entity} 带 id 即为更新(与 tapd-cli 的
|
|
149
|
+
// `story/bug/task update` 一致);POST /{entity}/update 需要额外的
|
|
150
|
+
// `xxx::update` 权限,多数个人 Token 没有该授权,会返回 403。
|
|
151
|
+
return this.request('POST', `/${entityPath(type)}`, { workspace_id: this.workspaceId, id, ...patch })
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async createStory(input) {
|
|
155
|
+
return this.request('POST', '/stories', {
|
|
156
|
+
workspace_id: this.workspaceId,
|
|
157
|
+
name: input.name,
|
|
158
|
+
description: input.description || '',
|
|
159
|
+
owner: input.owner || undefined,
|
|
160
|
+
priority: input.priority || undefined,
|
|
161
|
+
workitem_type_id: input.workitemTypeId || undefined,
|
|
162
|
+
})
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async addComment(type, id, content, author) {
|
|
166
|
+
return this.request('POST', '/comments', {
|
|
167
|
+
workspace_id: this.workspaceId,
|
|
168
|
+
entry_type: type === 'bug' ? 'bugs' : type === 'task' ? 'tasks' : 'stories',
|
|
169
|
+
entry_id: id,
|
|
170
|
+
description: content,
|
|
171
|
+
author: author || undefined,
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export { entityPath }
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
function json(value) { return [{ type: 'text', text: JSON.stringify(value, null, 2) }] }
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Build a ToolDefinition-compatible plain object. The reference
|
|
5
|
+
* implementation passes these fields to the official `defineTool` helper; we
|
|
6
|
+
* inline the same shape (parameters = field map with `required` per field) so
|
|
7
|
+
* the bundle stays dependency-free and resolvable in every profile.
|
|
8
|
+
*/
|
|
9
|
+
function tool(name, description, fields, execute) {
|
|
10
|
+
const properties = {}
|
|
11
|
+
const required = []
|
|
12
|
+
for (const [key, spec] of Object.entries(fields)) {
|
|
13
|
+
const { required: isRequired, ...schema } = spec
|
|
14
|
+
properties[key] = schema
|
|
15
|
+
if (isRequired) required.push(key)
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
name,
|
|
19
|
+
description,
|
|
20
|
+
parameters: { type: 'object', properties, ...(required.length ? { required } : {}) },
|
|
21
|
+
output: { schema: { type: 'object' }, render: (_args, value) => json(value) },
|
|
22
|
+
isConcurrencySafe: () => false,
|
|
23
|
+
execute,
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function registerTools(ctx, service) {
|
|
28
|
+
let registry
|
|
29
|
+
try { registry = ctx.get('tools') } catch { registry = undefined }
|
|
30
|
+
if (!registry || typeof registry.register !== 'function') return () => {}
|
|
31
|
+
const defs = [
|
|
32
|
+
tool('tapd_board_list', '读取 TAPD 任务看板。可按实体类型 story/task/bug 和关键词过滤。', {
|
|
33
|
+
type: { type: 'string', enum: ['all', 'story', 'task', 'bug'], description: '实体类型,默认 all' },
|
|
34
|
+
query: { type: 'string', description: '关键词,匹配标题/ID/处理人' },
|
|
35
|
+
}, async args => ({ ok: true, workspaceId: service.client.workspaceId, items: await service.listForTool(args.type, args.query) })),
|
|
36
|
+
tool('tapd_board_get', '读取一个 TAPD 工作项详情,包括描述、状态、处理人和 TAPD 链接。', {
|
|
37
|
+
type: { type: 'string', enum: ['story', 'task', 'bug'], required: true, description: '实体类型' },
|
|
38
|
+
id: { type: 'string', required: true, description: '工作项 ID' },
|
|
39
|
+
}, async args => ({ ok: true, item: await service.detail(args.type, args.id) })),
|
|
40
|
+
tool('tapd_board_move', '修改 TAPD 工作项状态。status 必须使用看板返回的物理状态值。', {
|
|
41
|
+
type: { type: 'string', enum: ['story', 'task', 'bug'], required: true, description: '实体类型' },
|
|
42
|
+
id: { type: 'string', required: true, description: '工作项 ID' },
|
|
43
|
+
status: { type: 'string', required: true, description: '目标状态物理值' },
|
|
44
|
+
}, async args => ({ ok: true, state: await service.apply('move', args) })),
|
|
45
|
+
tool('tapd_board_comment', '向 TAPD 工作项添加评论。', {
|
|
46
|
+
type: { type: 'string', enum: ['story', 'task', 'bug'], required: true, description: '实体类型' },
|
|
47
|
+
id: { type: 'string', required: true, description: '工作项 ID' },
|
|
48
|
+
content: { type: 'string', required: true, description: '评论内容' },
|
|
49
|
+
}, async args => ({ ok: true, state: await service.apply('comment', args) })),
|
|
50
|
+
tool('tapd_board_create_story', '在 TAPD 中创建一条需求(Story),创建后进入看板。', {
|
|
51
|
+
name: { type: 'string', required: true, description: '需求标题' },
|
|
52
|
+
description: { type: 'string', description: '需求描述' },
|
|
53
|
+
owner: { type: 'string', description: '处理人,默认当前用户' },
|
|
54
|
+
priority: { type: 'string', description: '优先级 1/2/3' },
|
|
55
|
+
}, async args => ({ ok: true, state: await service.apply('createStory', args) })),
|
|
56
|
+
]
|
|
57
|
+
const disposers = []
|
|
58
|
+
for (const definition of defs) { try { const dispose = registry.register(definition); if (typeof dispose === 'function') disposers.push(dispose) } catch (error) { console.warn('[tapd-task-board] tool registration failed', definition.name, error) } }
|
|
59
|
+
return () => disposers.splice(0).forEach(dispose => dispose())
|
|
60
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
|
|
6
|
+
/** 包根 package.json(Host 文件位于 <pkg>/src/host/version.js)。 */
|
|
7
|
+
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..')
|
|
8
|
+
const packageFile = path.join(packageRoot, 'package.json')
|
|
9
|
+
|
|
10
|
+
export const DEFAULT_REGISTRY = 'https://registry.npmjs.org'
|
|
11
|
+
export const DEFAULT_PACKAGE_NAME = 'dsh-task-board-tapd'
|
|
12
|
+
|
|
13
|
+
function readPackageJson() {
|
|
14
|
+
try {
|
|
15
|
+
const value = JSON.parse(readFileSync(packageFile, 'utf8'))
|
|
16
|
+
return value && typeof value === 'object' ? value : {}
|
|
17
|
+
} catch {
|
|
18
|
+
return {}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 当前安装版本(来自插件自身 package.json)。 */
|
|
23
|
+
export function currentVersion() {
|
|
24
|
+
const version = String(readPackageJson().version || '').trim()
|
|
25
|
+
return version || '0.0.0'
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 当前安装包名(发布到 npm 后即为 npm 包名)。 */
|
|
29
|
+
export function packageName() {
|
|
30
|
+
const name = String(readPackageJson().name || '').trim()
|
|
31
|
+
return name || DEFAULT_PACKAGE_NAME
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 版本比较:a > b 返回 1,a < b 返回 -1,相等返回 0。仅支持常见 semver(含预发布后缀)。 */
|
|
35
|
+
export function compareVersions(a, b) {
|
|
36
|
+
const normalize = value => String(value || '')
|
|
37
|
+
.trim()
|
|
38
|
+
.replace(/^v/i, '')
|
|
39
|
+
.split('+')[0]
|
|
40
|
+
const parse = value => {
|
|
41
|
+
const [core, prerelease] = normalize(value).split('-')
|
|
42
|
+
const nums = core.split('.').map(part => {
|
|
43
|
+
const n = parseInt(part, 10)
|
|
44
|
+
return Number.isFinite(n) ? n : 0
|
|
45
|
+
})
|
|
46
|
+
while (nums.length < 3) nums.push(0)
|
|
47
|
+
return { nums: nums.slice(0, 3), prerelease: prerelease || '' }
|
|
48
|
+
}
|
|
49
|
+
const left = parse(a)
|
|
50
|
+
const right = parse(b)
|
|
51
|
+
for (let i = 0; i < 3; i += 1) {
|
|
52
|
+
if (left.nums[i] > right.nums[i]) return 1
|
|
53
|
+
if (left.nums[i] < right.nums[i]) return -1
|
|
54
|
+
}
|
|
55
|
+
// 预发布版本低于同号正式版(1.0.0-beta < 1.0.0)
|
|
56
|
+
if (left.prerelease && !right.prerelease) return -1
|
|
57
|
+
if (!left.prerelease && right.prerelease) return 1
|
|
58
|
+
if (left.prerelease && right.prerelease) {
|
|
59
|
+
return left.prerelease.localeCompare(right.prerelease, 'en', { numeric: true })
|
|
60
|
+
}
|
|
61
|
+
return 0
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function normalizeRegistry(value) {
|
|
65
|
+
const registry = String(value || '').trim() || DEFAULT_REGISTRY
|
|
66
|
+
if (!/^https?:\/\//i.test(registry)) throw new Error(`registry 不是合法的 URL:${registry}`)
|
|
67
|
+
return registry.replace(/\/+$/, '')
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const PACKAGE_NAME_RE = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i
|
|
71
|
+
const VERSION_RE = /^[0-9A-Za-z][0-9A-Za-z.+_-]*$/
|
|
72
|
+
|
|
73
|
+
/** 查询 npm registry 上的最新版本。 */
|
|
74
|
+
export async function fetchLatest(options = {}) {
|
|
75
|
+
const registry = normalizeRegistry(options.registry)
|
|
76
|
+
const name = String(options.packageName || packageName()).trim()
|
|
77
|
+
if (!PACKAGE_NAME_RE.test(name)) throw new Error(`npm 包名不合法:${name}`)
|
|
78
|
+
const url = `${registry}/${name.split('/').map(encodeURIComponent).join('/')}/latest`
|
|
79
|
+
let response
|
|
80
|
+
try {
|
|
81
|
+
response = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(15000) })
|
|
82
|
+
} catch (error) {
|
|
83
|
+
throw new Error(`无法访问 npm registry(${registry}):${error?.message || error}`)
|
|
84
|
+
}
|
|
85
|
+
if (response.status === 404) {
|
|
86
|
+
throw new Error(`npm 上还没有包 ${name} 的发布版本(404)。如果你尚未发布,请先完成 npm publish。`)
|
|
87
|
+
}
|
|
88
|
+
if (!response.ok) throw new Error(`npm registry 查询失败(HTTP ${response.status})`)
|
|
89
|
+
let body
|
|
90
|
+
try { body = await response.json() } catch { throw new Error('npm registry 返回非 JSON') }
|
|
91
|
+
const version = String(body?.version || '').trim()
|
|
92
|
+
if (!version) throw new Error(`npm 上包 ${name} 没有有效版本号`)
|
|
93
|
+
return {
|
|
94
|
+
packageName: name,
|
|
95
|
+
registry,
|
|
96
|
+
latest: version,
|
|
97
|
+
current: currentVersion(),
|
|
98
|
+
updateAvailable: compareVersions(version, currentVersion()) > 0,
|
|
99
|
+
publishedAt: body?.time || '',
|
|
100
|
+
distTarball: body?.dist?.tarball || '',
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 通过 dsh CLI 把插件更新到指定版本:`dsh plugin --profile <profile> add <pkg>@<version>`。
|
|
106
|
+
* 返回执行结果;失败时抛出带 stderr 摘要的错误。更新后需要重启 DSH 才会加载新版本。
|
|
107
|
+
*/
|
|
108
|
+
export function installVersion(options = {}) {
|
|
109
|
+
const profile = String(options.profile || process.env.DSH_PROFILE || '').trim()
|
|
110
|
+
if (!profile || !/^[A-Za-z0-9._-]+$/.test(profile)) throw new Error(`无法确定当前 DSH profile(DSH_PROFILE=${profile || '空'})`)
|
|
111
|
+
const name = String(options.packageName || packageName()).trim()
|
|
112
|
+
if (!PACKAGE_NAME_RE.test(name)) throw new Error(`npm 包名不合法:${name}`)
|
|
113
|
+
const version = String(options.version || '').trim()
|
|
114
|
+
if (!VERSION_RE.test(version)) throw new Error(`版本号不合法:${version}`)
|
|
115
|
+
const target = `${name}@${version}`
|
|
116
|
+
const registry = normalizeRegistry(options.registry)
|
|
117
|
+
const args = ['plugin', '--profile', profile, 'add', target, '--registry', registry]
|
|
118
|
+
return new Promise((resolve, reject) => {
|
|
119
|
+
const isWindows = process.platform === 'win32'
|
|
120
|
+
const command = isWindows ? 'cmd.exe' : 'dsh'
|
|
121
|
+
const argv = isWindows ? ['/d', '/s', '/c', `dsh ${args.map(quoteArg).join(' ')}`] : args
|
|
122
|
+
execFile(command, argv, { timeout: 180000, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => {
|
|
123
|
+
const tail = text => String(text || '').trim().split(/\r?\n/).slice(-6).join('\n')
|
|
124
|
+
if (error) {
|
|
125
|
+
reject(new Error(`插件更新失败:${error.message}${tail(stderr) ? `\n${tail(stderr)}` : ''}${tail(stdout) ? `\n${tail(stdout)}` : ''}`))
|
|
126
|
+
return
|
|
127
|
+
}
|
|
128
|
+
resolve({ profile, packageName: name, version, stdout: tail(stdout), stderr: tail(stderr) })
|
|
129
|
+
})
|
|
130
|
+
})
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 给 cmd.exe 命令行加引号(参数均为受校验的安全字符,这里只处理空白与引号)。 */
|
|
134
|
+
function quoteArg(value) {
|
|
135
|
+
const text = String(value)
|
|
136
|
+
if (!/[\s"]/.test(text)) return text
|
|
137
|
+
return `"${text.replace(/"/g, '\\"')}"`
|
|
138
|
+
}
|