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.
package/index.js CHANGED
@@ -1,3 +1,15 @@
1
+ /**
2
+ * @file index.js
3
+ * @role 宿主半边:注册所有 /dsh-modpack-kit/api/* 路由、跑打包/安装/重装任务队列、给悬浮窗供数据、挂载三个附属小插件的路由表
4
+ * @sub 打包、安装、插件管理、社区资源、代码标注、插件树、任务队列、悬浮窗数据
5
+ * @exports api:route / api:createJob / api:publicJob / api:pruneJobs / api:mountSubRoutes / api:subRoute
6
+ * @reads profile(.dsh/profiles/<名字>)、插件自己的 config.json 与 packs/、各附属小插件的 manifest.json
7
+ * @writes 只写插件自己的状态目录与整合包文件;装插件、改启用态一律交给 lib/install.mjs 与 lib/plugin-manager.mjs
8
+ * @risk 路由名与 client.js 里的 api() 调用必须一一对应,改一个不改另一个就是 404;任务队列的状态机(running/paused/done/failed/cancelled)被悬浮窗与测试同时盯着
9
+ * @touch 改路由要同步 client.js、test/host-smoke.mjs、dev/tools/verify.cjs 的路由清单与 docs/CODE-MAP.md;改任务字段要同步 publicJob 与客户端的 JobDock
10
+ * @since 0.3.0
11
+ */
12
+
1
13
  /**
2
14
  * dsh-modpack-kit —— Host 侧。
3
15
  *
@@ -9,13 +21,14 @@
9
21
  */
10
22
  import fs from 'node:fs'
11
23
  import path from 'node:path'
24
+ import { fileURLToPath } from 'node:url'
12
25
  import { spawn } from 'node:child_process'
13
26
  import { randomBytes, createHash } from 'node:crypto'
14
27
  import { loadConfig, saveConfig, pathsFor, profileName, readHistory, appendHistory, clearHistory, removeHistory, appendLog, ensureDir, slugify, DEFAULT_CONFIG } from './lib/store.mjs'
15
28
  import { listInstalled, dshVersion, readProfilePackage, readBundles, runDshPlugin } from './lib/profile.mjs'
16
29
  import { downloadPackage, npmMetadata, pickVersion, fetchLimited, relativeTime, probeRegistry } from './lib/registry.mjs'
17
30
  import { buildPack, PackRefused } from './lib/pack.mjs'
18
- import { inspectPackBuffer, installPack, readPackFromUrl, InstallRefused } from './lib/install.mjs'
31
+ import { inspectPackBuffer, installPack, readPackFromUrl } from './lib/install.mjs'
19
32
  import { checkCompatibility } from './lib/compat.mjs'
20
33
  import { readMarketGroups, groupViews } from './lib/groups.mjs'
21
34
  import { classifyPlugin } from './lib/classify.mjs'
@@ -23,16 +36,38 @@ import { groupFindings } from './lib/scan.mjs'
23
36
  import { catalogSummary, searchCatalog, syncCatalog, categoryMapFor, lookupPlugins } from './lib/market-catalog.mjs'
24
37
  import { CATEGORY_FALLBACK, marketSummary, searchMarket, syncMarket, findMarketPack, fetchMarketPack } from './lib/modpack-catalog.mjs'
25
38
  import { resolveCommunity } from './lib/community.mjs'
39
+ import { findSubplugin, subEnabled, listSubplugins } from './lib/subplugins.mjs'
40
+ import { listManaged, setPluginEnabled, reinstallPlugin, resolveReinstallVersion, revealPluginDir, isValidPluginName, isValidVersion, pluginIcon, updatableItems, updatePlugins } from './lib/plugin-manager.mjs'
26
41
  import { whoAmI, openPackPullRequest, entryFileName, packFileName, ensureRelease, uploadReleaseAsset } from './lib/github.mjs'
42
+ import { themeActive, themeOf, themeVars, themeOptions } from './lib/theme.mjs'
27
43
  import { parseYaml } from './lib/yamlish.mjs'
28
44
  import { readPatch } from './lib/profile.mjs'
29
45
  import { buildReadme } from './lib/manifest.mjs'
30
46
  import { rewritePackManifest } from './lib/repack.mjs'
31
- import { sendJson as json, readBody, readRawBody, readJsonBody, MAX_JSON_BODY, MAX_DROP_BODY } from './lib/http.mjs'
47
+ import { testModeOn, playTestJob, testNote, testStepsFor } from './lib/testmode.mjs'
48
+ import { sendJson as json, readRawBody, readJsonBody, MAX_DROP_BODY } from './lib/http.mjs'
32
49
 
