dsh-modpack-kit 0.1.1 → 0.1.4

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
@@ -9,11 +9,12 @@ import path from 'node:path'
9
9
  import { randomBytes } from 'node:crypto'
10
10
  import { loadConfig, saveConfig, pathsFor, profileName, readHistory, appendHistory, appendLog, ensureDir, slugify, DEFAULT_CONFIG } from './lib/store.mjs'
11
11
  import { listInstalled, dshVersion, readProfilePackage, readBundles } from './lib/profile.mjs'
12
- import { downloadPackage, npmMetadata, fetchLimited, relativeTime } from './lib/registry.mjs'
12
+ import { downloadPackage, npmMetadata, pickVersion, fetchLimited, relativeTime } from './lib/registry.mjs'
13
13
  import { buildPack, PackRefused } from './lib/pack.mjs'
14
14
  import { inspectPackBuffer, installPack, readPackFromUrl, InstallRefused } from './lib/install.mjs'
15
15
  import { checkCompatibility } from './lib/compat.mjs'
16
16
  import { classifyPlugin } from './lib/classify.mjs'
17
+ import { groupFindings } from './lib/scan.mjs'
17
18
  import { catalogSummary, searchCatalog, syncCatalog, categoryMapFor, lookupPlugins } from './lib/market-catalog.mjs'
18
19
  import { parseYaml } from './lib/yamlish.mjs'
19
20
  import { readPatch } from './lib/profile.mjs'
@@ -21,6 +22,8 @@ import { buildReadme, pluginSummary } from './lib/manifest.mjs'
21
22
 
22
23
  const VERSION = '0.1.0'
23
24
  const MAX_JSON_BODY = 1024 * 1024
25
+ // 直接拖进来的整合包走原始字节(不塞 base64),上限与单次下载一致,够装大包
26
+ const MAX_DROP_BODY = 256 * 1024 * 1024
24
27
  const PENDING_TTL = 30 * 60 * 1000
25
28
  const PENDING_MAX = 4
26
29
  const PENDING_BYTES = 512 * 1024 * 1024
@@ -42,6 +45,22 @@ const readBody = (req, limit = MAX_JSON_BODY) => new Promise((resolve, reject) =
42
45
  req.on('error', reject)
43
46
  })
44
47
 
48
+ const readRawBody = (req, limit = MAX_DROP_BODY) => new Promise((resolve, reject) => {
49
+ let size = 0
50
+ const chunks = []
51
+ req.on('data', (chunk) => {
52
+ size += chunk.length
53
+ if (size > limit) {
54
+ reject(Object.assign(new Error('整合包太大:上限 ' + Math.round(limit / 1024 / 1024) + ' MB'), { statusCode: 413 }))
55
+ req.destroy()
56
+ return
57
+ }
58
+ chunks.push(chunk)
59
+ })
60
+ req.on('end', () => resolve(Buffer.concat(chunks)))
61
+ req.on('error', reject)
62
+ })
63
+
45
64
  const asJson = (text, fallback) => {
46
65
  try { return JSON.parse(text) } catch { return fallback }
47
66
  }
@@ -309,44 +328,144 @@ export default {
309
328
  }
310
329
  })
311
330
 
