dsh-pluginmarket-plus 0.1.0 → 0.2.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/client.js +1945 -3
- package/lib/index.js +532 -1
- package/lib/store.js +99 -1
- package/lib/updates.js +769 -0
- package/package.json +4 -1
package/lib/index.js
CHANGED
|
@@ -26,6 +26,7 @@ import { join, resolve } from 'node:path'
|
|
|
26
26
|
import z from '@deepseek-ai/schemastery'
|
|
27
27
|
import { CacheStore, sourceId } from './store.js'
|
|
28
28
|
import { fetchIndex, indexTitle, messageOf } from './refresh.js'
|
|
29
|
+
import { buildGitSpec, checkCandidates, collectCandidates, createUpdateQueue, latestGitFromIndex, parseGitSpec, UPDATE_STEP_STAGE } from './updates.js'
|
|
29
30
|
|
|
30
31
|
/** 包名(Client 模块 id 必须与它一致)。 */
|
|
31
32
|
export const name = 'dsh-pluginmarket-plus'
|
|
@@ -63,6 +64,12 @@ export const Config = z.object({
|
|
|
63
64
|
retries: z.natural().min(0).max(5).default(2),
|
|
64
65
|
/** 缓存目录,相对 profile 目录。 */
|
|
65
66
|
cacheDir: z.string().default('.pluginmarket-plus'),
|
|
67
|
+
/** 「可更新」列表是否包含已禁用的插件(默认关)。 */
|
|
68
|
+
updatesIncludeDisabled: z.boolean().default(false).volatile(),
|
|
69
|
+
/** 「可更新」列表是否包含预发布 / 已废弃版本(默认关)。 */
|
|
70
|
+
updatesIncludePrerelease: z.boolean().default(false).volatile(),
|
|
71
|
+
/** 「可更新」列表是否显示「检查失败」的项(默认关)。 */
|
|
72
|
+
updatesShowFailed: z.boolean().default(false).volatile(),
|
|
66
73
|
})
|
|
67
74
|
|
|
68
75
|
/**
|
|
@@ -78,6 +85,32 @@ function live(value, fallback) {
|
|
|
78
85
|
return value ?? fallback
|
|
79
86
|
}
|
|
80
87
|
|
|
88
|
+
/**
|
|
89
|
+
* 读取正在运行的 DSH 版本,供版本豁免使用(豁免是「精确 包@版本 × DSH 版本」的)。
|
|
90
|
+
*
|
|
91
|
+
* 优先用官方 `getDshRuntimeVersion()`;它不在本插件的解析范围内时退回读 DSH 安装的
|
|
92
|
+
* `package.json`。两条路都走不通时返回 undefined,由调用方要求请求体带上 `runtimeVersion`。
|
|
93
|
+
* @returns {Promise<string|undefined>} DSH 版本,或 undefined。
|
|
94
|
+
*/
|
|
95
|
+
async function detectRuntimeVersion() {
|
|
96
|
+
try {
|
|
97
|
+
const boot = await import('@deepseek-ai/dsh-app-boot')
|
|
98
|
+
const version = boot?.getDshRuntimeVersion?.()
|
|
99
|
+
if (typeof version === 'string' && version.trim() !== '') return version.trim()
|
|
100
|
+
} catch {
|
|
101
|
+
// 本插件不在 DSH 安装的解析范围内:继续用下面的兜底。
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
const { createRequire } = await import('node:module')
|
|
105
|
+
const require = createRequire(import.meta.url)
|
|
106
|
+
const version = require('@deepseek-ai/dsh/package.json')?.version
|
|
107
|
+
if (typeof version === 'string' && version.trim() !== '') return version.trim()
|
|
108
|
+
} catch {
|
|
109
|
+
// DSH 安装不在解析范围内。
|
|
110
|
+
}
|
|
111
|
+
return undefined
|
|
112
|
+
}
|
|
113
|
+
|
|
81
114
|
/**
|
|
82
115
|
* 归一化源列表:只保留 http(s) 绝对地址、去重、保持顺序。
|
|
83
116
|
* @param {unknown} list - 原始列表。
|
|
@@ -171,7 +204,7 @@ function jsonResponse(payload, status = 200) {
|
|
|
171
204
|
*/
|
|
172
205
|
export function apply(ctx, config) {
|
|
173
206
|
const profileDir = ctx.get('profileContext')?.dir ?? process.env.DSH_PROFILE_DIR ?? process.cwd()
|
|
174
|
-
const cacheDir = resolve(profileDir, String(config.cacheDir
|
|
207
|
+
const cacheDir = resolve(profileDir, String(live(config.cacheDir, '.pluginmarket-plus')))
|
|
175
208
|
const store = new CacheStore(cacheDir)
|
|
176
209
|
|
|
177
210
|
/** @type {import('@deepseek-ai/cordis').Context|undefined} */
|
|
@@ -191,6 +224,33 @@ export function apply(ctx, config) {
|
|
|
191
224
|
/** 本插件最近一次写进「发现」页的完整列表,用来识别“这是我自己写的”事件。 */
|
|
192
225
|
let lastWrittenIndexes = []
|
|
193
226
|
|
|
227
|
+
/** @type {any} `pluginManager` 服务;执行更新与版本豁免都靠它。 */
|
|
228
|
+
let pluginManager
|
|
229
|
+
/** @type {Map<string, Record<string, unknown>>} 上一次 `POST /updates/check` 的结果,按包名索引(内存缓存,不落盘)。 */
|
|
230
|
+
const checkCache = new Map()
|
|
231
|
+
/** @type {Map<string, {chunks: string[], bytes: number, exits: (number|null)[]}>} 每个 requestId 的 pnpm 日志尾部。 */
|
|
232
|
+
const logTails = new Map()
|
|
233
|
+
/** 每个 requestId 保留的最大日志字节数与行数。 */
|
|
234
|
+
const LOG_TAIL_BYTES = 16 * 1024
|
|
235
|
+
const LOG_TAIL_CHUNKS = 80
|
|
236
|
+
/** @type {ReturnType<typeof createUpdateQueue>|undefined} 正在跑或最近跑完的更新队列。 */
|
|
237
|
+
let updateQueue
|
|
238
|
+
/** 同步「正在准备队列」闩锁:startUpdates 里任何 await 之前就置位,避免并发 apply 钻空子。 */
|
|
239
|
+
let updatesStarting = false
|
|
240
|
+
/** @type {object|undefined} 最近一次更新队列的结果快照。 */
|
|
241
|
+
let lastUpdateRun
|
|
242
|
+
/** 最近一次检查的完成时间。 */
|
|
243
|
+
let checkedAt = null
|
|
244
|
+
/**
|
|
245
|
+
* 「可更新」三个开关的内存兜底值。
|
|
246
|
+
*
|
|
247
|
+
* 正常情况下它们写进插件的 volatile 配置(`settings.mutate`)后立即生效;profile 还没有本插件
|
|
248
|
+
* 的配置条目、或 Settings 不可用时写入会失败,此时至少让本次进程内的开关立刻可用,并在响应里
|
|
249
|
+
* 如实报告 `saved: false`。
|
|
250
|
+
* @type {Map<string, boolean>}
|
|
251
|
+
*/
|
|
252
|
+
const updatesOverrides = new Map()
|
|
253
|
+
|
|
194
254
|
const entryId = ctx.fiber?.entry?.options?.id
|
|
195
255
|
const logger = {
|
|
196
256
|
info: (/** @type {string} */ message, /** @type {unknown} */ detail) => ctx.logger?.info?.(`dsh-pluginmarket-plus: ${message}`, detail),
|
|
@@ -240,6 +300,303 @@ export function apply(ctx, config) {
|
|
|
240
300
|
}
|
|
241
301
|
}
|
|
242
302
|
|
|
303
|
+
// --- 「可更新」数据(方案 §3 / §4 / §6 / §7)--------------------------------
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* 读一个「可更新」开关的当前值。
|
|
307
|
+
*
|
|
308
|
+
* 正常路径写进插件的 volatile 配置后立即生效;`settings.mutate` 不可用时(profile 还没有本插件
|
|
309
|
+
* 的配置条目)写入会失败,此时用内存兜底值,至少让本次进程内的开关立刻可用。
|
|
310
|
+
* @param {'updatesIncludeDisabled'|'updatesIncludePrerelease'|'updatesShowFailed'} key - 开关名。
|
|
311
|
+
* @returns {boolean} 开关状态。
|
|
312
|
+
*/
|
|
313
|
+
function updatesSwitch(key) {
|
|
314
|
+
const override = updatesOverrides.get(key)
|
|
315
|
+
if (typeof override === 'boolean') return override
|
|
316
|
+
return live(config[key], false) === true
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* 本地索引查询表的单次请求缓存:同一请求里 `listBundles()` + 每个 Git 候选各查一次,
|
|
321
|
+
* 没必要重复解析几 MB 的 JSON。
|
|
322
|
+
* @returns {ReturnType<CacheStore['cachedIndex']>} 查询表。
|
|
323
|
+
*/
|
|
324
|
+
function indexLookup() {
|
|
325
|
+
try {
|
|
326
|
+
return store.cachedIndex()
|
|
327
|
+
} catch (error) {
|
|
328
|
+
logger.warn(`读取本地索引失败:${messageOf(error)}`)
|
|
329
|
+
return { signature: '', size: 0, names: new Map() }
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* 从本地索引里取某个包在指定仓库目录下的最新提交。
|
|
335
|
+
* @param {ReturnType<CacheStore['cachedIndex']>} lookup - 查询表。
|
|
336
|
+
* @param {string} name - 包名。
|
|
337
|
+
* @param {{host: string, repository: string, path: string}} origin - 已安装副本的仓库目录。
|
|
338
|
+
* @returns {{commit: string, version: string, publishTimestamp: number}|undefined} 最新提交;索引里没有时 undefined。
|
|
339
|
+
*/
|
|
340
|
+
function gitFromIndex(lookup, name, origin) {
|
|
341
|
+
return latestGitFromIndex(lookup.names.get(name) ?? [], origin)
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* 收集候选:`listBundles()` + 本地索引 + 上一次检查的结果。
|
|
346
|
+
* @returns {Promise<{candidates: object[], checkedAt: number|null, indexLevel: object}>} 候选与索引摘要。
|
|
347
|
+
*/
|
|
348
|
+
async function candidatesPayload() {
|
|
349
|
+
const manager = pluginManager
|
|
350
|
+
/** @type {Record<string, unknown>[]} */
|
|
351
|
+
let bundles = []
|
|
352
|
+
let bundlesError = null
|
|
353
|
+
if (manager === undefined) {
|
|
354
|
+
bundlesError = 'plugin-manager-unavailable'
|
|
355
|
+
} else {
|
|
356
|
+
try {
|
|
357
|
+
bundles = await manager.listBundles()
|
|
358
|
+
} catch (error) {
|
|
359
|
+
bundlesError = messageOf(error)
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
const lookup = indexLookup()
|
|
363
|
+
const includeDisabled = updatesSwitch('updatesIncludeDisabled')
|
|
364
|
+
const includePrerelease = updatesSwitch('updatesIncludePrerelease')
|
|
365
|
+
const candidates = collectCandidates({
|
|
366
|
+
bundles,
|
|
367
|
+
cached: Object.fromEntries(checkCache),
|
|
368
|
+
indexInfo: { hasIndex: lookup.size > 0 },
|
|
369
|
+
includeDisabled,
|
|
370
|
+
includePrerelease,
|
|
371
|
+
})
|
|
372
|
+
return {
|
|
373
|
+
candidates,
|
|
374
|
+
checkedAt,
|
|
375
|
+
indexLevel: { sources: store.cachedIds().length, packages: lookup.size, error: bundlesError },
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** 停止队列并把正在跑的那一项交给后端取消流程。 */
|
|
380
|
+
async function cancelUpdates() {
|
|
381
|
+
const queue = updateQueue
|
|
382
|
+
if (queue === undefined) return { ok: true, cancelled: 'not-running' }
|
|
383
|
+
const active = queue.activeIndex()
|
|
384
|
+
queue.stop()
|
|
385
|
+
if (active < 0) return { ok: true, cancelled: 'not-running' }
|
|
386
|
+
const snapshot = queue.snapshot()
|
|
387
|
+
const item = snapshot.items[active]
|
|
388
|
+
if (item === undefined || pluginManager === undefined || typeof pluginManager.cancelInstall !== 'function') {
|
|
389
|
+
return { ok: true, cancelled: 'not-running' }
|
|
390
|
+
}
|
|
391
|
+
try {
|
|
392
|
+
const outcome = await pluginManager.cancelInstall(item.requestId)
|
|
393
|
+
// cancelInstall 只保证「进程退出且文件已还原」;completed 的结果不会被保留,
|
|
394
|
+
// 所以紧随其后的 waitForInstall 兜底确认一次。
|
|
395
|
+
if (outcome?.status === 'cancelled' && typeof pluginManager.waitForInstall === 'function') {
|
|
396
|
+
try {
|
|
397
|
+
await pluginManager.waitForInstall(item.requestId)
|
|
398
|
+
} catch {
|
|
399
|
+
// 请求已经结束,这里不需要再做什么。
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
return { ok: true, cancelled: outcome?.status ?? 'unknown', name: item.name }
|
|
403
|
+
} catch (error) {
|
|
404
|
+
logger.warn(`取消更新失败:${messageOf(error)}`)
|
|
405
|
+
return { ok: false, cancelled: 'failed', message: messageOf(error) }
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* 给一个包授予版本豁免(需要用户显式接受风险)。
|
|
411
|
+
* @param {string} packageVersion - 精确的 `包@版本`。
|
|
412
|
+
* @param {string|undefined} runtimeVersion - 精确的 DSH 版本。
|
|
413
|
+
* @returns {Promise<object>} 结果。
|
|
414
|
+
*/
|
|
415
|
+
async function grantExemption(packageVersion, runtimeVersion) {
|
|
416
|
+
if (pluginManager === undefined || typeof pluginManager.setVersionExemption !== 'function') {
|
|
417
|
+
return { ok: false, error: 'plugin-manager-unavailable' }
|
|
418
|
+
}
|
|
419
|
+
const runtime = typeof runtimeVersion === 'string' && runtimeVersion.trim() !== ''
|
|
420
|
+
? runtimeVersion.trim()
|
|
421
|
+
: await detectRuntimeVersion()
|
|
422
|
+
if (runtime === undefined) return { ok: false, error: 'runtime-version-unknown' }
|
|
423
|
+
try {
|
|
424
|
+
const outcome = await pluginManager.setVersionExemption(packageVersion, runtime, true, true)
|
|
425
|
+
return { ok: true, runtimeVersion: runtime, result: outcome }
|
|
426
|
+
} catch (error) {
|
|
427
|
+
return { ok: false, error: 'exempt-failed', message: messageOf(error) }
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* 安排一次后台顺序更新;同一时刻只跑一个队列。
|
|
433
|
+
*
|
|
434
|
+
* 进入函数先同步占住闩锁(之后才允许 await),所以两个并发的 `POST /updates/apply`
|
|
435
|
+
* 一定有一个拿到 409 `update-running`,不会都成功入队。
|
|
436
|
+
* @param {object[]} items - 请求体里的项。
|
|
437
|
+
* @returns {Promise<object>} 结果。
|
|
438
|
+
*/
|
|
439
|
+
async function startUpdates(items) {
|
|
440
|
+
if (updatesStarting || (updateQueue !== undefined && updateQueue.isRunning())) {
|
|
441
|
+
return { ok: false, error: 'update-running' }
|
|
442
|
+
}
|
|
443
|
+
updatesStarting = true
|
|
444
|
+
try {
|
|
445
|
+
const lookup = indexLookup()
|
|
446
|
+
/** @type {object[]} */
|
|
447
|
+
const planned = []
|
|
448
|
+
for (const item of items) {
|
|
449
|
+
const name = typeof item.name === 'string' ? item.name : ''
|
|
450
|
+
if (name === '') return { ok: false, error: 'invalid-item', message: '缺少包名' }
|
|
451
|
+
const checked = checkCache.get(name)
|
|
452
|
+
const kind = item.kind === 'git' || (checked?.kind === 'git') ? 'git' : 'npm'
|
|
453
|
+
const current = typeof checked?.current === 'string' ? checked.current : typeof item.current === 'string' ? item.current : ''
|
|
454
|
+
let latest = typeof checked?.latest === 'string' ? checked.latest : ''
|
|
455
|
+
// registry 更新永远用 name@version:真实 pluginManager 的 checkRegistryUpdate 只要收到
|
|
456
|
+
// spec 就 invalid-spec 拒绝,所以 registry 项即使请求体带了 spec 也必须忽略。
|
|
457
|
+
let spec = kind === 'git' && typeof item.spec === 'string' && item.spec !== '' ? item.spec : undefined
|
|
458
|
+
let commit = kind === 'git' && typeof item.commit === 'string' ? item.commit : undefined
|
|
459
|
+
if (kind === 'git') {
|
|
460
|
+
// Git 包必须给出固定 40 位 commit 的 spec;没有就从本地索引补,补不出来就说清缺什么。
|
|
461
|
+
let origin
|
|
462
|
+
if (spec !== undefined) origin = parseGitSpec(spec)
|
|
463
|
+
if (origin === undefined) {
|
|
464
|
+
const candidate = (await candidatesPayload()).candidates.find(entry => entry.name === name)
|
|
465
|
+
origin = candidate?.origin
|
|
466
|
+
}
|
|
467
|
+
const found = origin === undefined ? undefined : gitFromIndex(lookup, name, origin)
|
|
468
|
+
const itemCommit = typeof item.commit === 'string' ? item.commit.toLowerCase() : ''
|
|
469
|
+
if (/^[0-9a-f]{40}$/u.test(itemCommit) && origin !== undefined) {
|
|
470
|
+
commit = itemCommit
|
|
471
|
+
latest = latest === '' ? itemCommit : latest
|
|
472
|
+
spec = buildGitSpec(origin, itemCommit)
|
|
473
|
+
} else if (found !== undefined && origin !== undefined) {
|
|
474
|
+
commit = found.commit
|
|
475
|
+
latest = found.version
|
|
476
|
+
spec = buildGitSpec(origin, found.commit)
|
|
477
|
+
}
|
|
478
|
+
if (typeof spec !== 'string' || spec === '') {
|
|
479
|
+
return { ok: false, error: 'not-checkable', message: `${name} 的 Git 提交不在本地索引里,先点「检查更新」` }
|
|
480
|
+
}
|
|
481
|
+
if (latest === '') latest = commit ?? ''
|
|
482
|
+
} else if (latest === '') {
|
|
483
|
+
return { ok: false, error: 'not-checked', message: `${name} 还没有检查到目标版本,先点「检查更新」` }
|
|
484
|
+
}
|
|
485
|
+
planned.push({
|
|
486
|
+
name,
|
|
487
|
+
version: latest,
|
|
488
|
+
kind,
|
|
489
|
+
current,
|
|
490
|
+
latest,
|
|
491
|
+
...kind === 'git' && spec !== undefined ? { spec } : {},
|
|
492
|
+
...commit === undefined ? {} : { commit },
|
|
493
|
+
})
|
|
494
|
+
}
|
|
495
|
+
if (planned.length === 0) return { ok: false, error: 'empty-items' }
|
|
496
|
+
const queue = createUpdateQueue({
|
|
497
|
+
items: planned,
|
|
498
|
+
onError: message => logger.warn(`更新失败:${message}`),
|
|
499
|
+
runItem: async (item) => {
|
|
500
|
+
if (pluginManager === undefined || typeof pluginManager.updateBundle !== 'function') {
|
|
501
|
+
throw new Error('plugin-manager-unavailable')
|
|
502
|
+
}
|
|
503
|
+
// 契约:updateBundle(name, version, {requestId, spec?});spec 只属于 Git 包。
|
|
504
|
+
const options = item.kind === 'git' && item.spec !== undefined
|
|
505
|
+
? { requestId: item.requestId, spec: item.spec }
|
|
506
|
+
: { requestId: item.requestId }
|
|
507
|
+
return pluginManager.updateBundle(item.name, item.version, options)
|
|
508
|
+
},
|
|
509
|
+
})
|
|
510
|
+
updateQueue = queue
|
|
511
|
+
lastUpdateRun = undefined
|
|
512
|
+
queue.start().then((run) => {
|
|
513
|
+
lastUpdateRun = {
|
|
514
|
+
...run,
|
|
515
|
+
finishedAt: Date.now(),
|
|
516
|
+
items: undefined,
|
|
517
|
+
}
|
|
518
|
+
void syncMarket().catch(() => {})
|
|
519
|
+
}).catch(error => logger.warn(`更新队列异常结束:${messageOf(error)}`))
|
|
520
|
+
return {
|
|
521
|
+
ok: true,
|
|
522
|
+
requestId: 'updates',
|
|
523
|
+
requestIds: queue.snapshot().items.map(item => item.requestId),
|
|
524
|
+
items: queue.snapshot().items,
|
|
525
|
+
}
|
|
526
|
+
} catch (error) {
|
|
527
|
+
logger.warn(`准备更新队列失败:${messageOf(error)}`)
|
|
528
|
+
return { ok: false, error: 'apply-failed', message: messageOf(error) }
|
|
529
|
+
} finally {
|
|
530
|
+
updatesStarting = false
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* 队列状态(含每项阶段与 pnpm 日志尾部)。
|
|
536
|
+
* @returns {object} 状态对象。
|
|
537
|
+
*/
|
|
538
|
+
function updatesStatePayload() {
|
|
539
|
+
const queue = updateQueue
|
|
540
|
+
if (queue === undefined) {
|
|
541
|
+
return {
|
|
542
|
+
ok: true,
|
|
543
|
+
running: updatesStarting,
|
|
544
|
+
starting: updatesStarting,
|
|
545
|
+
queue: null,
|
|
546
|
+
items: [],
|
|
547
|
+
logs: [],
|
|
548
|
+
lastRun: lastUpdateRun ?? null,
|
|
549
|
+
checkedAt,
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
const snapshot = queue.snapshot()
|
|
553
|
+
const activeIndex = queue.activeIndex()
|
|
554
|
+
const active = activeIndex >= 0 ? snapshot.items[activeIndex] : undefined
|
|
555
|
+
const logs = active === undefined ? [] : (logTails.get(active.requestId)?.chunks ?? [])
|
|
556
|
+
return {
|
|
557
|
+
ok: true,
|
|
558
|
+
running: snapshot.running || updatesStarting,
|
|
559
|
+
starting: updatesStarting,
|
|
560
|
+
stopped: snapshot.stopped,
|
|
561
|
+
finished: snapshot.finished,
|
|
562
|
+
summary: snapshot.summary,
|
|
563
|
+
active: active?.name ?? null,
|
|
564
|
+
activeRequestId: active?.requestId ?? null,
|
|
565
|
+
items: snapshot.items,
|
|
566
|
+
logs,
|
|
567
|
+
lastRun: lastUpdateRun ?? null,
|
|
568
|
+
checkedAt,
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* 记录 pnpm 日志尾部(按 requestId 保留最后若干行)。
|
|
574
|
+
* @param {{requestId?: unknown, text?: unknown, stream?: unknown, exitCode?: unknown}} chunk - `plugin-manager/install-log` 的载荷。
|
|
575
|
+
* @returns {void}
|
|
576
|
+
*/
|
|
577
|
+
function recordLog(chunk) {
|
|
578
|
+
const requestId = typeof chunk?.requestId === 'string' ? chunk.requestId : undefined
|
|
579
|
+
if (requestId === undefined) return
|
|
580
|
+
const entry = logTails.get(requestId) ?? { chunks: [], bytes: 0, exits: [] }
|
|
581
|
+
const text = typeof chunk.text === 'string' ? chunk.text : ''
|
|
582
|
+
const stream = chunk.stream === 'stderr' ? 'stderr' : 'stdout'
|
|
583
|
+
for (const line of text.split(/\r?\n/u)) {
|
|
584
|
+
if (line.trim() === '') continue
|
|
585
|
+
entry.chunks.push(stream === 'stderr' ? `! ${line}` : line)
|
|
586
|
+
entry.bytes += Buffer.byteLength(line) + 1
|
|
587
|
+
}
|
|
588
|
+
if (typeof chunk.exitCode === 'number' || chunk.exitCode === null) entry.exits.push(chunk.exitCode)
|
|
589
|
+
while (entry.chunks.length > LOG_TAIL_CHUNKS) {
|
|
590
|
+
entry.bytes -= Buffer.byteLength(entry.chunks[0]) + 1
|
|
591
|
+
entry.chunks.shift()
|
|
592
|
+
}
|
|
593
|
+
while (entry.bytes > LOG_TAIL_BYTES && entry.chunks.length > 1) {
|
|
594
|
+
entry.bytes -= Buffer.byteLength(entry.chunks[0]) + 1
|
|
595
|
+
entry.chunks.shift()
|
|
596
|
+
}
|
|
597
|
+
logTails.set(requestId, entry)
|
|
598
|
+
}
|
|
599
|
+
|
|
243
600
|
/**
|
|
244
601
|
* 当前每个源的展示状态。
|
|
245
602
|
* @returns {object[]} 状态数组。
|
|
@@ -307,6 +664,9 @@ export function apply(ctx, config) {
|
|
|
307
664
|
autoRefresh: live(config.autoRefresh, true) !== false,
|
|
308
665
|
refreshIntervalHours: Number(live(config.refreshIntervalHours, 4)),
|
|
309
666
|
managePluginMarket: live(config.managePluginMarket, true) !== false,
|
|
667
|
+
updatesIncludeDisabled: updatesSwitch('updatesIncludeDisabled'),
|
|
668
|
+
updatesIncludePrerelease: updatesSwitch('updatesIncludePrerelease'),
|
|
669
|
+
updatesShowFailed: updatesSwitch('updatesShowFailed'),
|
|
310
670
|
fetchTimeoutMs: Number(config.fetchTimeoutMs ?? 120000),
|
|
311
671
|
maxBytes: Number(config.maxBytes ?? 64 * 1024 * 1024),
|
|
312
672
|
retries: Number(config.retries ?? 2),
|
|
@@ -654,6 +1014,9 @@ export function apply(ctx, config) {
|
|
|
654
1014
|
patch.refreshIntervalHours = hours
|
|
655
1015
|
}
|
|
656
1016
|
if (typeof body.managePluginMarket === 'boolean') patch.managePluginMarket = body.managePluginMarket
|
|
1017
|
+
if (typeof body.updatesIncludeDisabled === 'boolean') patch.updatesIncludeDisabled = body.updatesIncludeDisabled
|
|
1018
|
+
if (typeof body.updatesIncludePrerelease === 'boolean') patch.updatesIncludePrerelease = body.updatesIncludePrerelease
|
|
1019
|
+
if (typeof body.updatesShowFailed === 'boolean') patch.updatesShowFailed = body.updatesShowFailed
|
|
657
1020
|
if (body.sources !== undefined) {
|
|
658
1021
|
const next = normalizeSources(body.sources)
|
|
659
1022
|
const previous = effectiveSources()
|
|
@@ -665,6 +1028,14 @@ export function apply(ctx, config) {
|
|
|
665
1028
|
patch.sources = next
|
|
666
1029
|
}
|
|
667
1030
|
const saved = await writeConfig(patch)
|
|
1031
|
+
// 写配置失败(profile 还没有本插件条目 / Settings 不可用)时,至少让这些开关在本次
|
|
1032
|
+
// 进程内立刻生效;响应里的 `saved: false` 会如实告诉界面没有落盘。
|
|
1033
|
+
for (const key of ['updatesIncludeDisabled', 'updatesIncludePrerelease', 'updatesShowFailed']) {
|
|
1034
|
+
if (typeof patch[key] !== 'boolean') continue
|
|
1035
|
+
const effective = live(config[key], undefined)
|
|
1036
|
+
if (saved && effective === patch[key]) updatesOverrides.delete(key)
|
|
1037
|
+
else updatesOverrides.set(key, patch[key])
|
|
1038
|
+
}
|
|
668
1039
|
if (added.length > 0) await refreshMany({ urls: added })
|
|
669
1040
|
if (patch.managePluginMarket === false) await restoreMarket()
|
|
670
1041
|
else if (patch.managePluginMarket === true || patch.sources !== undefined) await syncMarket(patch.sources !== undefined)
|
|
@@ -686,6 +1057,129 @@ export function apply(ctx, config) {
|
|
|
686
1057
|
return jsonResponse({ ok: false, error: 'market-failed', message: messageOf(error) }, 500)
|
|
687
1058
|
}
|
|
688
1059
|
})
|
|
1060
|
+
|
|
1061
|
+
// --- 「可更新」桥(owner-only;方案 §6)----------------------------------
|
|
1062
|
+
|
|
1063
|
+
// 候选列表:只读缓存,不联网。`state` 是 `available / skipped / current / uncheckable / unknown / error`。
|
|
1064
|
+
route(`${API_PREFIX}/updates`, ['GET'], async () => {
|
|
1065
|
+
try {
|
|
1066
|
+
const payload = await candidatesPayload()
|
|
1067
|
+
return jsonResponse({
|
|
1068
|
+
ok: true,
|
|
1069
|
+
candidates: payload.candidates,
|
|
1070
|
+
checkedAt: payload.checkedAt,
|
|
1071
|
+
index: payload.indexLevel,
|
|
1072
|
+
config: {
|
|
1073
|
+
includeDisabled: updatesSwitch('updatesIncludeDisabled'),
|
|
1074
|
+
includePrerelease: updatesSwitch('updatesIncludePrerelease'),
|
|
1075
|
+
showFailed: updatesSwitch('updatesShowFailed'),
|
|
1076
|
+
},
|
|
1077
|
+
running: updatesStarting || (updateQueue?.isRunning() ?? false),
|
|
1078
|
+
})
|
|
1079
|
+
} catch (error) {
|
|
1080
|
+
return jsonResponse({ ok: false, error: 'updates-failed', message: messageOf(error) }, 500)
|
|
1081
|
+
}
|
|
1082
|
+
})
|
|
1083
|
+
|
|
1084
|
+
// 权威检查:registry → listVersions();git → 本地索引里的最新 commit。
|
|
1085
|
+
route(`${API_PREFIX}/updates/check`, ['POST'], async (request) => {
|
|
1086
|
+
try {
|
|
1087
|
+
const body = await readJsonBody(request)
|
|
1088
|
+
const names = Array.isArray(body.names) ? body.names.filter(name => typeof name === 'string') : undefined
|
|
1089
|
+
const payload = await candidatesPayload()
|
|
1090
|
+
const includePrerelease = updatesSwitch('updatesIncludePrerelease')
|
|
1091
|
+
const lookup = indexLookup()
|
|
1092
|
+
if (lookup.size === 0) {
|
|
1093
|
+
// 索引缺失时 Git 包标记不可检查且不报错;registry 包照样能用 registry 查。
|
|
1094
|
+
logger.info('本地索引为空,Git 包本次标记为不可检查')
|
|
1095
|
+
}
|
|
1096
|
+
const result = await checkCandidates({
|
|
1097
|
+
candidates: payload.candidates,
|
|
1098
|
+
names,
|
|
1099
|
+
dependencies: {
|
|
1100
|
+
includePrerelease,
|
|
1101
|
+
listVersions: async (name) => {
|
|
1102
|
+
if (pluginManager === undefined || typeof pluginManager.listVersions !== 'function') {
|
|
1103
|
+
return { status: 'refused', problem: 'not-updatable', reason: 'plugin-manager-unavailable', attempts: [] }
|
|
1104
|
+
}
|
|
1105
|
+
return pluginManager.listVersions(name)
|
|
1106
|
+
},
|
|
1107
|
+
latestGit: (name, origin) => gitFromIndex(lookup, name, origin),
|
|
1108
|
+
},
|
|
1109
|
+
})
|
|
1110
|
+
for (const entry of result.checked) checkCache.set(entry.name, entry)
|
|
1111
|
+
checkedAt = Date.now()
|
|
1112
|
+
const refreshed = await candidatesPayload()
|
|
1113
|
+
return jsonResponse({
|
|
1114
|
+
ok: true,
|
|
1115
|
+
checked: result.checked,
|
|
1116
|
+
skipped: result.skipped,
|
|
1117
|
+
unknown: result.unknown,
|
|
1118
|
+
candidates: refreshed.candidates,
|
|
1119
|
+
checkedAt,
|
|
1120
|
+
})
|
|
1121
|
+
} catch (error) {
|
|
1122
|
+
return jsonResponse({ ok: false, error: 'check-failed', message: messageOf(error) }, 500)
|
|
1123
|
+
}
|
|
1124
|
+
})
|
|
1125
|
+
|
|
1126
|
+
// 入队顺序更新:立刻返回,后台逐个 updateBundle;进度看 /updates/state。
|
|
1127
|
+
route(`${API_PREFIX}/updates/apply`, ['POST'], async (request) => {
|
|
1128
|
+
try {
|
|
1129
|
+
const body = await readJsonBody(request)
|
|
1130
|
+
const raw = Array.isArray(body.items) ? body.items : []
|
|
1131
|
+
const items = raw.filter(item => item !== null && typeof item === 'object')
|
|
1132
|
+
if (items.length === 0) {
|
|
1133
|
+
return jsonResponse({ ok: false, error: 'no-items', message: '请求体 items 为空' }, 400)
|
|
1134
|
+
}
|
|
1135
|
+
const started = await startUpdates(items)
|
|
1136
|
+
if (started.ok !== true) {
|
|
1137
|
+
const status = started.error === 'update-running'
|
|
1138
|
+
? 409
|
|
1139
|
+
: started.error === 'plugin-manager-unavailable' ? 503 : started.error === 'apply-failed' ? 500 : 400
|
|
1140
|
+
return jsonResponse(started, status)
|
|
1141
|
+
}
|
|
1142
|
+
return jsonResponse({ ok: true, started: true, requestIds: started.requestIds, items: started.items })
|
|
1143
|
+
} catch (error) {
|
|
1144
|
+
return jsonResponse({ ok: false, error: 'apply-failed', message: messageOf(error) }, 500)
|
|
1145
|
+
}
|
|
1146
|
+
})
|
|
1147
|
+
|
|
1148
|
+
// 队列进度:每项阶段(来自 plugin-manager/update-state)与当前项的 pnpm 日志尾部。
|
|
1149
|
+
route(`${API_PREFIX}/updates/state`, ['GET'], async () => jsonResponse(updatesStatePayload()))
|
|
1150
|
+
|
|
1151
|
+
// 取消:停队列 + 取消当前项。
|
|
1152
|
+
route(`${API_PREFIX}/updates/cancel`, ['POST'], async () => {
|
|
1153
|
+
try {
|
|
1154
|
+
const result = await cancelUpdates()
|
|
1155
|
+
return jsonResponse({ ...result, state: updatesStatePayload() }, result.ok === true ? 200 : 500)
|
|
1156
|
+
} catch (error) {
|
|
1157
|
+
return jsonResponse({ ok: false, error: 'cancel-failed', message: messageOf(error) }, 500)
|
|
1158
|
+
}
|
|
1159
|
+
})
|
|
1160
|
+
|
|
1161
|
+
// 版本豁免:必须显式 acceptRisk === true。
|
|
1162
|
+
route(`${API_PREFIX}/updates/exempt`, ['POST'], async (request) => {
|
|
1163
|
+
try {
|
|
1164
|
+
const body = await readJsonBody(request)
|
|
1165
|
+
const packageName = typeof body.package === 'string' ? body.package.trim() : ''
|
|
1166
|
+
const version = typeof body.version === 'string' ? body.version.trim() : ''
|
|
1167
|
+
if (packageName === '' || version === '') {
|
|
1168
|
+
return jsonResponse({ ok: false, error: 'invalid-request', message: '需要 package 与 version' }, 400)
|
|
1169
|
+
}
|
|
1170
|
+
if (body.acceptRisk !== true) {
|
|
1171
|
+
return jsonResponse({ ok: false, error: 'risk-not-accepted', message: '授予版本豁免需要显式接受风险(acceptRisk: true)' }, 400)
|
|
1172
|
+
}
|
|
1173
|
+
const result = await grantExemption(`${packageName}@${version}`, typeof body.runtimeVersion === 'string' ? body.runtimeVersion : undefined)
|
|
1174
|
+
if (result.ok !== true) {
|
|
1175
|
+
const status = result.error === 'plugin-manager-unavailable' ? 503 : result.error === 'runtime-version-unknown' ? 409 : 500
|
|
1176
|
+
return jsonResponse(result, status)
|
|
1177
|
+
}
|
|
1178
|
+
return jsonResponse(result)
|
|
1179
|
+
} catch (error) {
|
|
1180
|
+
return jsonResponse({ ok: false, error: 'exempt-failed', message: messageOf(error) }, 500)
|
|
1181
|
+
}
|
|
1182
|
+
})
|
|
689
1183
|
})
|
|
690
1184
|
|
|
691
1185
|
// --- 发现页服务:接管已有索引源、首次补缓存、定时刷新 ----------------------
|
|
@@ -700,6 +1194,43 @@ export function apply(ctx, config) {
|
|
|
700
1194
|
})().catch(error => logger.warn(`接管「发现」页索引源失败:${messageOf(error)}`))
|
|
701
1195
|
})
|
|
702
1196
|
|
|
1197
|
+
// --- 更新执行引擎:复用 pluginManager,进度来自它的事件(方案 §1.1 / §6)----
|
|
1198
|
+
ctx.inject(['pluginManager'], (managerCtx) => {
|
|
1199
|
+
pluginManager = managerCtx.pluginManager
|
|
1200
|
+
/** @type {Array<() => void>} */
|
|
1201
|
+
const disposers = []
|
|
1202
|
+
|
|
1203
|
+
// 每项的阶段:plugin-manager/update-state 的 checking → removing → installing → restoring。
|
|
1204
|
+
disposers.push(managerCtx.on('plugin-manager/update-state', (/** @type {{requestId?: string, step?: string}} */ progress) => {
|
|
1205
|
+
const queue = updateQueue
|
|
1206
|
+
if (queue === undefined || progress === null || typeof progress !== 'object') return
|
|
1207
|
+
const stage = progress.step === undefined ? undefined : UPDATE_STEP_STAGE[progress.step]
|
|
1208
|
+
if (stage === undefined || typeof progress.requestId !== 'string') return
|
|
1209
|
+
const item = queue.snapshot().items.find(entry => entry.requestId === progress.requestId)
|
|
1210
|
+
if (item !== undefined) queue.setStage(item.name, stage)
|
|
1211
|
+
}))
|
|
1212
|
+
|
|
1213
|
+
// pnpm 日志尾部:按 requestId 保留最后若干行,供 /updates/state 展开。
|
|
1214
|
+
disposers.push(managerCtx.on('plugin-manager/install-log', (/** @type {object} */ chunk) => recordLog(chunk)))
|
|
1215
|
+
|
|
1216
|
+
// 一次操作结束后,还在跑的队列保留日志;跑完了就清掉,下一次从干净的一轮开始。
|
|
1217
|
+
disposers.push(managerCtx.on('plugin-manager/changed', () => {
|
|
1218
|
+
if (updateQueue?.isRunning() === true) return
|
|
1219
|
+
if (lastUpdateRun !== undefined) logTails.clear()
|
|
1220
|
+
}))
|
|
1221
|
+
|
|
1222
|
+
ctx.effect(() => () => {
|
|
1223
|
+
for (const dispose of disposers) {
|
|
1224
|
+
try {
|
|
1225
|
+
dispose()
|
|
1226
|
+
} catch {
|
|
1227
|
+
// 已经随 fiber 一起释放。
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
pluginManager = undefined
|
|
1231
|
+
}, 'dsh-pluginmarket-plus: update listeners')
|
|
1232
|
+
})
|
|
1233
|
+
|
|
703
1234
|
// 用户在「发现 → 索引源」里增删时,跟随同步(防抖,忽略本插件自己的写入)。
|
|
704
1235
|
ctx.on('plugin-market/changed', () => {
|
|
705
1236
|
if (marketChangeTimer !== undefined) clearTimeout(marketChangeTimer)
|