33
50
  const VERSION = (() => {
34
51
  try { return JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version || '0.0.0' } catch { return '0.0.0' }
35
52
  })()
53
+ // 插件自己的根目录:附属小插件读源码标注、读清单都从这里出发(不许由请求决定)
54
+ const ROOT = path.dirname(fileURLToPath(import.meta.url))
55
+ // 这份代码是什么时候被加载进进程的:客户端用「磁盘文件比它新」来判断要不要提示重启。
56
+ const LOADED_AT = Date.now()
57
+ // 只看自己这层的入口文件,够用来判断「磁盘上有人改过、但这一份还是旧的」
58
+ const RUNTIME_FILES = ['index.js', 'client.js', 'lib/subplugins.mjs', 'lib/theme.mjs', 'community/index.mjs', 'annotate/index.mjs', 'plugin-tree/index.mjs']
59
+
60
+ function runtimeFreshness() {
61
+ let newest = 0
62
+ let newestFile = ''
63
+ for (const rel of RUNTIME_FILES) {
64
+ try {
65
+ const st = fs.statSync(path.join(ROOT, rel))
66
+ if (st.mtimeMs > newest) { newest = st.mtimeMs; newestFile = rel }
67
+ } catch {}
68
+ }
69
+ return { loadedAt: LOADED_AT, newestMtime: Math.round(newest), newestFile, stale: newest > LOADED_AT + 1500 }
70
+ }
36
71
  const PENDING_TTL = 30 * 60 * 1000
37
72
  const PENDING_MAX = 4
38
73
  const PENDING_BYTES = 512 * 1024 * 1024
