dsh-modpack-kit 0.2.4 → 0.3.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,557 @@
1
+ /**
2
+ * @file lib/plugin-manager.mjs
3
+ * @role 插件管理:列表(分组/启用态/可更新)、启用禁用(市场优先、配置层兜底)、重装(可保留本机配置)
4
+ * @sub 插件管理、启用禁用、更新、重装
5
+ * @exports isValidPluginName / isValidVersion / writeMarketDisabled / listManaged / setPluginEnabled / resolveReinstallVersion / dropPatchEntries / reinstallPlugin / revealPluginDir
6
+ * @reads profile 的 package.json 与 node_modules、.dsh-market/state.json、cordis.patch.yml、市场目录
7
+ * @writes 市场 state.json 的 disabled、cordis.patch.yml 的 disabled、profile 的 bundles
8
+ * @risk 这是唯一会改「别人的插件」的模块:按路径装的插件不能被换成市场版,停用不能把插件文件删掉,卸载后中途取消会留下半空状态
9
+ * @touch 改字段要同步 client.js 的 PluginManagerPanel 与 /plugins* 四条路由;改重装步骤要同步 JobDock 的步骤渲染
10
+ * @since 0.3.0
11
+ */
12
+
13
+ /**
14
+ * dsh-modpack —— 插件管理(列表 / 启用禁用 / 更新 / 重装)。
15
+ *
16
+ * 这一层是「和插件市场同一份数据、但不用非得装市场」:
17
+ * * 停用名单和分组都读市场自己的 `.dsh-market/state.json`,
18
+ * 市场在的时候两边看到的是同一个状态;
19
+ * * 市场不在时(纯净 DSH),停用退回配置层 `cordis.patch.yml` 的
20
+ * `disabled: true`,照样能关掉一个插件;
21
+ * * 更新只按市场目录(和插件市场同一个索引)给出「有没有新版」,
22
+ * 真装还是走官方 CLI / 宿主 pluginManager,跟市场装的完全一样。
23
+ *
24
+ * 这里不做热挂载:装/卸/开关都标记「重启后生效」。市场那套 hotMount
25
+ * 会改运行中的组合,我们没有宿主内部 API,硬碰只会让 DSH 起不来。
26
+ */
27
+ import fs from 'node:fs'
28
+ import path from 'node:path'
29
+ import { spawn } from 'node:child_process'
30
+ import {
31
+ listInstalled,
32
+ readProfilePackage,
33
+ readBundles,
34
+ ensureBundles,
35
+ setBundles,
36
+ readPatch,
37
+ writePatch,
38
+ patchPath,
39
+ runDshPlugin,
40
+ } from './profile.mjs'
41
+ import { readMarketGroups, marketStatePath, hasMarket } from './groups.mjs'
42
+ import { lookupPlugins } from './market-catalog.mjs'
43
+ import { appendLog } from './store.mjs'
44
+ import { compareVersions } from './semver.mjs'
45
+ import { parseYaml, upsertPatchItem } from './yamlish.mjs'
46
+
47
+ const NAME_RE = /^(?:@[A-Za-z0-9][A-Za-z0-9._-]*\/)?[A-Za-z0-9][A-Za-z0-9._-]*$/u
48
+ const VERSION_RE = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/u
49
+
50
+ /** 插件名只认 npm 包名,别让奇怪的名字进到命令行。 */
51
+ export function isValidPluginName(name) {
52
+ return typeof name === 'string' && NAME_RE.test(name) && name.length <= 214
53
+ }
54
+
55
+ /** 版本号只认完整 semver(`latest`、范围都不行,我们只装确定的版本)。 */
56
+ export function isValidVersion(version) {
57
+ return typeof version === 'string' && VERSION_RE.test(version)
58
+ }
59
+
60
+ /** 配置层里 id → 条目。文件坏了就当没有配置,不要让列表整页报错。 */
61
+ function patchEntries(profileDir) {
62
+ const text = readPatch(profileDir)
63
+ if (!text) return { text: '', items: [] }
64
+ try {
65
+ const parsed = parseYaml(text)
66
+ const items = Array.isArray(parsed) ? parsed.filter((item) => item && typeof item === 'object' && typeof item.id === 'string') : []
67
+ return { text, items }
68
+ } catch {
69
+ return { text, items: [] }
70
+ }
71
+ }
72
+
73
+ /**
74
+ * 把停用状态写回插件市场的 state.json(只动 `disabled` 一项,别的键原样留着)。
75
+ * @returns {{changed: boolean, present: boolean, reason: string}}
76
+ */
77
+ export function writeMarketDisabled(profileDir, name, enabled) {
78
+ const empty = { changed: false, present: false, reason: '没装插件市场' }
79
+ if (typeof profileDir !== 'string' || profileDir === '') return empty
80
+ const file = marketStatePath(profileDir)
81
+ let raw
82
+ try {
83
+ raw = JSON.parse(fs.readFileSync(file, 'utf8'))
84
+ } catch {
85
+ return empty
86
+ }
87
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return { changed: false, present: false, reason: '市场状态文件看不懂' }
88
+ const list = Array.isArray(raw.disabled) ? raw.disabled.filter((item) => typeof item === 'string') : []
89
+ const listed = list.includes(name)
90
+ // 要的就是「已启用且不在名单」「要停用且已在名单」这两种不变的情况
91
+ if (enabled === !listed) return { changed: false, present: true, reason: '' }
92
+ raw.disabled = enabled ? list.filter((item) => item !== name) : [...list, name]
93
+ // 和市场一样用「临时文件 + rename」:写一半断电也不会留下半个 JSON
94
+ const tmp = file + '.' + Date.now() + '.tmp'
95
+ fs.writeFileSync(tmp, JSON.stringify(raw, null, 2) + '\n', 'utf8')
96
+ fs.renameSync(tmp, file)
97
+ return { changed: true, present: true, reason: '' }
98
+ }
99
+
100
+ /**
101
+ * 统一的插件视图:安装信息 + 市场分组 + 停用状态 + 目录里的最新版。
102
+ *
103
+ * @param {string} profileDir
104
+ * @param {object} config 插件配置(要用到插件市场目录的缓存)
105
+ */
106
+ export function listManaged(profileDir, config) {
107
+ const installed = listInstalled(profileDir)
108
+ const market = readMarketGroups(profileDir)
109
+ const marketPresent = market.present || hasMarket(profileDir)
110
+ const bundles = readBundles(readProfilePackage(profileDir))
111
+ // 依赖写法决定「这个插件是从哪儿来的」:file:/link:/本地路径 = 按路径装的(开发中的插件),
112
+ // 这种不能拿市场版本去覆盖,否则重装一次就把本地开发版换成 npm 上那个了。
113
+ const deps = (() => {
114
+ try {
115
+ const pkg = readProfilePackage(profileDir) || {}
116
+ return { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) }
117
+ } catch { return {} }
118
+ })()
119
+ const localSpecOf = (name) => {
120
+ const spec = typeof deps[name] === 'string' ? deps[name].trim() : ''
121
+ return /^(?:file:|link:|\.{1,2}[\\/]|[A-Za-z]:[\\/])/u.test(spec) ? spec : ''
122
+ }
123
+ const patch = patchEntries(profileDir)
124
+ const marketplace = (() => {
125
+ const names = installed.map((item) => item.name).filter(Boolean)
126
+ if (names.length === 0) return {}
127
+ try {
128
+ return lookupPlugins(config, names) || {}
129
+ } catch {
130
+ return {}
131
+ }
132
+ })()
133
+
134
+ const groupOf = new Map()
135
+ for (const group of market.order) for (const member of market.groups[group] || []) if (!groupOf.has(member)) groupOf.set(member, group)
136
+ const disabledSet = new Set(market.disabled)
137
+
138
+ const items = installed.map((item) => {
139
+ const entry = patch.items.find((row) => row.id === item.name)
140
+ const patched = entry && entry.disabled === true
141
+ const marketOff = marketPresent && disabledSet.has(item.name)
142
+ const inBundles = bundles.includes(item.name)
143
+ const latest = marketplace[item.name] || null
144
+ const latestVersion = latest && typeof latest.version === 'string' ? latest.version : ''
145
+ const installSpec = localSpecOf(item.name)
146
+ // 按路径装的插件不参与「可更新」:市场那版不是它的来源,点了只会把本地版换掉
147
+ const hasUpdate = !installSpec && Boolean(latestVersion && item.version && compareVersions(latestVersion, item.version) > 0)
148
+ return {
149
+ name: item.name,
150
+ dirName: item.dirName,
151
+ version: item.version || '',
152
+ latestVersion,
153
+ hasUpdate,
154
+ installSpec,
155
+ // 两种来源任一说不启用就算停用:市场的名单是主,配置层是兜底
156
+ enabled: !marketOff && !patched,
157
+ isBundle: Boolean(item.isBundle),
158
+ inBundles,
159
+ isDirect: item.isDirect !== false,
160
+ transitiveOf: item.transitiveOf || '',
161
+ isOrphan: Boolean(item.isOrphan),
162
+ hasConfig: Boolean(entry),
163
+ configDisabled: Boolean(patched),
164
+ category: (latest && latest.category) || '',
165
+ title: (latest && latest.title) || '',
166
+ description: item.description || (latest && latest.description) || '',
167
+ repository: (latest && latest.repository) || '',
168
+ source: latest ? 'market' : 'local',
169
+ group: groupOf.get(item.name) || '',
170
+ dir: item.dir || '',
171
+ size: item.size || 0,
172
+ }
173
+ })
174
+
175
+ const counts = {
176
+ all: items.length,
177
+ enabled: items.filter((item) => item.enabled).length,
178
+ disabled: items.filter((item) => !item.enabled).length,
179
+ updatable: items.filter((item) => item.hasUpdate).length,
180
+ }
181
+ return {
182
+ items,
183
+ counts,
184
+ marketPresent,
185
+ groups: market.order.slice(),
186
+ ungrouped: items.filter((item) => !item.group).length,
187
+ configPath: patchPath(profileDir),
188
+ }
189
+ }
190
+
191
+ /**
192
+ * 启用 / 停用。装市场时改市场自己的停用名单(跟市场界面完全同步);
193
+ * 没装市场时改配置层的 `disabled`。两者都只在下一次启动生效。
194
+ */
195
+ export function setPluginEnabled(profileDir, name, enabled) {
196
+ if (!isValidPluginName(name)) throw new Error('插件名不合法')
197
+ const installed = listInstalled(profileDir)
198
+ const item = installed.find((row) => row.name === name)
199
+ if (!item) throw new Error('本机没有这个插件:' + name)
200
+ if (item.isDirect === false) {
201
+ throw new Error(name + ' 是' + (item.transitiveOf ? ' ' + item.transitiveOf + ' ' : '别的插件') + '的子包,跟着父插件走,不能单独开关')
202
+ }
203
+ const marketPresent = hasMarket(profileDir)
204
+ const notes = []
205
+ if (marketPresent) {
206
+ const result = writeMarketDisabled(profileDir, name, enabled)
207
+ if (!result.present) notes.push('市场状态文件读不到,改用配置层')
208
+ else if (result.changed) notes.push(enabled ? '已从插件市场的停用名单移除' : '已加进插件市场的停用名单')
209
+ else notes.push('插件市场里本来就是' + (enabled ? '启用' : '停用') + '状态')
210
+ }
211
+ if (!marketPresent || notes[0] === '市场状态文件读不到,改用配置层') {
212
+ const text = readPatch(profileDir)
213
+ const entry = patchEntries(profileDir).items.find((row) => row.id === name)
214
+ if (!entry && !enabled) {
215
+ throw new Error('没有插件市场时,只有在配置层出现过(改过设置)的插件才能单独关;' + name + ' 没有配置条目')
216
+ }
217
+ const next = upsertPatchItem(text, {
218
+ id: name,
219
+ name: entry && entry.name ? entry.name : name,
220
+ config: entry && entry.config && typeof entry.config === 'object' ? entry.config : {},
221
+ disabled: !enabled,
222
+ })
223
+ writePatch(profileDir, next.text)
224
+ notes.push('已写入 cordis.patch.yml 的 disabled')
225
+ }
226
+ // 关键:停用的插件也从 bundles 里撤掉,否则启动时它照样被加载(配置层 disabled 才管用)
227
+ const bundles = readBundles(readProfilePackage(profileDir))
228
+ if (!enabled && bundles.includes(name)) {
229
+ setBundles(profileDir, bundles.filter((row) => row !== name))
230
+ notes.push('已从 bundles 撤下')
231
+ } else if (enabled && !bundles.includes(name) && item.isBundle) {
232
+ const added = ensureBundles(profileDir, [name])
233
+ if (added.changed) notes.push('已重新登记到 bundles')
234
+ }
235
+ appendLog('plugins toggle ' + name + ' enabled=' + enabled + ' :: ' + notes.join(' / '))
236
+ return { ok: true, name, enabled, notes, restartRequired: true, scope: marketPresent ? 'market' : 'patch' }
237
+ }
238
+
239
+ /**
240
+ * 重装用的目标版本:优先调用方给的,其次市场目录里的最新版,最后是当前版本。
241
+ * 返回值可能为空(本机版本都读不到),调用方要判。
242
+ */
243
+ export function resolveReinstallVersion(item) {
244
+ if (!item) return ''
245
+ if (isValidVersion(item.latestVersion)) return item.latestVersion
246
+ if (isValidVersion(item.version)) return item.version
247
+ return ''
248
+ }
249
+
250
+ /**
251
+ * 从配置层删掉某个插件的条目(「重装不保留本机配置」用)。
252
+ * 只删 id 命中的条目,其他行逐字节保留。
253
+ *
254
+ * @returns {{removed: number, backup: string}}
255
+ */
256
+ export function dropPatchEntries(profileDir, name) {
257
+ const text = readPatch(profileDir)
258
+ if (!text || !text.trim()) return { removed: 0, backup: '' }
259
+ const lines = text.split(/\r?\n/u)
260
+ // 跟 upsertPatchItem 一样按顶层 `- id:` 切块,删掉整块(含它下面的缩进行)
261
+ const starts = []
262
+ for (let i = 0; i < lines.length; i += 1) {
263
+ if (/^-(?:\s|$)/u.test(lines[i])) starts.push(i)
264
+ }
265
+ if (starts.length === 0) return { removed: 0, backup: '' }
266
+ const ranges = starts.map((start, index) => ({ start, end: index + 1 < starts.length ? starts[index + 1] : lines.length }))
267
+ const keep = []
268
+ let removed = 0
269
+ let cursor = 0
270
+ for (const range of ranges) {
271
+ const block = lines.slice(range.start, range.end).join('\n')
272
+ const idMatch = /^-\s+id:\s*(.+)$/mu.exec(block)
273
+ const id = idMatch ? idMatch[1].trim().replace(/^['"]|['"]$/gu, '') : ''
274
+ if (id === name) {
275
+ keep.push(...lines.slice(cursor, range.start))
276
+ cursor = range.end
277
+ removed += 1
278
+ }
279
+ }
280
+ if (removed === 0) return { removed: 0, backup: '' }
281
+ keep.push(...lines.slice(cursor))
282
+ // 全删空就留一个合法的空清单,别让 loader 读到一份空文件
283
+ const body = keep.join('\n')
284
+ const trimmed = body.replace(/\s+$/u, '')
285
+ const next = trimmed === '' || /^(?:#.*\n?)*$/u.test(trimmed) ? '[]\n' : trimmed + '\n'
286
+ const backup = writePatch(profileDir, next)
287
+ appendLog('plugins config drop ' + name + ' removed=' + removed)
288
+ return { removed, backup }
289
+ }
290
+
291
+ function cliTail(output, limit = 400) {
292
+ const text = String(output || '').trim()
293
+ if (!text) return ''
294
+ const lines = text.split(/\r?\n/u).filter((line) => line.trim() !== '')
295
+ return lines.slice(-3).join(' / ').slice(-limit)
296
+ }
297
+
298
+ /**
299
+ * 重装一个插件:卸 → 装 → 恢复原来的启用状态。
300
+ *
301
+ * 卸载已经成功、安装失败时,自动退回原版本再装一次——宁可「还是老版本」,
302
+ * 也不要留下一个被卸掉、却装不回来的插件。
303
+ *
304
+ * @param {object} params
305
+ * @param {string} params.profileDir
306
+ * @param {string} params.profile profile 名(CLI 参数)
307
+ * @param {string} params.name 插件名
308
+ * @param {string} [params.version] 目标版本
309
+ * @param {boolean} [params.keepConfig] 保留本机配置
310
+ * @param {(info: {pct: number, note: string, step?: string}) => void} [params.onProgress]
311
+ * @param {() => boolean} [params.isCancelled]
312
+ */
313
+ export async function reinstallPlugin(params) {
314
+ const { profileDir, profile, name } = params
315
+ const keepConfig = params.keepConfig !== false
316
+ const onProgress = typeof params.onProgress === 'function' ? params.onProgress : () => {}
317
+ const isCancelled = typeof params.isCancelled === 'function' ? params.isCancelled : () => false
318
+ if (!isValidPluginName(name)) throw new Error('插件名不合法')
319
+ const installed = listInstalled(profileDir)
320
+ const item = installed.find((row) => row.name === name)
321
+ if (!item) throw new Error('本机没有这个插件:' + name)
322
+ if (item.isDirect === false) throw new Error(name + ' 是别的插件的子包,重装要把父插件一起重装')
323
+
324
+ const before = listManaged(profileDir, params.config || {}).items.find((row) => row.name === name) || null
325
+ // 按路径装(file:/link:/本地目录)的插件:重装就重读那份目录,不换成市场版
326
+ const localSpec = (before && before.installSpec) || ''
327
+ const version = localSpec ? '' : isValidVersion(params.version) ? params.version : resolveReinstallVersion(before)
328
+ const fromVersion = item.version || ''
329
+ const wasEnabled = before ? before.enabled : true
330
+ const wasInBundles = readBundles(readProfilePackage(profileDir)).includes(name)
331
+ const actions = []
332
+
333
+ onProgress({ pct: 6, note: '读取当前状态:' + name + (fromVersion ? '@' + fromVersion : ''), step: 'read' })
334
+ if (isCancelled()) throw new Error('已取消')
335
+
336
+ if (!keepConfig) {
337
+ const dropped = dropPatchEntries(profileDir, name)
338
+ actions.push({ action: 'drop-config', ok: true, message: dropped.removed > 0 ? '删掉 ' + dropped.removed + ' 条本机配置' : '没有需要删的配置条目' })
339
+ onProgress({ pct: 14, note: dropped.removed > 0 ? '已清掉本机配置(' + dropped.removed + ' 条)' : '没有本机配置要清', step: 'config' })
340
+ } else {
341
+ actions.push({ action: 'keep-config', ok: true, message: '保留本机配置' })
342
+ onProgress({ pct: 14, note: '保留本机配置', step: 'config' })
343
+ }
344
+ if (isCancelled()) throw new Error('已取消')
345
+
346
+ onProgress({ pct: 22, note: '卸载 ' + name + '…', step: 'remove' })
347
+ const removed = await runDshPlugin(profile, ['remove', name], {
348
+ timeoutMs: 300000,
349
+ onLine: (line) => { if (line.trim()) onProgress({ pct: 22, note: '卸载:' + line.trim().slice(0, 120), step: 'remove' }) },
350
+ })
351
+ actions.push({ action: 'remove', ok: removed.code === 0, message: removed.code === 0 ? '已卸载' : cliTail(removed.output) || '卸载失败' })
352
+ if (removed.code !== 0) {
353
+ throw new Error('卸载失败,没有继续安装(插件还在原处):' + (cliTail(removed.output) || 'CLI 退出码 ' + removed.code))
354
+ }
355
+ // 卸载已经发生:从这里开始不再理会「取消」,否则会把插件留在「卸了没装」的半空状态
356
+
357
+ const spec = localSpec || (version ? name + '@' + version : name)
358
+ onProgress({ pct: 40, note: '安装 ' + spec + '…', step: 'install' })
359
+ let added = await runDshPlugin(profile, ['add', spec], {
360
+ timeoutMs: 600000,
361
+ onLine: (line) => { if (line.trim()) onProgress({ pct: 48, note: '安装:' + line.trim().slice(0, 120), step: 'install' }) },
362
+ })
363
+ let installedSpec = spec
364
+ if (added.code !== 0 && version && isValidVersion(fromVersion)) {
365
+ // 崩在半路:先想办法把原来的版本装回去,别把插件的坑留给人手补
366
+ onProgress({ pct: 55, note: '新版本没装成,退回 ' + name + '@' + fromVersion + '…', step: 'rollback' })
367
+ const retrySpec = localSpec || name + '@' + fromVersion
368
+ const retry = await runDshPlugin(profile, ['add', retrySpec], { timeoutMs: 600000 })
369
+ actions.push({ action: 'rollback', ok: retry.code === 0, message: retry.code === 0 ? '已退回 ' + fromVersion : cliTail(retry.output) || '退回失败' })
370
+ if (retry.code === 0) {
371
+ added = retry
372
+ installedSpec = retrySpec
373
+ }
374
+ }
375
+ actions.push({ action: 'add', ok: added.code === 0, message: added.code === 0 ? '已安装 ' + installedSpec : cliTail(added.output) || '安装失败' })
376
+ if (added.code !== 0) {
377
+ throw new Error('安装失败(' + installedSpec + '):' + (cliTail(added.output) || 'CLI 退出码 ' + added.code))
378
+ }
379
+
380
+ onProgress({ pct: 80, note: '恢复启用状态…', step: 'restore' })
381
+ if (wasEnabled === false) {
382
+ try {
383
+ setPluginEnabled(profileDir, name, false)
384
+ actions.push({ action: 'disable', ok: true, message: '保持停用' })
385
+ } catch (error) {
386
+ actions.push({ action: 'disable', ok: false, message: String((error && error.message) || error) })
387
+ }
388
+ } else {
389
+ if (!wasInBundles) {
390
+ // 原来没登记 bundles 的(市场装的常是这种),装完会自己出现在依赖里,这里只保证启用名单干净
391
+ ensureBundles(profileDir, [name])
392
+ }
393
+ const after = listManaged(profileDir, params.config || {}).items.find((row) => row.name === name) || null
394
+ if (after && !after.enabled) {
395
+ try {
396
+ setPluginEnabled(profileDir, name, true)
397
+ actions.push({ action: 'enable', ok: true, message: '已启用' })
398
+ } catch (error) {
399
+ actions.push({ action: 'enable', ok: false, message: String((error && error.message) || error) })
400
+ }
401
+ } else {
402
+ actions.push({ action: 'enable', ok: true, message: '保持启用' })
403
+ }
404
+ }
405
+
406
+ const afterVersion = (() => {
407
+ const row = listInstalled(profileDir).find((it) => it.name === name)
408
+ return row ? row.version || '' : ''
409
+ })()
410
+ onProgress({ pct: 96, note: '完成:' + name + (afterVersion ? '@' + afterVersion : ''), step: 'done' })
411
+ appendLog('plugins reinstall ' + name + ' ' + fromVersion + ' -> ' + (afterVersion || '?') + ' keepConfig=' + keepConfig)
412
+ return {
413
+ ok: true,
414
+ name,
415
+ fromVersion,
416
+ toVersion: afterVersion,
417
+ requestedVersion: version,
418
+ keepConfig,
419
+ actions,
420
+ restartRequired: true,
421
+ }
422
+ }
423
+
424
+ /** 在资源管理器里定位插件目录(给列表行「打开目录」用)。 */
425
+ export function revealPluginDir(profileDir, name) {
426
+ if (!isValidPluginName(name)) throw new Error('插件名不合法')
427
+ const item = listInstalled(profileDir).find((row) => row.name === name)
428
+ if (!item || !item.dir) throw new Error('找不到这个插件的目录')
429
+ const dir = item.dir
430
+ if (!fs.existsSync(dir)) throw new Error('目录不存在:' + dir)
431
+ if (process.platform === 'win32') spawn('explorer.exe', ['/select,' + path.normalize(dir)], { detached: true, stdio: 'ignore' }).unref()
432
+ else if (process.platform === 'darwin') spawn('open', [dir], { detached: true, stdio: 'ignore' }).unref()
433
+ else spawn('xdg-open', [path.dirname(dir)], { detached: true, stdio: 'ignore' }).unref()
434
+ return { dir }
435
+ }
436
+
437
+ // —— 行首图标:优先用插件包里自带的图(市场装的也是 npm 包,图就在包里)——
438
+ // 只在已装插件的目录里找,不联网、不解析 SVG;超过 512KB 的不读(图标不该那么大)。
439
+ const ICON_FILES = [
440
+ 'assets/icon.png',
441
+ 'assets/icon.svg',
442
+ 'assets/icon-512.png',
443
+ 'assets/icon-180.png',
444
+ 'icon.png',
445
+ 'icon.svg',
446
+ 'logo.png',
447
+ 'logo.svg',
448
+ 'assets/logo.png',
449
+ 'assets/logo.svg',
450
+ ]
451
+ const ICON_MAX = 512 * 1024
452
+ const ICON_MIME = {
453
+ '.png': 'image/png',
454
+ '.jpg': 'image/jpeg',
455
+ '.jpeg': 'image/jpeg',
456
+ '.webp': 'image/webp',
457
+ '.gif': 'image/gif',
458
+ '.svg': 'image/svg+xml',
459
+ }
460
+ const iconMemo = new Map()
461
+
462
+ /** 找一个插件的图标:返回 { name, mime, base64, file },找不到就 throw。 */
463
+ export function pluginIcon(profileDir, name) {
464
+ if (!isValidPluginName(name)) throw new Error('插件名不合法')
465
+ const item = listInstalled(profileDir).find((row) => row.name === name)
466
+ if (!item || !item.dir) throw new Error('本机没有这个插件:' + name)
467
+ // dir 是软链/硬链拷进来的副本,realDir 才是真目录;两个都试
468
+ const roots = [item.realDir, item.dir].filter(Boolean)
469
+ for (const root of roots) {
470
+ for (const rel of ICON_FILES) {
471
+ const file = path.join(root, rel)
472
+ let stat
473
+ try { stat = fs.statSync(file) } catch { continue }
474
+ if (!stat.isFile() || stat.size > ICON_MAX) continue
475
+ const key = file + ':' + stat.mtimeMs + ':' + stat.size
476
+ let cached = iconMemo.get(key)
477
+ if (!cached) {
478
+ cached = { base64: fs.readFileSync(file).toString('base64'), mime: ICON_MIME[path.extname(file).toLowerCase()] || 'application/octet-stream' }
479
+ iconMemo.set(key, cached)
480
+ for (const [oldKey] of iconMemo) if (iconMemo.size > 200 && oldKey !== key) iconMemo.delete(oldKey)
481
+ }
482
+ return { name, mime: cached.mime, base64: cached.base64, file: path.relative(root, file) || rel, size: stat.size }
483
+ }
484
+ }
485
+ throw new Error('这个插件的包里没有图标文件(找过 icon.png / icon.svg / assets/icon-*.png)')
486
+ }
487
+
488
+ /** 一键更新要动哪些:可更新、没按路径装、而且当前是启用状态(停用的插件不跟着批量动)。 */
489
+ export function updatableItems(items) {
490
+ const list = Array.isArray(items) ? items : []
491
+ return list.filter((item) => item && item.hasUpdate && !item.installSpec && item.enabled !== false)
492
+ }
493
+
494
+ /**
495
+ * 一键更新:一个个 add name@version,失败的那条记下来、继续下一个。
496
+ * 不删不卸、不动配置,也不碰停用的插件——批量操作越老实越好。
497
+ */
498
+ export async function updatePlugins(params) {
499
+ const { profileDir, profile } = params
500
+ const onProgress = typeof params.onProgress === 'function' ? params.onProgress : () => {}
501
+ const isCancelled = typeof params.isCancelled === 'function' ? params.isCancelled : () => false
502
+ const targets = Array.isArray(params.targets) ? params.targets : []
503
+ if (!targets.length) throw new Error('没有可更新的插件')
504
+ const results = []
505
+ const total = targets.length
506
+ for (let index = 0; index < total; index += 1) {
507
+ const target = targets[index]
508
+ const name = String(target.name || '')
509
+ const to = String(target.latest || '')
510
+ if (!isValidPluginName(name)) {
511
+ results.push({ name, ok: false, error: '插件名不合法' })
512
+ continue
513
+ }
514
+ if (isCancelled()) {
515
+ results.push({ name, ok: false, error: '已取消' })
516
+ continue
517
+ }
518
+ const pct = Math.round(((index + 0.15) / total) * 100)
519
+ onProgress({ pct, note: '更新 ' + name + (to ? ' → ' + to : '') + '(' + (index + 1) + '/' + total + ')', step: name })
520
+ const spec = to ? name + '@' + to : name
521
+ try {
522
+ const saved = (() => {
523
+ const row = listManaged(profileDir, params.config || {}).items.find((item) => item.name === name)
524
+ return { enabled: row ? row.enabled : true, inBundles: readBundles(readProfilePackage(profileDir)).includes(name) }
525
+ })()
526
+ const added = await runDshPlugin(profile, ['add', spec], {
527
+ timeoutMs: 600000,
528
+ onLine: (line) => { if (line.trim()) onProgress({ pct, note: '更新 ' + name + ':' + line.trim().slice(0, 110), step: name }) },
529
+ })
530
+ if (added.code !== 0) {
531
+ results.push({ name, ok: false, to, error: cliTail(added.output) || 'CLI 退出码 ' + added.code })
532
+ continue
533
+ }
534
+ // 更新后把启用态摆回原样(插件市场那份名单有时会因为重装被写掉)
535
+ if (saved.enabled === false) {
536
+ try { setPluginEnabled(profileDir, name, false) } catch {}
537
+ } else if (!saved.inBundles) {
538
+ try { ensureBundles(profileDir, [name]) } catch {}
539
+ }
540
+ const after = listInstalled(profileDir).find((item) => item.name === name)
541
+ results.push({ name, ok: true, to: after ? after.version || to : to })
542
+ } catch (error) {
543
+ results.push({ name, ok: false, to, error: String((error && error.message) || error) })
544
+ }
545
+ }
546
+ const failed = results.filter((row) => !row.ok)
547
+ onProgress({ pct: 100, note: failed.length ? '更新完成,' + failed.length + ' 个没成功' : '全部更新完成(' + (total - failed.length) + ' 个)', step: 'done' })
548
+ appendLog('plugins update ' + results.map((row) => row.name + (row.ok ? '=' + row.to : '!')).join(' '))
549
+ return {
550
+ ok: failed.length === 0,
551
+ total,
552
+ updated: results.filter((row) => row.ok).length,
553
+ failed: failed.length,
554
+ results,
555
+ restartRequired: true,
556
+ }
557
+ }
package/lib/profile.mjs CHANGED
@@ -1,3 +1,15 @@
1
+ /**
2
+ * @file lib/profile.mjs
3
+ * @role profile 读写:插件列表(含子包/残包判定)、bundles、cordis.patch.yml、跑官方 dsh CLI
4
+ * @sub profile、插件列表、bundles、CLI
5
+ * @exports readJson / readProfilePackage / listInstalled / dshVersion / readBundles / ensureBundles / setBundles / patchPath / readPatch / writePatch / runDshPlugin
6
+ * @reads .dsh/profiles/<名字> 下的 package.json、node_modules、cordis.patch.yml
7
+ * @writes bundles 与 patch 文件(都带 .bak 备份 + 原子写)
8
+ * @risk file: 依赖在 profile 里是硬链接拷贝,直接覆盖写会同时改到源码副本;所以更新一律先 unlink 再写
9
+ * @touch 改判定要同步 lib/install.mjs 的跳过子包逻辑与 client.js 的「子包 · 跟随 X」显示
10
+ * @since 0.3.0
11
+ */
12
+
1
13
  /**
2
14
  * dsh-modpack —— 只读 + 受控写入 DSH profile。
3
15
  *
package/lib/registry.mjs CHANGED
@@ -1,3 +1,15 @@
1
+ /**
2
+ * @file lib/registry.mjs
3
+ * @role npm registry:探测可达性、取包元数据、挑版本、下载 tarball、抓市场目录包
4
+ * @sub npm、版本选择、下载
5
+ * @exports assertAllowedUrl / fetchLimited / fetchJson / validatePackageName / metadataLimit / probeRegistry / npmMetadata / pickVersion / relativeTime / downloadPackage / fetchCatalog / npmSearchCatalog
6
+ * @reads registry.npmjs.org、npm 包 tarball
7
+ * @writes 不落盘(下载结果交给上层)
8
+ * @risk 元数据可能巨大(16 MB 上限曾把市场大包直接打死),必须分层退让;范围写法要支持 ^ ~ 与精确版本
9
+ * @touch 改上限要同步 store.mjs 的 maxMetadataBytes 与 test 的边界用例
10
+ * @since 0.3.0
11
+ */
12
+
1
13
  /**
2
14
  * dsh-modpack —— 从 npm / 插件市场源取包。
3
15
  *
package/lib/repack.mjs CHANGED
@@ -1,3 +1,14 @@
1
+ /**
2
+ * @file lib/repack.mjs
3
+ * @role 轻量重打包:只改清单里的几个字段(简介、分类、封面…),其余字节原样保留
4
+ * @sub 社区资源上传、改词条
5
+ * @exports rewritePackManifest
6
+ * @reads 原 .dshpack 的字节
7
+ * @risk 这是「改过的包还能不能被装」的关键:zip 里其它条目的压缩方式与顺序不能乱动
8
+ * @touch 改字段要同步 lib/manifest.mjs 的 schema 与上传面板的输入项
9
+ * @since 0.3.0
10
+ */
11
+
1
12
  import { readZip, readZipText, writeZip } from './zip.mjs'
2
13
  import { MANIFEST_NAME, buildReadme, sha256 } from './manifest.mjs'
3
14
 
package/lib/scan.mjs CHANGED
@@ -1,3 +1,15 @@
1
+ /**
2
+ * @file lib/scan.mjs
3
+ * @role 安全与合规扫描:文件名与内容里的敏感信息(密钥、令牌、私钥)、可疑脚本、可执行文件,产出分级报告
4
+ * @sub 安全检测、合规
5
+ * @exports scanFileName / looksBinary / scanFile / groupFindings / severityRank / scanEntries / renderScanReport
6
+ * @reads 包内文件字节(只在内存里)
7
+ * @writes 不落盘:命中原文不许写日志、不许进历史
8
+ * @risk 这是插件的安全底线:漏一条 high 等于把别人的密钥发出去;规则连「看起来像」的都要报,宁可多报
9
+ * @touch 加规则要同步 test/run.mjs 的样例与「命中不落盘」用例;改分级要同步客户端的红色确认流程
10
+ * @since 0.3.0
11
+ */
12
+
1
13
  /**
2
14
  * dsh-modpack —— 安全检测:敏感信息与恶意代码痕迹。
3
15
  *
package/lib/semver.mjs CHANGED
@@ -1,3 +1,13 @@
1
+ /**
2
+ * @file lib/semver.mjs
3
+ * @role 最小 semver:解析、比较、范围匹配(^ ~ 精确 * x 区间)
4
+ * @sub 版本
5
+ * @exports parseVersion / compareVersions / satisfies
6
+ * @risk 范围解析错会让「可更新」判断跟着错(把已是最新的说成能更新,或者反过来)
7
+ * @touch 加语法要同步 lib/registry.mjs 的 pickVersion 与 lib/plugin-manager.mjs 的 hasUpdate
8
+ * @since 0.3.0
9
+ */
10
+
1
11
  /**
2
12
  * dsh-modpack —— 极小 semver(够判兼容性,不做完整实现)。
3
13
  *