312
- // —— 打包 ——
313
- route('/dsh-modpack-kit/api/pack', async (req, res) => {
314
- if (!needPost(req, res)) return
315
- const body = asJson(await readBody(req), {})
331
+ // —— 打包(支持后台任务:左下角悬浮窗要进度,且允许同时打多个包) ——
332
+ const jobs = new Map()
333
+ let jobSeq = 0
334
+ // 收尾的记录按状态分别留:完成的多留一会儿方便回看,失败/取消的很快就清,别堆在眼前。
335
+ // 秒数来自设置 jobKeepSeconds(0 = 收尾就清),测试就靠它把时间压到零。
336
+ const FAILED_KEEP = 15 * 1000
337
+ const RUNNING_STALE = 10 * 60 * 1000
338
+ const keepMs = () => Math.max(0, Number(config.jobKeepSeconds) || 0) * 1000
339
+ const heartbeatAge = (job, now) => {
340
+ const stamp = Date.parse(job.updatedAt || job.finishedAt || job.startedAt || '') || 0
341
+ return stamp > 0 ? now - stamp : 0
342
+ }
343
+ // 卡住的 running(进程还在但心跳没了):标成失败,让它走失败那条清理路径
344
+ const reapStuck = (job, now) => {
345
+ if (job.status !== 'running') return
346
+ if (heartbeatAge(job, now) <= RUNNING_STALE) return
347
+ job.status = 'failed'
348
+ job.error = '卡住了:很久没有新进度,已自动收掉'
349
+ job.note = '已自动收掉'
350
+ job.finishedAt = new Date().toISOString()
351
+ job.updatedAt = job.finishedAt
352
+ job.updatedAt = job.finishedAt
353
+ }
354
+ const pruneJobs = () => {
355
+ const now = Date.now()
356
+ const keep = keepMs()
357
+ for (const [id, job] of jobs) {
358
+ reapStuck(job, now)
359
+ // 停在风险点等你决定的,一直留着
360
+ if (job.status === 'paused') continue
361
+ if (job.status === 'running') continue
362
+ const age = heartbeatAge(job, now)
363
+ const limit = job.status === 'done' || job.status === 'acked' ? keep : Math.min(keep, FAILED_KEEP)
364
+ if (limit <= 0 || age > limit) jobs.delete(id)
365
+ }
366
+ for (const id of [...jobs.keys()]) {
367
+ if (jobs.size <= 20) break
368
+ const job = jobs.get(id)
369
+ if (job.status === 'running' || job.status === 'paused') continue
370
+ jobs.delete(id)
371
+ }
372
+ }
373
+ const createJob = (kind, label) => {
374
+ const job = {
375
+ id: 'job_' + (++jobSeq).toString(36) + '_' + Date.now().toString(36),
376
+ kind,
377
+ label,
378
+ status: 'running',
379
+ pct: 0,
380
+ note: '准备中',
381
+ startedAt: new Date().toISOString(),
382
+ // 最近一次有动静的时间:用来判断「还活着」还是「卡住了」
383
+ updatedAt: new Date().toISOString(),
384
+ finishedAt: '',
385
+ error: '',
386
+ data: null,
387
+ // 风险停下来的任务:保留原始请求,等你选「立即停止」还是「我知道在干什么」
388
+ risk: null,
389
+ body: null,
390
+ }
391
+ jobs.set(job.id, job)
392
+ pruneJobs()
393
+ return job
394
+ }
395
+ const publicJob = (job) => ({
396
+ id: job.id,
397
+ kind: job.kind,
398
+ label: job.label,
399
+ status: job.status,
400
+ pct: job.pct,
401
+ note: job.note,
402
+ startedAt: job.startedAt,
403
+ finishedAt: job.finishedAt,
404
+ error: job.error,
405
+ data: job.data,
406
+ risk: job.risk,
407
+ // 只有「可确认继续」的风险任务才给「我知道在干什么」;停下来的任务都能删
408
+ canAck: Boolean(job.risk && job.risk.needsAck && job.status === 'paused'),
409
+ canDismiss: job.status !== 'running',
410
+ })
411
+
412
+ class JobCancelled extends Error {}
413
+ const performPack = async (body, job, resume = null) => {
316
414
  const selection = Array.isArray(body.selection) ? body.selection : []
317
- if (selection.length === 0) { json(res, 400, { ok: false, error: '没有选择任何插件' }); return }
318
415
  const options = body.options && typeof body.options === 'object' ? body.options : {}
319
416
  const dir = profileDir()
320
417
  const installed = installedOrEmpty()
418
+ const dshVersionNow = (() => { try { return dshVersion(dir) } catch { return '' } })()
419
+ // 市场目录里能查到的插件:风险项默认放行,但需调用方 acknowledge
420
+ let trusted = []
421
+ try {
422
+ const look = lookupPlugins(config, selection.map((item) => String(item.name || '')).filter(Boolean))
423
+ trusted = Object.keys(look || {})
424
+ } catch { trusted = [] }
425
+ const onProgress = (event) => {
426
+ if (!job) return
427
+ if (job.cancelled) throw new JobCancelled('已取消')
428
+ job.pct = event.pct
429
+ job.note = event.note || job.note
430
+ }
321
431
  try {
322
432
  const result = await buildPack({
323
- selection: selection.map((item) => ({
324
- name: String(item.name || ''),
325
- source: item.source === 'npm' ? 'npm' : 'profile',
326
- spec: item.spec ? String(item.spec) : '',
327
- mode: item.mode === 'local' ? 'local' : item.mode === 'base' ? 'base' : undefined,
328
- download: (spec) => downloadPackage(String(item.name || ''), spec || item.spec || '', config),
329
- })),
433
+ selection: selection.map((item) => {
434
+ const name = String(item.name || '')
435
+ const here = installed.some((p) => p.name === name)
436
+ // 市场里没装的插件也能打包:本机没有这份代码,就从 registry 按版本取包
437
+ const source = item.source === 'npm' || item.source === 'market' || !here ? 'npm' : 'profile'
438
+ return {
439
+ name,
440
+ source,
441
+ spec: item.spec ? String(item.spec) : (source === 'npm' ? String(item.version || '') : ''),
442
+ mode: item.mode === 'local' ? 'local' : item.mode === 'base' ? 'base' : undefined,
443
+ download: (spec) => downloadPackage(name, spec || item.spec || String(item.version || ''), config),
444
+ }
445
+ }),
330
446
  options: {
331
447
  includePayload: options.includePayload !== false,
332
448
  includeConfig: options.includeConfig !== false,
333
449
  includeLocalEdits: options.includeLocalEdits === true,
334
450
  confirmLicense: options.confirmLicense === true,
335
451
  force: options.force === true,
452
+ acknowledge: options.acknowledge === true,
453
+ trusted,
336
454
  keepLocal: options.keepLocal !== false,
337
- // 扫描是强制的,客户端传什么都不认
338
455
  scanBeforePack: true,
456
+ onProgress,
339
457
  name: String(options.name || 'DSH 整合包'),
340
458
  description: String(options.description || ''),
341
459
  author: String(options.author || ''),
342
460
  license: String(options.license || ''),
343
461
  homepage: String(options.homepage || ''),
344
462
  extensions: options.extensions && typeof options.extensions === 'object' ? options.extensions : {},
463
+ resume: resume && typeof resume === 'object' ? resume : null,
345
464
  },
346
465
  context: {
347
466
  config,
348
467
  profileDir: dir,
349
- dshVersion: (() => { try { return dshVersion(dir) } catch { return '' } })(),
468
+ dshVersion: dshVersionNow,
350
469
  installed,
351
470
  pluginVersion: VERSION,
352
471
  extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
@@ -356,24 +475,219 @@ export default {
356
475
  })
357
476
  const token = rememberPending(result.fileName, { buffer: result.buffer, manifest: result.manifest, report: result.report, scan: result.scan })
358
477
  appendHistory({ at: new Date().toISOString(), kind: 'pack', name: result.manifest.name, format: result.manifest.format, plugins: result.manifest.plugins.map((p) => p.name + '@' + p.version), size: result.size, high: result.scan.counts.high }, config.historyLimit)
359
- json(res, 200, {
478
+ return {
360
479
  ok: true,
361
480
  token,
362
481
  fileName: result.fileName,
363
482
  size: result.size,
364
483
  manifest: result.manifest,
365
484
  scan: result.scan,
485
+ scanGroups: result.scanGroups,
366
486
  report: result.report,
367
487
  notes: result.notes,
368
- compat: checkCompatibility(result.manifest.plugins, { installed, dshVersion: (() => { try { return dshVersion(dir) } catch { return '' } })(), nodeVersion: process.versions.node, config }),
369
- })
488
+ compat: checkCompatibility(result.manifest.plugins, { installed, dshVersion: dshVersionNow, nodeVersion: process.versions.node, config }),
489
+ }
370
490
  } catch (error) {
491
+ if (error instanceof JobCancelled) {
492
+ // 取消发生在内存里:没有写入任何文件,直接丢弃缓冲
493
+ return { ok: false, cancelled: true, error: '已取消(未生成文件,本地没有残留)' }
494
+ }
371
495
  if (error instanceof PackRefused) {
372
- json(res, 200, { ok: false, refused: true, error: error.message, scan: error.scan })
496
+ const scanGroups = (() => { try { return error.scan ? groupFindings(error.scan.findings, (selection || []).map((item) => ({ name: String(item.name || '') }))) : [] } catch { return [] } })()
497
+ return {
498
+ ok: false,
499
+ refused: true,
500
+ needsAck: error.needsAck === true,
501
+ trustedOnly: error.trustedOnly === true,
502
+ error: error.message,
503
+ scan: error.scan,
504
+ scanGroups,
505
+ checkpoint: error.checkpoint || null,
506
+ }
507
+ }
508
+ return { ok: false, error: String((error && error.message) || error) }
509
+ }
510
+ }
511
+
512
+ // 任务收尾:只有「能确认继续」的风险才停下等你点一下;其余情况照旧判失败
513
+ const finishPackJob = (job, payload) => {
514
+ if (payload && payload.ok !== true && payload.refused === true) {
515
+ const counts = (payload.scan && payload.scan.counts) || {}
516
+ job.risk = {
517
+ high: counts.high || 0,
518
+ medium: counts.medium || 0,
519
+ low: counts.low || 0,
520
+ needsAck: payload.needsAck === true,
521
+ trustedOnly: payload.trustedOnly === true,
522
+ message: payload.error || '检测到风险',
523
+ // 只留分组摘要,不给界面塞整份 findings
524
+ groups: Array.isArray(payload.scanGroups)
525
+ ? payload.scanGroups.map((g) => ({
526
+ plugin: g.plugin || '',
527
+ label: g.label,
528
+ origin: g.origin,
529
+ counts: g.counts,
530
+ samples: Array.isArray(g.findings)
531
+ ? g.findings.slice(0, 4).map((f) => ({ label: f.label, severity: f.severity, file: f.file, line: f.line }))
532
+ : [],
533
+ }))
534
+ : [],
535
+ }
536
+ job.finishedAt = new Date().toISOString()
537
+ job.updatedAt = job.finishedAt
538
+ if (payload.needsAck === true) {
539
+ job.status = 'paused'
540
+ job.note = '检测到风险,等你决定'
541
+ job.pct = Math.min(job.pct || 0, 66)
542
+ job.checkpoint = payload.checkpoint || null
543
+ } else {
544
+ // 市场目录里查不到:没有「我知道在干什么」这条路,直接判失败
545
+ job.status = 'failed'
546
+ job.error = payload.error || '检测到风险'
547
+ job.note = '检测到风险,已拒绝出包'
548
+ job.data = payload
549
+ }
550
+ return
551
+ }
552
+ job.status = payload && payload.ok ? 'done' : payload && payload.cancelled === true ? 'cancelled' : 'failed'
553
+ job.data = payload
554
+ job.pct = payload && payload.ok ? 100 : job.pct
555
+ job.note = payload && payload.ok ? '完成' : ((payload && payload.error) || '已停止')
556
+ // 失败/取消也把原因放进 error,进度窗那一行能直接看到为什么卡住
557
+ if (!(payload && payload.ok)) job.error = (payload && payload.error) || job.note
558
+ job.finishedAt = new Date().toISOString()
559
+ job.updatedAt = job.finishedAt
560
+ }
561
+ const startPackJob = (body, label) => {
562
+ const job = createJob('pack', label || ('打包「' + String((body.options && body.options.name) || 'DSH 整合包') + '」'))
563
+ // 留一份原始请求:风险停下来之后,界面上点「我知道在干什么」要能照原样再跑一次
564
+ try {
565
+ job.body = JSON.parse(JSON.stringify({
566
+ selection: Array.isArray(body.selection) ? body.selection : [],
567
+ options: body.options && typeof body.options === 'object' ? body.options : {},
568
+ }))
569
+ } catch { job.body = null }
570
+ performPack(body, job)
571
+ .then((payload) => finishPackJob(job, payload))
572
+ .catch((error) => {
573
+ job.status = 'failed'
574
+ job.error = String((error && error.message) || error)
575
+ job.note = '失败'
576
+ job.finishedAt = new Date().toISOString()
577
+ job.updatedAt = job.finishedAt
578
+ })
579
+ return job
580
+ }
581
+
582
+ route('/dsh-modpack-kit/api/pack', async (req, res) => {
583
+ if (!needPost(req, res)) return
584
+ const body = asJson(await readBody(req), {})
585
+ const selection = Array.isArray(body.selection) ? body.selection : []
586
+ if (selection.length === 0) { json(res, 400, { ok: false, error: '没有选择任何插件' }); return }
587
+ if (body.async === true || body.background === true) {
588
+ const job = startPackJob(body)
589
+ json(res, 200, { ok: true, async: true, job: publicJob(job) })
590
+ return
591
+ }
592
+ const payload = await performPack(body, null)
593
+ json(res, 200, payload)
594
+ })
595
+
596
+ // 风险停下来之后:只有「我知道在干什么」,点它就在同一个任务里接着跑完
597
+ route('/dsh-modpack-kit/api/jobs/ack', async (req, res) => {
598
+ if (!needPost(req, res)) return
599
+ const body = asJson(await readBody(req), {})
600
+ const job = jobs.get(String(body.id || ''))
601
+ if (!job) { json(res, 404, { ok: false, error: '没有这个任务(可能已完成并过期)' }); return }
602
+ if (!job.risk) { json(res, 400, { ok: false, error: '这个任务没有风险项,不需要确认' }); return }
603
+ if (job.risk.needsAck !== true) { json(res, 400, { ok: false, error: '这些风险不在插件市场目录里,没法确认继续' }); return }
604
+ if (job.status === 'running') { json(res, 409, { ok: false, error: '任务还在跑,等它到风险点再说' }); return }
605
+ if (job.status !== 'paused') { json(res, 400, { ok: false, error: '这个任务已经收尾了,不能再确认' }); return }
606
+ // 同一个任务接着跑:复用停下来的那份检测结果,进度从检测点继续,不重新检测
607
+ const checkpoint = job.checkpoint || null
608
+ job.checkpoint = null
609
+ job.status = 'running'
610
+ job.cancelled = false
611
+ job.acked = true
612
+ // 确认过了就不该再吓人:红字(risk)撤掉,只留 status 与进度
613
+ job.risk = null
614
+ job.error = ''
615
+ job.note = checkpoint ? '已确认风险,从检测点继续' : '已确认风险,继续完成'
616
+ job.pct = Math.min(job.pct || 0, 66)
617
+ job.finishedAt = ''
618
+ const source = job.body || { selection: [] }
619
+ const replay = { selection: source.selection || [], options: { ...(source.options || {}), acknowledge: true } }
620
+ performPack(replay, job, checkpoint)
621
+ .then((payload) => finishPackJob(job, payload))
622
+ .catch((error) => {
623
+ job.status = 'failed'
624
+ job.error = String((error && error.message) || error)
625
+ job.note = '失败'
626
+ job.finishedAt = new Date().toISOString()
627
+ job.updatedAt = job.finishedAt
628
+ })
629
+ json(res, 200, { ok: true, job: publicJob(job) })
630
+ })
631
+
632
+ route('/dsh-modpack-kit/api/jobs/dismiss', async (req, res) => {
633
+ if (!needPost(req, res)) return
634
+ const body = asJson(await readBody(req), {})
635
+ const id = String(body.id || '')
636
+ const job = jobs.get(id)
637
+ if (!job) { json(res, 404, { ok: false, error: '没有这个任务(可能已经删了)' }); return }
638
+ if (job.status === 'running') { json(res, 400, { ok: false, error: '还在跑,先终止再删' }); return }
639
+ jobs.delete(id)
640
+ json(res, 200, { ok: true, removed: id })
641
+ })
642
+
643
+ // 清空进程:除了「正在跑」与「停在风险点等决定」,其余一律删——
644
+ // 完成的、失败的、取消的、超上限卡住的、以及假 running(心跳停了)都带走。
645
+ route('/dsh-modpack-kit/api/jobs/clear', async (req, res) => {
646
+ if (!needPost(req, res)) return
647
+ const removed = []
648
+ const now = Date.now()
649
+ for (const [id, job] of [...jobs.entries()]) {
650
+ if (job.status === 'paused') continue
651
+ if (job.status === 'running') {
652
+ // 还活着的不动;心跳停了的先标成失败,再按收尾清掉
653
+ reapStuck(job, now)
654
+ if (job.status === 'running') continue
655
+ }
656
+ // 卡住的 running:没有文件落盘(包在内存里组装),直接摘掉即可
657
+ jobs.delete(id)
658
+ removed.push(id)
659
+ }
660
+ pruneJobs()
661
+ json(res, 200, { ok: true, removed, jobs: [...jobs.values()].map(publicJob) })
662
+ })
663
+
664
+ route('/dsh-modpack-kit/api/jobs/cancel', async (req, res) => {
665
+ if (!needPost(req, res)) return
666
+ const body = asJson(await readBody(req), {})
667
+ const job = jobs.get(String(body.id || ''))
668
+ if (!job) { json(res, 404, { ok: false, error: '没有这个任务(可能已完成并过期)' }); return }
669
+ if (job.status !== 'running') {
670
+ // 停在风险点的任务:立即停止就是把它标成已停止,不留文件
671
+ if (job.status === 'paused') {
672
+ job.checkpoint = null
673
+ job.status = 'cancelled'
674
+ job.note = '已停止(未生成文件,本地没有残留)'
675
+ job.finishedAt = job.finishedAt || new Date().toISOString()
676
+ json(res, 200, { ok: true, job: publicJob(job) })
373
677
  return
374
678
  }
375
- json(res, 200, { ok: false, error: String((error && error.message) || error) })
679
+ json(res, 200, { ok: true, already: true, job: publicJob(job) })
680
+ return
376
681
  }
682
+ job.cancelled = true
683
+ job.note = '正在停止…'
684
+ json(res, 200, { ok: true, job: publicJob(job) })
685
+ })
686
+
687
+ route('/dsh-modpack-kit/api/jobs', (req, res) => {
688
+ if (req.method !== 'GET') { json(res, 405, { ok: false, error: '只支持 GET' }); return }
689
+ pruneJobs()
690
+ json(res, 200, { ok: true, jobs: [...jobs.values()].map(publicJob) })
377
691
  })
378
692
 
379
693
  // —— 下载 / 落盘 ——
@@ -406,19 +720,91 @@ export default {
406
720
  json(res, 200, { ok: true, path: target, size: item.buffer.length })
407
721
  })
408
722
 
409
- route('/dsh-modpack-kit/api/packs', async (req, res) => {
410
- if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
411
- const dir = pathsFor(config).packs
723
+ // 列某个目录下的整合包:GET 读本插件自己的 packs 目录,POST { dir } 读你指定的目录
724
+ const listPacks = (dir) => {
412
725
  const items = []
726
+ let error = ''
413
727
  try {
414
- for (const dirent of fs.readdirSync(dir, { withFileTypes: true })) {
415
- if (!dirent.isFile() || !dirent.name.endsWith('.dshpack')) continue
416
- const stat = fs.statSync(path.join(dir, dirent.name))
417
- items.push({ name: dirent.name, size: stat.size, mtime: stat.mtime.toISOString() })
728
+ const stat = fs.statSync(dir)
729
+ if (!stat.isDirectory()) error = '这个路径不是目录'
730
+ } catch (e) {
731
+ error = '这个目录读不到(不存在或没有权限)'
732
+ }
733
+ if (!error) {
734
+ try {
735
+ for (const dirent of fs.readdirSync(dir, { withFileTypes: true })) {
736
+ if (!dirent.isFile() || !dirent.name.toLowerCase().endsWith('.dshpack')) continue
737
+ const stat = fs.statSync(path.join(dir, dirent.name))
738
+ items.push({ name: dirent.name, size: stat.size, mtime: stat.mtime.toISOString(), path: path.join(dir, dirent.name) })
739
+ }
740
+ } catch (e) {
741
+ error = String((e && e.message) || e)
418
742
  }
419
- } catch {}
743
+ }
420
744
  items.sort((a, b) => (a.mtime < b.mtime ? 1 : -1))
421
- json(res, 200, { ok: true, dir, items })
745
+ return { error, items }
746
+ }
747
+
748
+ route('/dsh-modpack-kit/api/packs', async (req, res) => {
749
+ if (req.method === 'GET') {
750
+ const dir = pathsFor(config).packs
751
+ const listed = listPacks(dir)
752
+ json(res, 200, { ok: !listed.error, dir, items: listed.items, error: listed.error })
753
+ return
754
+ }
755
+ if (req.method !== 'POST') { json(res, 405, { ok: false }); return }
756
+ const body = asJson(await readBody(req), {})
757
+ const raw = String(body.dir || '').trim()
758
+ const dir = raw ? path.resolve(raw) : pathsFor(config).packs
759
+ const listed = listPacks(dir)
760
+ json(res, 200, { ok: !listed.error, dir, items: listed.items, error: listed.error })
761
+ })
762
+
763
+ // 拖到界面上的整合包:原始字节能走就走原始字节,走不通再走 base64 JSON
764
+ route('/dsh-modpack-kit/api/pack/drop', async (req, res) => {
765
+ if (!needPost(req, res)) return
766
+ let bytes = null
767
+ const contentType = String(req.headers['content-type'] || '').toLowerCase()
768
+ try {
769
+ if (contentType.includes('application/json')) {
770
+ // 有些环境不许 POST 二进制,界面会退回 base64:这里同样收
771
+ const body = asJson(await readBody(req, MAX_DROP_BODY), {}) || {}
772
+ const raw = typeof body.data === 'string' ? body.data : ''
773
+ if (!raw) { json(res, 400, { ok: false, error: '没有收到整合包内容' }); return }
774
+ bytes = Buffer.from(raw, 'base64')
775
+ } else {
776
+ bytes = await readRawBody(req)
777
+ }
778
+ } catch (error) {
779
+ json(res, 413, { ok: false, error: String((error && error.message) || error) })
780
+ return
781
+ }
782
+ if (!bytes || bytes.length < 32) { json(res, 400, { ok: false, error: '这个文件看起来不是整合包(太小了)' }); return }
783
+ try {
784
+ const inspected = inspectPackBuffer(bytes, {
785
+ config,
786
+ scanBeforeInstall: config.scanBeforeInstall !== false,
787
+ extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
788
+ })
789
+ const fileName = slugify(inspected.manifest.name || 'dropped', 'pack') + '.dshpack'
790
+ const token = rememberPending(fileName, { buffer: bytes, manifest: inspected.manifest, report: inspected.report, scan: inspected.scan })
791
+ json(res, 200, {
792
+ ok: true,
793
+ token,
794
+ fileName,
795
+ size: bytes.length,
796
+ manifest: inspected.manifest,
797
+ integrity: inspected.integrity,
798
+ scan: inspected.scan,
799
+ scanGroups: groupFindings(inspected.scan.findings, inspected.manifest.plugins),
800
+ report: inspected.report,
801
+ blockingReasons: inspected.blockingReasons,
802
+ notes: inspected.notes,
803
+ compat: compatFor(inspected.manifest),
804
+ })
805
+ } catch (error) {
806
+ json(res, 200, { ok: false, error: String((error && error.message) || error) })
807
+ }
422
808
  })
423
809
 
424
810
  async function inspectInput(body) {
@@ -451,6 +837,7 @@ export default {
451
837
  manifest: inspected.manifest,
452
838
  integrity: inspected.integrity,
453
839
  scan: inspected.scan,
840
+ scanGroups: groupFindings(inspected.scan.findings, inspected.manifest.plugins),
454
841
  report: inspected.report,
455
842
  blockingReasons: inspected.blockingReasons,
456
843
  notes: inspected.notes,
@@ -463,51 +850,186 @@ export default {
463
850
  })
464
851
 
465
852
  // —— 安装 ——
466
- route('/dsh-modpack-kit/api/install', async (req, res) => {
467
- if (!needPost(req, res)) return
468
- const body = asJson(await readBody(req), {})
469
- const options = {
470
- force: body.force === true,
471
- keepLocal: body.keepLocal !== false,
472
- applyConfig: body.applyConfig !== false,
473
- dryRun: body.dryRun === true,
474
- // 是否登记 bundle:请求里给了就听请求的,没给就听设置里的 enableOnInstall(默认关)。
475
- enableBundles: typeof body.enableBundles === 'boolean' ? body.enableBundles : config.enableOnInstall === true,
853
+ // —— 安装:先跳过本机已装的,装完其余再问要不要替换 ——
854
+ const pendingInstalls = new Map()
855
+ const rememberInstall = (inspected) => {
856
+ const token = 'inst_' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36)
857
+ pendingInstalls.set(token, { inspected, at: Date.now() })
858
+ // 上限 4 份、30 分钟过期:别让内存一直攒着包
859
+ for (const [key, item] of pendingInstalls) {
860
+ if (pendingInstalls.size <= 4) break
861
+ if (key === token) continue
862
+ pendingInstalls.delete(key)
476
863
  }
477
- try {
478
- const inspected = await inspectInput(body)
479
- if (inspected.blockingReasons.length > 0 && !options.force) {
480
- const refused = new InstallRefused(inspected.blockingReasons.join(';'), inspected.scan)
481
- json(res, 200, { ok: false, refused: true, error: refused.message, integrity: inspected.integrity, scan: inspected.scan, report: inspected.report })
482
- return
864
+ for (const [key, item] of pendingInstalls) {
865
+ if (Date.now() - item.at > 30 * 60 * 1000) pendingInstalls.delete(key)
866
+ }
867
+ return token
868
+ }
869
+
870
+ const installOptionsOf = (body) => ({
871
+ force: body.force === true,
872
+ keepLocal: body.keepLocal !== false,
873
+ applyConfig: body.applyConfig !== false,
874
+ dryRun: body.dryRun === true,
875
+ // 是否登记 bundle:请求里给了就听请求的,没给就听设置里的 enableOnInstall(默认关)。
876
+ enableBundles: typeof body.enableBundles === 'boolean' ? body.enableBundles : config.enableOnInstall === true,
877
+ // 默认:本机已装(同名或同插件不同版本)先跳过,其余照装,最后再问
878
+ deferExisting: body.deferExisting !== false && body.replaceExisting !== true,
879
+ replaceExisting: body.replaceExisting === true,
880
+ only: Array.isArray(body.only) && body.only.length > 0 ? body.only.map(String) : null,
881
+ // 联网且有插件市场时优先按市场版本装(默认开;请求里能逐次关掉)
882
+ preferMarket: typeof body.preferMarket === 'boolean' ? body.preferMarket : config.preferMarketOnInstall !== false,
883
+ })
884
+
885
+ const runInstall = async (inspected, body, job) => {
886
+ const options = installOptionsOf(body)
887
+ const push = (pct, note) => {
888
+ if (!job) return
889
+ if (job.cancelled) throw new JobCancelled('已取消')
890
+ job.pct = pct
891
+ job.note = note || job.note
892
+ job.updatedAt = new Date().toISOString()
893
+ }
894
+ const scanGroups = groupFindings(inspected.scan.findings, inspected.manifest.plugins)
895
+ if (inspected.blockingReasons.length > 0 && !options.force) {
896
+ return {
897
+ ok: false,
898
+ refused: true,
899
+ error: inspected.blockingReasons.join(';'),
900
+ integrity: inspected.integrity,
901
+ scan: inspected.scan,
902
+ scanGroups,
903
+ report: inspected.report,
483
904
  }
484
- const result = await installPack({
485
- manifest: inspected.manifest,
486
- entries: inspected.entries,
487
- config,
488
- options,
489
- context: {
490
- profileDir: profileDir(),
491
- resolveSource: async (plugin, packRoot) => {
492
- const downloaded = await downloadPackage(plugin.name, plugin.version || plugin.requested || '', config)
493
- const target = path.join(packRoot, 'plugins', plugin.dirName || plugin.name)
494
- ensureDir(target)
495
- for (const entry of downloaded.entries) {
496
- const dest = path.join(target, entry.name)
497
- if (!path.resolve(dest).startsWith(path.resolve(target) + path.sep)) continue
498
- ensureDir(path.dirname(dest))
499
- fs.writeFileSync(dest, entry.data)
500
- }
501
- appendLog('resolve ' + plugin.name + '@' + downloaded.version + ' from ' + downloaded.registry)
502
- return target
503
- },
905
+ }
906
+ push(12, '开始安装')
907
+ const result = await installPack({
908
+ manifest: inspected.manifest,
909
+ entries: inspected.entries,
910
+ config,
911
+ options: { ...options, onProgress: (event) => push(event.pct, event.note) },
912
+ context: {
913
+ profileDir: profileDir(),
914
+ // 联网且市场可用时,优先按市场版本装(能用就返回 name@version,用不了返回 null 走包内)
915
+ resolveMarket: async (plugin) => {
916
+ try {
917
+ const { meta } = await npmMetadata(plugin.name, config)
918
+ const version = pickVersion(meta, plugin.version || plugin.spec || '') || pickVersion(meta, '')
919
+ if (!version) return null
920
+ appendLog('market ' + plugin.name + '@' + version + ' 优先于包内 ' + (plugin.version || '(未标版本)'))
921
+ return { spec: plugin.name + '@' + version, version }
922
+ } catch (error) {
923
+ appendLog('market miss ' + plugin.name + ': ' + String((error && error.message) || error))
924
+ return null
925
+ }
504
926
  },
505
- })
506
- appendHistory({ at: new Date().toISOString(), kind: 'install', name: inspected.manifest.name, format: inspected.manifest.format, ok: result.ok, pack: inspected.manifest.name, actions: result.actions.length }, config.historyLimit)
507
- json(res, 200, { ok: result.ok, ...result, manifest: inspected.manifest, scan: inspected.scan, report: inspected.report, integrity: inspected.integrity })
927
+ resolveSource: async (plugin, packRoot) => {
928
+ const downloaded = await downloadPackage(plugin.name, plugin.version || plugin.requested || '', config)
929
+ const target = path.join(packRoot, 'plugins', plugin.dirName || plugin.name)
930
+ ensureDir(target)
931
+ for (const entry of downloaded.entries) {
932
+ const dest = path.join(target, entry.name)
933
+ if (!path.resolve(dest).startsWith(path.resolve(target) + path.sep)) continue
934
+ ensureDir(path.dirname(dest))
935
+ fs.writeFileSync(dest, entry.data)
936
+ }
937
+ appendLog('resolve ' + plugin.name + '@' + downloaded.version + ' from ' + downloaded.registry)
938
+ return target
939
+ },
940
+ },
941
+ })
942
+ appendHistory({ at: new Date().toISOString(), kind: 'install', name: inspected.manifest.name, format: inspected.manifest.format, ok: result.ok, pack: inspected.manifest.name, actions: result.actions.length }, config.historyLimit)
943
+ const token = rememberInstall(inspected)
944
+ return {
945
+ ok: result.ok,
946
+ ...result,
947
+ token,
948
+ manifest: inspected.manifest,
949
+ scan: inspected.scan,
950
+ scanGroups,
951
+ report: inspected.report,
952
+ integrity: inspected.integrity,
953
+ }
954
+ }
955
+
956
+ const performInstall = async (body, job) => {
957
+ try {
958
+ const push = (pct, note) => {
959
+ if (!job) return
960
+ if (job.cancelled) throw new JobCancelled('已取消')
961
+ job.pct = pct
962
+ job.note = note || job.note
963
+ }
964
+ push(4, '读取整合包')
965
+ const inspected = await inspectInput(body)
966
+ return await runInstall(inspected, body, job)
508
967
  } catch (error) {
509
- json(res, 200, { ok: false, error: String((error && error.message) || error) })
968
+ if (error instanceof JobCancelled) return { ok: false, cancelled: true, error: '已取消(没有改动 profile)' }
969
+ return { ok: false, error: String((error && error.message) || error) }
970
+ }
971
+ }
972
+
973
+ const finishInstallJob = (job, payload) => {
974
+ job.status = payload && payload.ok ? 'done' : payload && payload.cancelled === true ? 'cancelled' : 'failed'
975
+ job.data = payload
976
+ job.pct = payload && payload.ok ? 100 : job.pct
977
+ job.note = payload && payload.ok ? '完成' : ((payload && payload.error) || '已停止')
978
+ if (!(payload && payload.ok)) job.error = (payload && payload.error) || job.note
979
+ job.finishedAt = new Date().toISOString()
980
+ job.updatedAt = job.finishedAt
981
+ }
982
+
983
+ const startInstallJob = (body, label) => {
984
+ const job = createJob('install', label || '安装整合包')
985
+ performInstall(body, job)
986
+ .then((payload) => finishInstallJob(job, payload))
987
+ .catch((error) => {
988
+ job.status = 'failed'
989
+ job.error = String((error && error.message) || error)
990
+ job.note = '失败'
991
+ job.finishedAt = new Date().toISOString()
992
+ job.updatedAt = job.finishedAt
993
+ })
994
+ return job
995
+ }
996
+
997
+ route('/dsh-modpack-kit/api/install', async (req, res) => {
998
+ if (!needPost(req, res)) return
999
+ const body = asJson(await readBody(req), {})
1000
+ if (body.async === true || body.background === true) {
1001
+ const job = startInstallJob(body, body.label ? String(body.label) : undefined)
1002
+ json(res, 200, { ok: true, async: true, job: publicJob(job) })
1003
+ return
1004
+ }
1005
+ const payload = await performInstall(body, null)
1006
+ json(res, 200, payload)
1007
+ })
1008
+
1009
+ // 装完的追问:把刚才跳过的那些换成包内版本
1010
+ route('/dsh-modpack-kit/api/install/replace', async (req, res) => {
1011
+ if (!needPost(req, res)) return
1012
+ const body = asJson(await readBody(req), {})
1013
+ const token = String(body.token || '')
1014
+ const item = pendingInstalls.get(token)
1015
+ if (!item) { json(res, 400, { ok: false, error: '这次安装的上下文已过期,请重新读一遍整合包' }); return }
1016
+ const names = Array.isArray(body.names) && body.names.length > 0 ? body.names.map(String) : null
1017
+ if (body.async === true || body.background === true) {
1018
+ const job = createJob('install', '替换为包内版本' + (names ? '(' + names.length + ' 个)' : ''))
1019
+ runInstall(item.inspected, { ...body, replaceExisting: true, keepLocal: false, only: names }, job)
1020
+ .then((payload) => finishInstallJob(job, payload))
1021
+ .catch((error) => {
1022
+ job.status = 'failed'
1023
+ job.error = String((error && error.message) || error)
1024
+ job.note = '失败'
1025
+ job.finishedAt = new Date().toISOString()
1026
+ job.updatedAt = job.finishedAt
1027
+ })
1028
+ json(res, 200, { ok: true, async: true, job: publicJob(job) })
1029
+ return
510
1030
  }
1031
+ const payload = await runInstall(item.inspected, { ...body, replaceExisting: true, keepLocal: false, only: names }, null)
1032
+ json(res, 200, payload)
511
1033
  })
512
1034
 
513
1035
  // —— 历史 ——