@@ -90,6 +125,18 @@ export default {
90
125
  electron: process.versions.electron || '',
91
126
  dshVersion: version,
92
127
  pluginVersion: VERSION,
128
+ // 测试模式:界面据此在顶部挂一个橙色标记,免得有人以为真装了东西
129
+ testMode: testModeOn(config),
130
+ // 配色:id + 两个实色 + 算好的 CSS 变量,界面直接挂到 :root 上。
131
+ // native(跟宿主黑白)时 vars 是空的,界面据此什么都不注入。
132
+ theme: (() => {
133
+ const theme = themeOf(config)
134
+ // 界面风格选「经典(改版前)」时干脆不给变量:客户端就算漏判也注入不了颜色
135
+ return { ...theme, vars: config.uiStyle === 'classic' ? {} : themeVars(theme), themed: themeActive(theme, config.uiStyle) }
136
+ })(),
137
+ themePresets: themeOptions(),
138
+ // 界面风格:classic = 改版前的界面(客户端据此不注入配色、设置页回平铺列表)
139
+ uiStyle: config.uiStyle === 'classic' ? 'classic' : 'new',
93
140
  profile: profileName(config),
94
141
  paths: pathsFor(config),
95
142
  catalog,
@@ -101,6 +148,14 @@ export default {
101
148
  community: (() => {
102
149
  try { return resolveCommunity(dir, config) } catch { return null }
103
150
  })(),
151
+ // 附属小插件清单:本插件下面挂着谁、各自几个接口、是内置还是外部实现、开没开
152
+ subplugins: (() => {
153
+ try { return listSubplugins(ROOT, dir, config) } catch { return [] }
154
+ })(),
155
+ // 磁盘上的文件是不是比运行中的这份新:界面据此提示「重启 DSH 才生效」
156
+ runtime: (() => {
157
+ try { return runtimeFreshness() } catch { return null }
158
+ })(),
104
159
  placements: {
105
160
  settings: config.showInSettings !== false,
106
161
  sidebar: config.showInSidebar !== false,
@@ -189,12 +244,74 @@ export default {
189
244
 
190
245
  // 社区资源是「整合包」的附属小插件:关掉它的时候,那几条接口统一回 404
191
246
  // (不是 405/500),界面据此提示「去设置里打开」,主体照常。
192
- const COMMUNITY_OFF = { ok: false, error: '社区资源已关闭(小插件没启用):在设置里打开「显示『社区资源』这一栏」' }
193
- const communityRoute = (pathname, handler) => route(pathname, async (req, res) => {
194
- if (config.showModpackMarket === false) { json(res, 404, COMMUNITY_OFF); return }
247
+ // 附属小插件统一走这里:谁被关掉,谁的接口就统一回 404(不是 405/500),
248
+ // 界面据此提示「去设置 → 附属小插件里打开」,主体照常跑。
249
+ // 名字里的括注(「社区资源(整合包的附属小插件)」)是给人看的全名,报错里只留短名。
250
+ const subLabel = (manifest) => {
251
+ const raw = String((manifest && (manifest.label || manifest.name)) || '这个附属小插件')
252
+ return raw.replace(/([^)]*)/gu, '').replace(/\([^)]*\)/gu, '').trim() || '这个附属小插件'
253
+ }
254
+ const subRoute = (id, pathname, handler) => route(pathname, async (req, res) => {
255
+ let manifest = null
256
+ try { manifest = findSubplugin(ROOT, id) } catch { manifest = null }
257
+ if (manifest && !subEnabled(manifest, config)) {
258
+ json(res, 404, { ok: false, error: subLabel(manifest) + '已关闭(附属小插件没启用):在设置 → 附属小插件里打开' })
259
+ return
260
+ }
195
261
  await handler(req, res)
196
262
  })
197
263
 
264
+ const communityRoute = (pathname, handler) => subRoute('dsh-modpack-community', pathname, handler)
265
+
266
+ // 代码标注、插件树这两个附属小插件自己带接口表;宿主只负责鉴权、方法校验与 JSON 包装。
267
+ // 它们的实现按需加载:启动时只读各自的 manifest(几百字节)来登记路由,
268
+ // 第一次真的有人调接口时才 import(插件树那条会顺带拉进 lib/plugin-graph.mjs)。
269
+ const subEngines = new Map()
270
+ const subTable = (id) => {
271
+ if (!subEngines.has(id)) {
272
+ const builders = {
273
+ 'dsh-modpack-annotate': () => import('./annotate/index.mjs').then((mod) => mod.annotateRoutes({ root: ROOT })),
274
+ 'dsh-modpack-plugin-tree': () => import('./plugin-tree/index.mjs').then((mod) => mod.treeRoutes({ root: ROOT, context: () => ({ profileDir: profileDir(), config }) })),
275
+ }
276
+ const build = builders[id]
277
+ if (!build) return null
278
+ const promise = build().catch((error) => {
279
+ subEngines.delete(id)
280
+ throw error
281
+ })
282
+ subEngines.set(id, promise)
283
+ }
284
+ return subEngines.get(id)
285
+ }
286
+ const mountLazySub = (id) => {
287
+ const manifest = (() => { try { return findSubplugin(ROOT, id) } catch { return null } })()
288
+ const listed = manifest && Array.isArray(manifest.routes) ? manifest.routes : []
289
+ for (const fullPath of listed) {
290
+ route(fullPath, async (req, res) => {
291
+ const now = (() => { try { return findSubplugin(ROOT, id) } catch { return null } })()
292
+ if (now && !subEnabled(now, config)) {
293
+ json(res, 404, { ok: false, error: subLabel(now) + '已关闭(附属小插件没启用):在设置 → 附属小插件里打开' })
294
+ return
295
+ }
296
+ const table = await subTable(id)
297
+ const item = (table || []).find((one) => one.path === fullPath || '/dsh-modpack-kit/api' + one.path === fullPath)
298
+ if (!item) {
299
+ json(res, 404, { ok: false, error: '这个附属小插件没有登记这条接口:' + fullPath })
300
+ return
301
+ }
302
+ const methods = Array.isArray(item.methods) && item.methods.length ? item.methods : ['GET']
303
+ if (!methods.includes(req.method)) {
304
+ json(res, 405, { ok: false, error: '只接受 ' + methods.join(' / ') })
305
+ return
306
+ }
307
+ const data = await item.run(req, res)
308
+ if (!res.writableEnded) json(res, 200, { ok: true, ...(data && typeof data === 'object' ? data : { data }) })
309
+ })
310
+ }
311
+ }
312
+ mountLazySub('dsh-modpack-annotate')
313
+ mountLazySub('dsh-modpack-plugin-tree')
314
+
198
315
  function pendingBytes() {
199
316
  let total = 0
200
317
  for (const item of pending.values()) total += item.buffer ? item.buffer.length : 0
@@ -334,7 +451,16 @@ export default {
334
451
  return
335
452
  }
336
453
  config = saveConfig(next)
337
- json(res, 200, { ok: true, config })
454
+ // 改完立刻把配色也算回去:界面拿这一份就地重挂主题变量,不用等下一次 /status
455
+ const themeNow = themeOf(config)
456
+ json(res, 200, {
457
+ ok: true,
458
+ config,
459
+ uiStyle: config.uiStyle === 'classic' ? 'classic' : 'new',
460
+ theme: { ...themeNow, vars: config.uiStyle === 'classic' ? {} : themeVars(themeNow), themed: themeActive(themeNow, config.uiStyle) },
461
+ themed: themeActive(themeNow, config.uiStyle),
462
+ themePresets: themeOptions(),
463
+ })
338
464
  })
339
465
 
340
466
  // —— 插件目录:分类、词条、分页搜索都照插件市场的来 ——
@@ -617,7 +743,8 @@ export default {
617
743
  const host = body.host === 'release' ? 'release' : 'repo'
618
744
  // 演练:把整套检查(类型、读包、改词条、封面、条目拼装)真跑一遍,
619
745
  // 但不碰 GitHub、不开 PR、不需要凭据。用来验实现,也方便先看条目长什么样。
620
- const dryRun = body.dryRun === true
746
+ // 测试模式:上传一律按「演练」处理,连凭据都不读
747
+ const dryRun = body.dryRun === true || testModeOn(config)
621
748
  const ownerRepo = String(body.repo || '').trim()
622
749
  const tag = String(body.tag || '').trim()
623
750
 
@@ -1049,6 +1176,8 @@ const COVER_MAX_BYTES = 300 * 1024
1049
1176
  finishedAt: '',
1050
1177
  error: '',
1051
1178
  data: null,
1179
+ // 分步骤的任务(重装插件)用它显示「做到哪一步了」;别的任务留空数组
1180
+ steps: [],
1052
1181
  // 风险停下来的任务:保留原始请求,等你选「立即停止」还是「我知道在干什么」
1053
1182
  risk: null,
1054
1183
  body: null,
@@ -1068,6 +1197,7 @@ const COVER_MAX_BYTES = 300 * 1024
1068
1197
  finishedAt: job.finishedAt,
1069
1198
  error: job.error,
1070
1199
  data: job.data,
1200
+ steps: Array.isArray(job.steps) ? job.steps : [],
1071
1201
  risk: job.risk,
1072
1202
  // 只有「可确认继续」的风险任务才给「我知道在干什么」;停下来的任务都能删
1073
1203
  canAck: Boolean(job.risk && job.risk.needsAck && job.status === 'paused'),
@@ -1250,6 +1380,11 @@ const COVER_MAX_BYTES = 300 * 1024
1250
1380
  }
1251
1381
  const startPackJob = (body, label) => {
1252
1382
  const job = createJob('pack', label || ('打包「' + String((body.options && body.options.name) || 'DSH 整合包') + '」'))
1383
+ if (testModeOn(config)) {
1384
+ // 测试模式:不打包、不联网、不写文件,只把流程与进度演一遍(见 lib/testmode.mjs)
1385
+ playTestJob(job, testStepsFor('pack'), { action: '打包', cancelled: () => Boolean(job.cancelled), data: { selection: Array.isArray(body.selection) ? body.selection : [] } })
1386
+ return job
1387
+ }
1253
1388
  // 留一份原始请求:风险停下来之后,界面上点「我知道在干什么」要能照原样再跑一次
1254
1389
  try {
1255
1390
  job.body = JSON.parse(JSON.stringify({
@@ -1298,6 +1433,10 @@ const COVER_MAX_BYTES = 300 * 1024
1298
1433
  }
1299
1434
  const version = typeof body.version === 'string' ? body.version.trim() : ''
1300
1435
  const wanted = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/u.test(version) ? name + '@' + version : name
1436
+ if (testModeOn(config)) {
1437
+ json(res, 200, { ok: true, test: true, note: testNote('安装插件'), spec: wanted, application: 'restart-required', restartRequired: true, error: '', output: '' })
1438
+ return
1439
+ }
1301
1440
  const manager = ctx.get('pluginManager')
1302
1441
  try {
1303
1442
  if (manager && typeof manager.installBundle === 'function') {
@@ -1330,6 +1469,240 @@ const COVER_MAX_BYTES = 300 * 1024
1330
1469
  }
1331
1470
  })
1332
1471
 
1472
+ // —— 插件管理:列表 / 启用禁用 / 重装 ——
1473
+ // 数据是「已装插件 + 插件市场那份状态」,市场不在也能用(停用退回配置层)。
1474
+ route('/dsh-modpack-kit/api/plugins', (req, res) => {
1475
+ if (req.method !== 'GET') { json(res, 405, { ok: false, error: '只支持 GET' }); return }
1476
+ try {
1477
+ json(res, 200, { ok: true, ...listManaged(profileDir(), config), profile: profileName(config) })
1478
+ } catch (error) {
1479
+ json(res, 500, { ok: false, error: String((error && error.message) || error) })
1480
+ }
1481
+ })
1482
+
1483
+ route('/dsh-modpack-kit/api/plugins/toggle', async (req, res) => {
1484
+ if (!needPost(req, res)) return
1485
+ const body = await readJsonBody(req)
1486
+ const name = typeof body.name === 'string' ? body.name.trim() : ''
1487
+ if (!isValidPluginName(name)) { json(res, 400, { ok: false, error: '插件名不合法' }); return }
1488
+ if (typeof body.enabled !== 'boolean') { json(res, 400, { ok: false, error: 'enabled 要给 true 或 false' }); return }
1489
+ if (testModeOn(config)) {
1490
+ json(res, 200, { ok: true, test: true, note: testNote(body.enabled ? '启用插件' : '停用插件'), name, enabled: body.enabled, restartRequired: true })
1491
+ return
1492
+ }
1493
+ try {
1494
+ json(res, 200, { ok: true, ...setPluginEnabled(profileDir(), name, body.enabled) })
1495
+ } catch (error) {
1496
+ json(res, 400, {
1497
+ ok: false,
1498
+ name,
1499
+ error: String((error && error.message) || error),
1500
+ hint: '停用状态写在插件市场那份名单里(没装市场就写配置层),下次启动 DSH 才生效。',
1501
+ })
1502
+ }
1503
+ })
1504
+
1505
+ route('/dsh-modpack-kit/api/plugins/reveal', async (req, res) => {
1506
+ if (!needPost(req, res)) return
1507
+ const body = await readJsonBody(req)
1508
+ const name = typeof body.name === 'string' ? body.name.trim() : ''
1509
+ try {
1510
+ json(res, 200, { ok: true, ...revealPluginDir(profileDir(), name) })
1511
+ } catch (error) {
1512
+ json(res, 400, { ok: false, error: String((error && error.message) || error) })
1513
+ }
1514
+ })
1515
+
1516
+ // 行首图标:只从已装插件的包里读(市场装的也是 npm 包),不联网。
1517
+ route('/dsh-modpack-kit/api/plugins/icon', (req, res) => {
1518
+ if (req.method !== 'GET') { json(res, 405, { ok: false, error: '只支持 GET' }); return }
1519
+ let name = ''
1520
+ try {
1521
+ const url = new URL(String(req.url || '/'), 'http://dsh.local')
1522
+ name = String(url.searchParams.get('name') || '').trim()
1523
+ } catch { name = '' }
1524
+ if (!isValidPluginName(name)) { json(res, 400, { ok: false, error: '插件名不合法' }); return }
1525
+ try {
1526
+ const icon = pluginIcon(profileDir(), name)
1527
+ json(res, 200, { ok: true, name: icon.name, mime: icon.mime, file: icon.file, size: icon.size, dataUrl: 'data:' + icon.mime + ';base64,' + icon.base64 })
1528
+ } catch (error) {
1529
+ json(res, 404, { ok: false, name, error: String((error && error.message) || error) })
1530
+ }
1531
+ })
1532
+
1533
+ // 一键更新:可更新 + 启用中 + 不是按路径装的,才算进来;停用的一律不跟着批量动。
1534
+ route('/dsh-modpack-kit/api/plugins/update-all', async (req, res) => {
1535
+ if (!needPost(req, res)) return
1536
+ const body = await readJsonBody(req)
1537
+ const dir = profileDir()
1538
+ let items = []
1539
+ try { items = listManaged(dir, config).items } catch (error) {
1540
+ json(res, 500, { ok: false, error: String((error && error.message) || error) })
1541
+ return
1542
+ }
1543
+ const wanted = Array.isArray(body.names) ? body.names.map((name) => String(name || '').trim()).filter(Boolean) : []
1544
+ let targets = updatableItems(items)
1545
+ if (wanted.length) targets = targets.filter((item) => wanted.includes(item.name))
1546
+ if (!targets.length) {
1547
+ json(res, 400, {
1548
+ ok: false,
1549
+ error: '没有可更新的插件',
1550
+ hint: '停用的插件、按路径装的插件不在一键更新里;要单独更新请用行尾的「更新」。',
1551
+ })
1552
+ return
1553
+ }
1554
+ const job = createJob('update', '一键更新 ' + targets.length + ' 个插件')
1555
+ if (testModeOn(config)) {
1556
+ const skipped = items.filter((item) => item.hasUpdate && updatableItems([item]).length === 0).map((item) => item.name)
1557
+ playTestJob(job, testStepsFor('update'), {
1558
+ action: '更新',
1559
+ cancelled: () => Boolean(job.cancelled),
1560
+ data: { updated: targets.map((item) => ({ name: item.name, from: item.version, to: item.latest })), failed: [], skipped },
1561
+ })
1562
+ json(res, 200, { ok: true, job: publicJob(job), names: targets.map((item) => item.name), test: true })
1563
+ return
1564
+ }
1565
+ job.steps = targets.map((item) => ({ key: item.name, label: item.name + (item.latest ? ' → ' + item.latest : ''), state: 'pending', note: '' }))
1566
+ job.note = '准备更新 ' + targets.length + ' 个插件'
1567
+ job.data = { names: targets.map((item) => item.name), skipped: items.filter((item) => item.hasUpdate && !updatableItems([item]).length).map((item) => item.name) }
1568
+ json(res, 200, { ok: true, job: publicJob(job), names: targets.map((item) => item.name) })
1569
+ ;(async () => {
1570
+ let current = ''
1571
+ try {
1572
+ const result = await updatePlugins({
1573
+ profileDir: dir,
1574
+ profile: profileName(config),
1575
+ config,
1576
+ targets: targets.map((item) => ({ name: item.name, latest: item.latest })),
1577
+ isCancelled: () => Boolean(job.cancelled),
1578
+ onProgress: (info) => {
1579
+ if (job.cancelled) return
1580
+ job.pct = Math.max(job.pct || 0, Number(info.pct) || 0)
1581
+ job.note = String(info.note || job.note)
1582
+ job.updatedAt = new Date().toISOString()
1583
+ if (info.step && info.step !== current) {
1584
+ const at = job.steps.findIndex((step) => step.key === info.step)
1585
+ if (at >= 0) {
1586
+ job.steps.forEach((step, index) => {
1587
+ if (index < at && step.state !== 'done' && step.state !== 'failed') step.state = 'done'
1588
+ })
1589
+ const row = job.steps[at]
1590
+ if (row.state === 'pending') row.state = 'running'
1591
+ }
1592
+ current = info.step
1593
+ }
1594
+ },
1595
+ })
1596
+ const failedNames = new Set((result.results || []).filter((row) => !row.ok).map((row) => row.name))
1597
+ job.steps = job.steps.map((step) => (
1598
+ failedNames.has(step.key)
1599
+ ? { ...step, state: 'failed', note: ((result.results || []).find((row) => row.name === step.key) || {}).error || '' }
1600
+ : { ...step, state: 'done' }
1601
+ ))
1602
+ job.cancelled = false
1603
+ job.status = 'done'
1604
+ job.pct = 100
1605
+ job.note = result.failed ? '更新完成,' + result.failed + ' 个没成功(点开看原因)' : '全部更新完成(' + result.updated + ' 个)'
1606
+ job.data = { ...result, skipped: (job.data && job.data.skipped) || [] }
1607
+ } catch (error) {
1608
+ const message = String((error && error.message) || error)
1609
+ const running = job.steps.find((step) => step.state === 'running')
1610
+ if (running) { running.state = 'failed'; running.note = message.slice(0, 200) }
1611
+ job.status = job.cancelled ? 'cancelled' : 'failed'
1612
+ job.error = message
1613
+ job.note = job.cancelled ? '已取消' : message.slice(0, 160)
1614
+ } finally {
1615
+ job.finishedAt = new Date().toISOString()
1616
+ job.updatedAt = job.finishedAt
1617
+ }
1618
+ })()
1619
+ })
1620
+
1621
+ route('/dsh-modpack-kit/api/plugins/reinstall', async (req, res) => {
1622
+ if (!needPost(req, res)) return
1623
+ const body = await readJsonBody(req)
1624
+ const name = typeof body.name === 'string' ? body.name.trim() : ''
1625
+ if (!isValidPluginName(name)) { json(res, 400, { ok: false, error: '插件名不合法' }); return }
1626
+ const wanted = typeof body.version === 'string' ? body.version.trim() : ''
1627
+ if (wanted && !isValidVersion(wanted)) { json(res, 400, { ok: false, error: '版本号要给完整 semver(例如 1.2.3)' }); return }
1628
+ const keepConfig = body.keepConfig !== false
1629
+ const dir = profileDir()
1630
+ let current = null
1631
+ try {
1632
+ current = listManaged(dir, config).items.find((item) => item.name === name) || null
1633
+ } catch { current = null }
1634
+ if (!current) { json(res, 404, { ok: false, error: '本机没有这个插件:' + name }); return }
1635
+ const target = wanted || resolveReinstallVersion(current)
1636
+ const job = createJob('reinstall', '重装 ' + name + (target ? '@' + target : ''))
1637
+ const plan = [
1638
+ ['read', '读取当前状态'],
1639
+ ['config', keepConfig ? '保留本机配置' : '清掉本机配置'],
1640
+ ['remove', '卸载旧版本'],
1641
+ ['install', '安装' + (target ? ' ' + target : ' 最新版')],
1642
+ ['restore', '恢复启用状态'],
1643
+ ['done', '收尾'],
1644
+ ]
1645
+ job.steps = plan.map(([key, label]) => ({ key, label, state: 'pending', note: '' }))
1646
+ job.note = '准备重装 ' + name
1647
+ const markStep = (key) => {
1648
+ const at = job.steps.findIndex((step) => step.key === key)
1649
+ if (at < 0) return
1650
+ job.steps.forEach((step, index) => {
1651
+ if (index < at && step.state !== 'done') step.state = 'done'
1652
+ if (index === at && step.state === 'pending') step.state = 'running'
1653
+ })
1654
+ }
1655
+ if (testModeOn(config)) {
1656
+ // 测试模式:步骤清单照旧显示,但一条也不执行(不卸载、不安装、不动配置)
1657
+ playTestJob(job, testStepsFor('reinstall'), { action: '重装', cancelled: () => Boolean(job.cancelled), data: { name, target, keepConfig } })
1658
+ json(res, 200, { ok: true, job: publicJob(job), target, test: true })
1659
+ return
1660
+ }
1661
+ json(res, 200, { ok: true, job: publicJob(job), target })
1662
+ ;(async () => {
1663
+ try {
1664
+ const result = await reinstallPlugin({
1665
+ profileDir: dir,
1666
+ profile: profileName(config),
1667
+ name,
1668
+ version: target || undefined,
1669
+ keepConfig,
1670
+ config,
1671
+ isCancelled: () => Boolean(job.cancelled),
1672
+ onProgress: (info) => {
1673
+ if (job.cancelled) return
1674
+ job.pct = Math.max(job.pct || 0, Number(info.pct) || 0)
1675
+ job.note = String(info.note || job.note)
1676
+ job.updatedAt = new Date().toISOString()
1677
+ if (info.step) markStep(info.step)
1678
+ },
1679
+ })
1680
+ // 插件已经装回来了:这时候即便点过取消也不能报取消,不然人会以为没装
1681
+ const wasCancelled = Boolean(job.cancelled)
1682
+ job.cancelled = false
1683
+ job.steps = job.steps.map((step) => ({ ...step, state: step.state === 'pending' || step.state === 'running' ? 'done' : step.state }))
1684
+ job.status = 'done'
1685
+ job.pct = 100
1686
+ job.note = '已重装 ' + name + (result.toVersion ? ' → ' + result.toVersion : '') + (wasCancelled ? '(中途点了取消,但已经装回来了)' : '')
1687
+ job.data = result
1688
+ } catch (error) {
1689
+ const message = String((error && error.message) || error)
1690
+ const cancelled = Boolean(job.cancelled) || /已取消/u.test(message)
1691
+ const running = job.steps.find((step) => step.state === 'running')
1692
+ if (running) {
1693
+ running.state = cancelled ? 'cancelled' : 'failed'
1694
+ running.note = message.slice(0, 200)
1695
+ }
1696
+ job.status = cancelled ? 'cancelled' : 'failed'
1697
+ job.error = message
1698
+ job.note = cancelled ? '已取消' : message.slice(0, 160)
1699
+ } finally {
1700
+ job.finishedAt = new Date().toISOString()
1701
+ job.updatedAt = job.finishedAt
1702
+ }
1703
+ })()
1704
+ })
1705
+
1333
1706
  route('/dsh-modpack-kit/api/pack', async (req, res) => {
1334
1707
  if (!needPost(req, res)) return
1335
1708
  const body = await readJsonBody(req)
@@ -1349,6 +1722,10 @@ const COVER_MAX_BYTES = 300 * 1024
1349
1722
  json(res, 200, { ok: true, async: true, job: publicJob(job) })
1350
1723
  return
1351
1724
  }
1725
+ if (testModeOn(config)) {
1726
+ json(res, 200, { ok: true, test: true, note: testNote('打包'), selection: [], groups: [] })
1727
+ return
1728
+ }
1352
1729
  const payload = await performPack(body, null)
1353
1730
  json(res, 200, payload)
1354
1731
  })
@@ -1454,6 +1831,19 @@ const COVER_MAX_BYTES = 300 * 1024
1454
1831
  route('/dsh-modpack-kit/api/download', async (req, res) => {
1455
1832
  if (!needPost(req, res)) return
1456
1833
  const body = await readJsonBody(req)
1834
+ const safeName0 = String(body.fileName || 'pack.dshpack').replace(/[^\w.\-]+/gu, '_')
1835
+ if (testModeOn(config)) {
1836
+ // 测试模式:不吐真实包体,给一份能存下来的占位文件,保存对话框、文件名、大小照走
1837
+ const fake = Buffer.from('测试模式:这份「' + safeName0 + '」只是流程占位,里面没有真的整合包数据。\n', 'utf8')
1838
+ res.writeHead(200, {
1839
+ 'Content-Type': 'application/octet-stream',
1840
+ 'Content-Disposition': 'attachment; filename="' + safeName0 + '"',
1841
+ 'Content-Length': fake.length,
1842
+ 'Cache-Control': 'no-store',
1843
+ })
1844
+ res.end(fake)
1845
+ return
1846
+ }
1457
1847
  const item = pending.get(String(body.token || ''))
1458
1848
  if (!item) { json(res, 404, { ok: false, error: '打包结果已过期,请重新打包' }); return }
1459
1849
  const safeName = String(body.fileName || item.fileName || 'pack.dshpack').replace(/[^\w.\-]+/gu, '_')
@@ -1469,6 +1859,11 @@ const COVER_MAX_BYTES = 300 * 1024
1469
1859
  route('/dsh-modpack-kit/api/save', async (req, res) => {
1470
1860
  if (!needPost(req, res)) return
1471
1861
  const body = await readJsonBody(req)
1862
+ if (testModeOn(config)) {
1863
+ const fakeName = slugify(body.fileName || 'test-pack', 'pack') + '.dshpack'
1864
+ json(res, 200, { ok: true, test: true, note: testNote('保存'), path: path.join(pathsFor(config).packs, fakeName), size: 0 })
1865
+ return
1866
+ }
1472
1867
  const item = pending.get(String(body.token || ''))
1473
1868
  if (!item) { json(res, 404, { ok: false, error: '打包结果已过期,请重新打包' }); return }
1474
1869
  const paths = pathsFor(config)
@@ -1547,6 +1942,10 @@ const COVER_MAX_BYTES = 300 * 1024
1547
1942
  }
1548
1943
  const name = raw
1549
1944
  const dir = pathsFor(config).packs
1945
+ if (testModeOn(config)) {
1946
+ json(res, 200, { ok: true, test: true, note: testNote('删除安装包'), dir, items: listPacks(dir).items })
1947
+ return
1948
+ }
1550
1949
  const target = path.join(dir, name)
1551
1950
  if (path.dirname(target) !== path.resolve(dir)) { json(res, 400, { ok: false, error: '不在插件自己的 packs 目录里' }); return }
1552
1951
  try {
@@ -1780,6 +2179,22 @@ const COVER_MAX_BYTES = 300 * 1024
1780
2179
  }
1781
2180
  push(4, '读取整合包')
1782
2181
  const inspected = await inspectInput(body)
2182
+ if (testModeOn(config)) {
2183
+ // 测试模式:包是真读的(校验 / 扫描 / 清单都照跑,只读不写),安装这一步只演
2184
+ if (job) {
2185
+ await playTestJob(job, testStepsFor('install'), { action: '安装', cancelled: () => Boolean(job.cancelled), data: { manifest: inspected.manifest && inspected.manifest.name, items: [] } })
2186
+ }
2187
+ return {
2188
+ ok: true,
2189
+ test: true,
2190
+ note: testNote('安装'),
2191
+ actions: [],
2192
+ manifest: inspected.manifest,
2193
+ scan: inspected.scan,
2194
+ integrity: inspected.integrity,
2195
+ report: inspected.report,
2196
+ }
2197
+ }
1783
2198
  const payload = await runInstall(inspected, body, job)
1784
2199
  // 装完按设置把这份安装包清掉:只删插件自己 packs 目录里的文件,别的路径不碰
1785
2200
  if (payload && payload.ok && config.autoClearPack === true) {