dsh-modpack-kit 0.1.8 → 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/lib/install.mjs CHANGED
@@ -13,6 +13,7 @@ import { MANIFEST_NAME, normalizeManifest, sha256 } from './manifest.mjs'
13
13
  import { checkCompatibility } from './compat.mjs'
14
14
  import { captureConfigs, collectFiles } from './pack.mjs'
15
15
  import { upsertPatchItem, parseYaml } from './yamlish.mjs'
16
+ import { applyMarketGroups, hasMarket } from './groups.mjs'
16
17
  import {
17
18
  ensureDir,
18
19
  writeJsonAtomic,
@@ -257,6 +258,18 @@ export async function installPack(input) {
257
258
  const total = manifest.plugins.length
258
259
  let restartFromManager = false
259
260
 
261
+ // 离线也能装懒人包:完整包(以及混合包里带本体的那几个)代码就在包里。
262
+ // 先快速探一下 registry,不通就别再「先按市场版本装」——不然每个插件都要等一遍超时。
263
+ let offline = options.offline === true
264
+ if (!offline && options.offline !== false && typeof context.probeRegistry === 'function') {
265
+ try {
266
+ offline = !(await context.probeRegistry())
267
+ } catch {
268
+ offline = false
269
+ }
270
+ if (offline) lines.push('现在连不上 registry:本次直接用包里自带的插件(插件市场会显示成本地安装),不联网也能装完')
271
+ }
272
+
260
273
  for (const plugin of manifest.plugins) {
261
274
  const index = manifest.plugins.indexOf(plugin)
262
275
  progress({ pct: 12 + Math.round(((index + 1) / total) * 68), note: '安装 ' + plugin.name + (plugin.version ? ' ' + plugin.version : '') })
@@ -287,7 +300,7 @@ export async function installPack(input) {
287
300
  // 取不到 / 离线 / 关掉开关(options.preferMarket === false)时,按包内带来的那份装。
288
301
  // 例外:包里这份当初就是从插件市场取的(source npm/market),无论开关如何都优先走市场,
289
302
  // 因为包内那份只是同一份市场包的副本;市场取不到再退回包内副本。
290
- const fromMarketSource = plugin.source === 'npm' || plugin.source === 'market'
303
+ const fromMarketSource = !offline && (plugin.source === 'npm' || plugin.source === 'market')
291
304
  let marketHit = null
292
305
  // 包里这份本来就是从 registry 取的(source npm/market)时,版本号已经记在清单里,
293
306
  // 不必再问一次 registry:直接按 name@version 装,插件市场才会把它记成市场版
@@ -295,7 +308,7 @@ export async function installPack(input) {
295
308
  if (fromMarketSource && plugin.version && String(plugin.version) !== '0.0.0' && /^[0-9][0-9A-Za-z.+-]*$/u.test(String(plugin.version))) {
296
309
  marketHit = { spec: plugin.name + '@' + plugin.version, version: String(plugin.version), fromPack: true }
297
310
  }
298
- if (!marketHit && (options.preferMarket !== false || fromMarketSource) && typeof context.resolveMarket === 'function') {
311
+ if (!offline && !marketHit && (options.preferMarket !== false || fromMarketSource) && typeof context.resolveMarket === 'function') {
299
312
  try {
300
313
  marketHit = await context.resolveMarket(plugin)
301
314
  } catch (error) {
@@ -305,17 +318,52 @@ export async function installPack(input) {
305
318
  }
306
319
 
307
320
  let dir = null
321
+ // 这个插件的代码是不是就装在包里(完整包全部是;混合包只有「没有确定版本 / 要带本机改动」的那几个是)
322
+ let embedded = false
308
323
  // 轻量包的代码是刚从 registry 取回来的,装的时候直接用 name@version:
309
324
  // 用 file: 指向临时目录的话,临时目录一删就断,插件市场也会当成「本地安装」。
310
325
  let resolvedSpec = null
326
+ // 轻量包在内存里扫:把 tarball 解出来的条目直接交给扫描器,
327
+ // 不再先落一份到临时目录再扫(少一次磁盘写、也不会有残留要清)。
328
+ let memoryEntries = null
311
329
  if (!marketHit) {
312
- if (manifest.format === 'full' && pluginPayload(entries, plugin.dirName || plugin.name).length > 0) {
330
+ if (pluginPayload(entries, plugin.dirName || plugin.name).length > 0) {
313
331
  try {
314
332
  dir = materializePayload(entries, manifest, plugin, config)
333
+ embedded = true
315
334
  } catch (error) {
316
335
  actions.push({ plugin: plugin.name, action: 'install', ok: false, message: String(error?.message || error) })
317
336
  continue
318
337
  }
338
+ } else if (typeof context.resolveSourceEntries === 'function') {
339
+ if (offline) {
340
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '当前没网:这个包只记版本、没带本体,装不了;联网后再试,或改用完整包(混合包里带本体的插件也一样能离线装)' })
341
+ continue
342
+ }
343
+ try {
344
+ memoryEntries = await context.resolveSourceEntries(plugin)
345
+ if (!Array.isArray(memoryEntries) || memoryEntries.length === 0) throw new Error('取回来的包里没有文件')
346
+ } catch (error) {
347
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '取包失败:' + String(error?.message || error) })
348
+ continue
349
+ }
350
+ if (plugin.version && String(plugin.version) !== '0.0.0') resolvedSpec = plugin.name + '@' + plugin.version
351
+ // 轻量包本体不夹带源码,真正的代码是刚取回来的:装之前必须补扫一遍,否则「安装前检测」是空转
352
+ try {
353
+ const deep = scanEntries(memoryEntries, { extraRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [] })
354
+ if (deep.counts.high > 0 && !options.force && !acknowledged) {
355
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '从市场取回的代码里有 ' + deep.counts.high + ' 个高风险项,已拦下' })
356
+ continue
357
+ }
358
+ lines.push('轻量包:已补扫从市场取回的 ' + deep.scannedFiles + ' 个文件(高 ' + deep.counts.high + ',全程在内存里,没有落盘)')
359
+ } catch (error) {
360
+ actions.push({ plugin: plugin.name, action: 'install', ok: false, message: '补充扫描失败:' + String(error?.message || error) })
361
+ continue
362
+ }
363
+ if (options.dryRun) {
364
+ actions.push({ plugin: plugin.name, action: 'install', ok: true, message: '演练:将按 ' + (resolvedSpec || plugin.name) + ' 从市场安装(已内存扫描 ' + memoryEntries.length + ' 个文件)' })
365
+ continue
366
+ }
319
367
  } else if (typeof context.resolveSource === 'function') {
320
368
  try {
321
369
  dir = await context.resolveSource(plugin, packRoot)
@@ -328,8 +376,8 @@ export async function installPack(input) {
328
376
  continue
329
377
  }
330
378
 
331
- if (manifest.format !== 'full') {
332
- if (plugin.version && String(plugin.version) !== '0.0.0') resolvedSpec = plugin.name + '@' + plugin.version
379
+ if (!embedded) {
380
+ if (!resolvedSpec && plugin.version && String(plugin.version) !== '0.0.0') resolvedSpec = plugin.name + '@' + plugin.version
333
381
  // 轻量包本体不夹带源码,真正的代码是刚下载回来的:装之前必须补扫一遍,否则「安装前检测」是空转
334
382
  try {
335
383
  const brought = collectFiles(dir, {
@@ -358,7 +406,13 @@ export async function installPack(input) {
358
406
  continue
359
407
  }
360
408
 
361
- const targetSpec = marketHit ? marketHit.spec : resolvedSpec || 'file:' + dir
409
+ // 完整包默认先按「名字@版本」从市场装:能联网且版本存在时,profile 依赖会写成 ^版本,
410
+ // 插件市场据此认成「市场版」(方案 A)。失败或离线才退回包内副本(file:,市场显示本地安装)。
411
+ let preferMarketSpec = null
412
+ if (!offline && !marketHit && embedded && options.preferMarketOnInstall !== false && options.preferMarket !== false && dir && plugin.version && String(plugin.version) !== '0.0.0' && /^[0-9][0-9A-Za-z.+-]*$/u.test(String(plugin.version))) {
413
+ preferMarketSpec = plugin.name + '@' + String(plugin.version)
414
+ }
415
+ const targetSpec = marketHit ? marketHit.spec : preferMarketSpec || resolvedSpec || 'file:' + dir
362
416
  let attempt = await installSpec(targetSpec, marketHit && marketHit.version ? { name: plugin.name, version: marketHit.version } : null)
363
417
  let code = attempt.code
364
418
  let application = attempt.application
@@ -369,7 +423,7 @@ export async function installPack(input) {
369
423
 
370
424
  // registry 这条路断了时,退回包里/本地已有的那份——能装上比装不上强,但依赖会写成 file:,
371
425
  // 插件市场会把它当成本地安装,所以下面要明确提示。
372
- if (code !== 0 && marketHit && marketHit.fromPack && manifest.format === 'full' && !dir && pluginPayload(entries, plugin.dirName || plugin.name).length > 0) {
426
+ if (code !== 0 && marketHit && marketHit.fromPack && !dir && pluginPayload(entries, plugin.dirName || plugin.name).length > 0) {
373
427
  try {
374
428
  dir = materializePayload(entries, manifest, plugin, config)
375
429
  } catch (error) {
@@ -386,6 +440,16 @@ export async function installPack(input) {
386
440
  if (application === 'restart-required') restartFromManager = true
387
441
  }
388
442
  }
443
+ if (code !== 0 && preferMarketSpec && dir) {
444
+ appendLog('install ' + plugin.name + ' market failed exit=' + code + ' retry=pack')
445
+ lines.push('按 ' + preferMarketSpec + ' 没装成(退出码 ' + code + '),改用包内自带的那份继续(插件市场会显示成本地安装)')
446
+ attempt = await installSpec('file:' + dir, null)
447
+ code = attempt.code
448
+ usedManager = attempt.manager
449
+ application = attempt.application
450
+ if (application === 'restart-required') restartFromManager = true
451
+ preferMarketSpec = null
452
+ }
389
453
  if (code !== 0 && resolvedSpec && dir) {
390
454
  appendLog('install ' + plugin.name + ' market failed exit=' + code + ' retry=file')
391
455
  lines.push('按 ' + resolvedSpec + ' 装失败(退出码 ' + code + '),改用本地已下载的副本重试')
@@ -464,8 +528,16 @@ export async function installPack(input) {
464
528
  let text = patch
465
529
  for (const plugin of manifest.plugins) {
466
530
  const snap = manifest.plugins.find((p) => p.name === plugin.name && p.configIncluded)
531
+ const perPlugin = options.configChoice && typeof options.configChoice === 'object' ? options.configChoice[plugin.name] : undefined
532
+ if (perPlugin === 'local') {
533
+ actions.push({ plugin: plugin.name, action: 'config', ok: true, message: '按你的选择:这个插件保持本机配置,不覆盖' })
534
+ continue
535
+ }
536
+ if (perPlugin === 'pack') {
537
+ // 明确要求用包内配置:跳过「保留本地」的判断
538
+ }
467
539
  if (!snap) continue
468
- if (options.keepLocal !== false && config.keepLocal !== false) {
540
+ if (perPlugin !== 'pack' && options.keepLocal !== false && config.keepLocal !== false) {
469
541
  const captured = captureConfigs(text, [snap], (t) => parseYaml(t)).captured
470
542
  if (captured.size > 0) {
471
543
  actions.push({ plugin: plugin.name, action: 'config', ok: true, message: '本地已有配置,按“保留本地”不覆盖' })
@@ -543,6 +615,31 @@ export async function installPack(input) {
543
615
  }
544
616
  }
545
617
 
618
+ // 分组:按市场分组整体打包的插件,装到同样装了插件市场的机器上时,
619
+ // 并进同名分组(只加成员,不动已有的其它分组与顺序)。
620
+ const groupAdds = new Map()
621
+ for (const plugin of manifest.plugins) {
622
+ if (!plugin.group || plugin.transitiveOf) continue
623
+ if (!groupAdds.has(plugin.group)) groupAdds.set(plugin.group, [])
624
+ groupAdds.get(plugin.group).push(plugin.name)
625
+ }
626
+ if (groupAdds.size > 0 && options.syncGroups !== false) {
627
+ const entriesText = [...groupAdds].map(([name, members]) => name + '(' + members.length + ' 个)').join('、')
628
+ if (!hasMarket(profileDir)) {
629
+ lines.push('这个包按分组打包(' + entriesText + '),但目标 profile 没装插件市场,分组没有写入')
630
+ } else if (options.dryRun) {
631
+ lines.push('演练:将把 ' + entriesText + ' 并进插件市场分组')
632
+ } else {
633
+ const applied = applyMarketGroups(profileDir, Object.fromEntries(groupAdds))
634
+ if (applied.changed) {
635
+ lines.push('已按包内分组并入插件市场:' + applied.summary)
636
+ actions.push({ plugin: '', action: 'group', ok: true, message: '并入市场分组:' + applied.summary })
637
+ } else if (applied.error) {
638
+ lines.push('市场分组没能写入(' + applied.error + ');插件已经装好,分组可以在插件市场里手动加')
639
+ }
640
+ }
641
+ }
642
+
546
643
  const ok = actions.every((a) => a.ok)
547
644
  const record = {
548
645
  at: new Date().toISOString(),
package/lib/manifest.mjs CHANGED
@@ -45,7 +45,11 @@ function normalizePlugin(raw) {
45
45
  isBundle: raw.isBundle !== false,
46
46
  // 谁的内部组件:装父包时会一起装上,安装侧据此跳过,不重复装
47
47
  transitiveOf: typeof raw.transitiveOf === 'string' && /^[@A-Za-z0-9._\/-]{1,160}$/u.test(raw.transitiveOf) ? raw.transitiveOf : '',
48
+ // 打包时按市场分组整体加入的组名(目标机器有插件市场时并进去)
49
+ group: typeof raw.group === 'string' && /^[\p{L}\p{N}_ -]{1,40}$/u.test(raw.group) ? raw.group : '',
48
50
  localEdits: bool(raw.localEdits),
51
+ // 混合包里这个插件的本体是不是连代码一起打进包了(false = 安装时按版本取)
52
+ embedded: bool(raw.embedded),
49
53
  configMode: raw.configMode === 'preset' ? 'preset' : raw.configMode === 'custom' ? 'custom' : (bool(raw.localEdits) || bool(raw.configIncluded) ? 'custom' : 'preset'),
50
54
  // 老包没有 mode 字段,用 localEdits 兜底
51
55
  mode: raw.mode === 'local' ? 'local' : raw.mode === 'base' ? 'base' : bool(raw.localEdits) ? 'local' : 'base',
@@ -91,7 +95,7 @@ export function normalizeManifest(raw) {
91
95
  if (seen.has(p.name)) throw new Error('重复插件:' + p.name)
92
96
  seen.add(p.name)
93
97
  }
94
- const format = raw.format === 'full' ? 'full' : 'lite'
98
+ const format = raw.format === 'full' ? 'full' : raw.format === 'hybrid' ? 'hybrid' : 'lite'
95
99
  return {
96
100
  schema: SCHEMA,
97
101
  kind: KIND,
@@ -110,6 +114,7 @@ export function normalizeManifest(raw) {
110
114
  dshVersion: str(raw.dshVersion, 40),
111
115
  options: {
112
116
  includePayload: format === 'full',
117
+ strategy: format,
113
118
  includeConfig: raw.options ? bool(raw.options.includeConfig) : true,
114
119
  includeLocalEdits: raw.options ? bool(raw.options.includeLocalEdits) : false,
115
120
  keepLocalOnInstall: raw.options ? raw.options.keepLocalOnInstall !== false : true,
@@ -147,14 +152,19 @@ export function buildReadme(manifest, extra = {}) {
147
152
  for (const line of manifest.description.split(/\r?\n/u)) lines.push(line)
148
153
  }
149
154
  lines.push('')
150
- lines.push('格式:' + manifest.format + '(' + (manifest.format === 'full' ? '完整版:包含插件本体,任何工具解压即可读' : '轻量版:只有清单,需要 dsh-modpack 插件联网安装') + ')')
155
+ const formatText = manifest.format === 'full'
156
+ ? '完整包:包含插件本体,不联网也能装(有网时优先按市场版本装,装完照样是市场版)'
157
+ : manifest.format === 'hybrid'
158
+ ? '混合包:能按版本装的插件只记版本(安装时联网取包),没有确定版本或带本机改动的插件连本体一起打进来(这部分不用联网);配置/数据快照照常保留'
159
+ : '仅下载码:只有清单与版本号,安装时联网按版本取包,不带配置'
160
+ lines.push('格式:' + manifest.format + '(' + formatText + ')')
151
161
  lines.push('生成:' + manifest.createdAt + ' 生成器:' + manifest.generator.name + ' ' + manifest.generator.version)
152
162
  if (manifest.author) lines.push('打包者:' + manifest.author)
153
163
  if (manifest.dshVersion) lines.push('打包时 DSH 版本:' + manifest.dshVersion)
154
164
  lines.push('')
155
165
  lines.push('包含的插件(' + manifest.plugins.length + ' 个)')
156
166
  for (const p of manifest.plugins) {
157
- lines.push(' · ' + p.name + '@' + p.version + (p.license ? ' [' + p.license + ']' : ' [未标注 license]') + (p.localEdits ? ' (含打包者的本地修改)' : ''))
167
+ lines.push(' · ' + p.name + '@' + p.version + (p.license ? ' [' + p.license + ']' : ' [未标注 license]') + (p.localEdits ? ' (含打包者的本地修改)' : '') + (manifest.format === 'hybrid' ? (p.embedded ? ' (本体在包里)' : ' (安装时按版本从市场取)') : ''))
158
168
  }
159
169
  lines.push('')
160
170
  lines.push('安全检测')
@@ -163,7 +173,10 @@ export function buildReadme(manifest, extra = {}) {
163
173
  lines.push(' 提醒:静态检测不是杀毒,未命中不代表保证安全;安装前请自行确认来源。')
164
174
  lines.push('')
165
175
  lines.push('怎么装')
166
- if (manifest.format === 'lite') {
176
+ if (manifest.format !== 'full') {
177
+ if (manifest.format === 'hybrid') {
178
+ lines.push(' 带本体的插件直接从包里装(不联网也能装);只记版本的插件会联网按版本取包。')
179
+ }
167
180
  lines.push(' 方式 A(有 dsh-modpack 插件):侧栏「整合包 → 安装」选择本文件,会联网按版本取包并校验完整性。')
168
181
  lines.push(' 方式 B(裸 DSH 也能装):解压后运行 install/ 里的安装器,它会按清单里的名字与版本从 registry 取包:')
169
182
  lines.push(' Windows: install\\install.cmd 其它: sh install/install.sh')
package/lib/net.mjs CHANGED
@@ -66,6 +66,8 @@ function curlOnce(url, { timeoutMs, maxBytes, accept }) {
66
66
  const args = ['-sS', '-i', '--max-time', String(Math.max(1, Math.round(timeoutMs / 1000)))]
67
67
  if (maxBytes > 0) args.push('--max-filesize', String(maxBytes))
68
68
  if (process.platform === 'win32') args.push('--ssl-no-revoke')
69
+ // 传输压缩:npm 的版本清单动辄十几 MB,不压缩会让慢链路直接超时
70
+ args.push('--compressed')
69
71
  args.push('-H', 'user-agent: dsh-modpack', '-H', 'accept: ' + (accept || '*/*'), url)
70
72
  execFile('curl', args, { maxBuffer: Math.max(4 * 1024 * 1024, Math.min(maxBytes + 1024 * 1024, 512 * 1024 * 1024)), windowsHide: true }, (error, stdout, stderr) => {
71
73
  if (error) {
@@ -82,7 +84,7 @@ async function fetchOnce(url, { timeoutMs, maxBytes, accept }) {
82
84
  const res = await fetch(url, {
83
85
  redirect: 'manual',
84
86
  signal: AbortSignal.timeout(timeoutMs),
85
- headers: { 'user-agent': 'dsh-modpack', accept: accept || '*/*' },
87
+ headers: { 'user-agent': 'dsh-modpack', accept: accept || '*/*', 'accept-encoding': 'gzip, deflate, br' },
86
88
  })
87
89
  const headers = new Map()
88
90
  for (const [key, value] of res.headers) headers.set(key.toLowerCase(), value)
@@ -155,7 +157,7 @@ export async function requestBuffer(url, config, options = {}) {
155
157
 
156
158
  /** 取 JSON,体积默认 16 MB。 */
157
159
  export async function requestJson(url, config, options = {}) {
158
- const buf = await requestBuffer(url, config, { ...options, maxBytes: options.maxBytes ?? 16 * 1024 * 1024, accept: 'application/json' })
160
+ const buf = await requestBuffer(url, config, { ...options, maxBytes: options.maxBytes ?? 16 * 1024 * 1024, accept: options.accept ?? 'application/json' })
159
161
  try {
160
162
  return JSON.parse(buf.toString('utf8'))
161
163
  } catch {
package/lib/pack.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * dsh-modpack —— 打包。
3
3
  *
4
- * 两个版本:
5
- * full 完整版:插件本体一起装进 zip,没装 dsh-modpack 的人解压也能按 README 手工装;
6
- * lite 轻量版:只有清单和来源,必须由 dsh-modpack 联网按版本取包。
4
+ * 三种打包策略:
5
+ * full 完整包:插件本体装进 zip,不联网也能装;允许带自定义配置与数据。
6
+ * lite 仅下载码:只有清单与版本号,体积最小;不带配置,装完依赖写成 ^版本(市场认市场版)。
7
+ * hybrid 混合包:只带版本号与配置/数据/补丁片段,不带插件本体;体积接近 lite,配置照样能带。
7
8
  *
8
9
  * 打包顺序是刻意的:先收集 → 先扫描 → 再决定是否允许写盘。扫描在内存里做,
9
10
  * 命中原文不落盘;高风险默认拒绝出包,除非调用方显式 force 并写进报告。
@@ -15,6 +16,7 @@ import { scanEntries, renderScanReport, groupFindings } from './scan.mjs'
15
16
  import { MANIFEST_NAME, SCHEMA, KIND, normalizeManifest, buildReadme, sha256, shortHash } from './manifest.mjs'
16
17
  import { scanFileName } from './scan.mjs'
17
18
  import { slugify } from './store.mjs'
19
+ import { npmMetadata } from './registry.mjs'
18
20
 
19
21
  const STUB_DIR = new URL('../assets/', import.meta.url)
20
22
  const stub = (name) => fs.readFileSync(new URL(name, STUB_DIR))
@@ -311,7 +313,10 @@ export async function buildPack(input) {
311
313
  let scan = null
312
314
  let trustedOnly = false
313
315
  const scanRules = context.extraScanRules || []
314
- const format = options.includePayload === false ? 'lite' : 'full'
316
+ const strategy = options.strategy === 'lite' || options.strategy === 'hybrid'
317
+ ? options.strategy
318
+ : options.includePayload === false ? 'lite' : 'full'
319
+ const format = strategy
315
320
  const progress = typeof options.onProgress === 'function' ? options.onProgress : () => {}
316
321
  const tick = (stage, pct, note) => { try { progress({ stage, pct: Math.max(0, Math.min(100, Math.round(pct))), note }) } catch {} }
317
322
 
@@ -353,16 +358,37 @@ export async function buildPack(input) {
353
358
  ? true
354
359
  : options.includeConfig !== false
355
360
 
361
+ // 混合包按插件分档:能按「名字@版本」装的就只记版本(轻量那部分),
362
+ // 没有确定版本、或要带走本机改动的插件才连代码一起打进包里(完整那部分)。
363
+ // 判断版本号时先看本机已装的那份(profile 源的对象里带 version)。
364
+ const installedForVersion = source === 'profile' && Array.isArray(context.installed)
365
+ ? context.installed.find((p) => p.name === pick.name)
366
+ : null
367
+ const candidateVersion = String((installedForVersion && installedForVersion.version) || pick.version || pick.spec || '')
368
+ const versionOk = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/u.test(candidateVersion) && candidateVersion !== '0.0.0'
369
+ const embedded = format === 'full' || (format === 'hybrid' && (!versionOk || (wantLocal && source === 'profile')))
370
+ if (format === 'hybrid') {
371
+ notes.push(embedded
372
+ ? pick.name + ':没有确定的版本号或要带走本机改动,完整打包(安装时不需要联网)'
373
+ : pick.name + ':只记版本号,安装时联网从市场取包')
374
+ }
375
+ const needPayload = embedded
356
376
  if (source === 'profile') {
357
377
  const installed = context.installed.find((p) => p.name === pick.name)
358
378
  if (!installed) throw new Error('本地找不到插件:' + pick.name)
359
- const loaded = readInstalledPlugin(installed, { maxFileBytes: config?.maxFileBytes, maxTotalBytes: config?.maxPackBytes })
379
+ if (!needPayload) {
380
+ // 只带版本号:读一下 package.json 就够(清单要用 license / peer / engines),不碰几万个文件
381
+ pkg = installed.pkg || null
382
+ payloadDir = installed.dirName || installed.name
383
+ localEdits = false
384
+ }
385
+ const loaded = needPayload ? readInstalledPlugin(installed, { maxFileBytes: config?.maxFileBytes, maxTotalBytes: config?.maxPackBytes }) : { files: [], notes: [], pkg }
360
386
  files = loaded.files
361
387
  pkg = loaded.pkg
362
388
  notes.push(...loaded.notes)
363
389
  payloadDir = installed.dirName || installed.name
364
390
  localEdits = true
365
- if (!wantLocal && typeof pick.download === 'function') {
391
+ if (needPayload && !wantLocal && typeof pick.download === 'function') {
366
392
  // 想打“上游原版”就从 registry 重下,失败则保留本地并标注
367
393
  try {
368
394
  const downloaded = await pick.download(installed.version)
@@ -379,7 +405,21 @@ export async function buildPack(input) {
379
405
  }
380
406
  }
381
407
  } else if (source === 'npm') {
382
- if (typeof pick.download !== 'function') throw new Error('缺少下载器')
408
+ if (!needPayload) {
409
+ const meta = await npmMetadata(pick.name, config, { version: requested })
410
+ const versions = (meta.meta && meta.meta.versions) || {}
411
+ const key = Object.keys(versions)[0] || ''
412
+ pkg = key ? versions[key] : null
413
+ registry = meta.registry || ''
414
+ if (pkg && pkg.dist) {
415
+ tarball = pkg.dist.tarball || ''
416
+ integrity = pkg.dist.integrity || pkg.dist.shasum || ''
417
+ }
418
+ payloadDir = (pkg && pkg.name) || pick.name
419
+ localEdits = false
420
+ if (!pkg) throw new Error('取不到版本信息:' + pick.name)
421
+ } else if (typeof pick.download !== 'function') throw new Error('缺少下载器')
422
+ if (needPayload) {
383
423
  const downloaded = await pick.download(requested)
384
424
  pkg = downloaded.pkg
385
425
  registry = downloaded.registry
@@ -389,6 +429,7 @@ export async function buildPack(input) {
389
429
  payloadDir = dirName
390
430
  files = downloaded.entries.map((e) => ({ name: 'plugins/' + dirName + '/' + e.name, data: e.data }))
391
431
  localEdits = false
432
+ }
392
433
  } else {
393
434
  throw new Error('不支持的来源:' + source)
394
435
  }
@@ -422,6 +463,7 @@ export async function buildPack(input) {
422
463
  hasPatch: Boolean(pkg.dsh && pkg.dsh.bundle && pkg.dsh.bundle.patch),
423
464
  isBundle: Boolean(pkg.dsh && (pkg.dsh.bundle || pkg.dsh.client)),
424
465
  localEdits,
466
+ embedded,
425
467
  mode: localEdits ? 'local' : 'base',
426
468
  configMode: wantConfig ? 'custom' : 'preset',
427
469
  configIncluded: false,
@@ -429,6 +471,8 @@ export async function buildPack(input) {
429
471
  peerDependencies: pkg.peerDependencies && typeof pkg.peerDependencies === 'object' ? pkg.peerDependencies : {},
430
472
  engines: pkg.engines && typeof pkg.engines === 'object' ? pkg.engines : {},
431
473
  dirName,
474
+ // 按市场分组整体加入时记下组名:装到同样有插件市场的机器上会并进同名分组
475
+ group: typeof pick.group === 'string' ? pick.group.trim().slice(0, 40) : '',
432
476
  }
433
477
  manifestPlugins.push(entry)
434
478
  depsOf.set(name, {
@@ -456,7 +500,8 @@ export async function buildPack(input) {
456
500
 
457
501
  // 配置与数据快照
458
502
  capturedFiles = []
459
- if (options.includeConfig !== false && manifestPlugins.some((plugin) => plugin.configMode === 'custom')) {
503
+ const configAllowed = format !== 'lite'
504
+ if (configAllowed && options.includeConfig !== false && manifestPlugins.some((plugin) => plugin.configMode === 'custom')) {
460
505
  const { captured, notes: configNotes } = captureConfigs(context.patchText || '', manifestPlugins, context.parsePatch)
461
506
  notes.push(...configNotes)
462
507
  for (const plugin of manifestPlugins) {
@@ -547,7 +592,8 @@ export async function buildPack(input) {
547
592
  generator: { name: 'dsh-modpack', version: context.pluginVersion || '0.0.0' },
548
593
  dshVersion: context.dshVersion || '',
549
594
  options: {
550
- includePayload: format === 'full',
595
+ includePayload: format === 'full' || payload.length > 0,
596
+ strategy: format,
551
597
  includeConfig: manifestPlugins.some((plugin) => plugin.configMode === 'custom'),
552
598
  includeLocalEdits: manifestPlugins.some((plugin) => plugin.mode === 'local'),
553
599
  keepLocalOnInstall: options.keepLocal !== false,
package/lib/registry.mjs CHANGED
@@ -24,24 +24,101 @@ export function validatePackageName(name) {
24
24
  return name
25
25
  }
26
26
 
27
- /** 依次尝试每个 registry,第一个成功的算。 */
28
- export async function npmMetadata(name, config) {
27
+ /** npm 的「精简清单」:只带依赖与 dist,体积通常比完整清单小得多。 */
28
+ const META_ACCEPT = 'application/vnd.npm.install-v1+json'
29
+ const EXACT_VERSION_RE = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u
30
+
31
+ /**
32
+ * 版本清单的体积上限(字节)。
33
+ * billion-context 这类包的清单曾经十几 MB,固定 16 MB 会让它整个装不上,
34
+ * 所以默认放宽到 64 MB,并且允许在设置里调(maxMetadataBytes,单位 MB)。
35
+ */
36
+ export function metadataLimit(config) {
37
+ const mb = Number(config?.maxMetadataBytes)
38
+ if (Number.isFinite(mb) && mb > 0) return Math.max(4, Math.min(512, Math.floor(mb))) * 1024 * 1024
39
+ return 64 * 1024 * 1024
40
+ }
41
+
42
+ /**
43
+ * 取一个包的版本清单,按「精简 → 完整 → 单版本」三层退让。
44
+ *
45
+ * 为什么不是一条路:vnd.npm.install-v1+json 通常最小,但个别包反而更大;
46
+ * 完整清单有时更小;而只要调用方知道确切版本,/name/1.2.3 这条 REST 永远最小。
47
+ * 三层都失败才算失败,错误信息里带上每层的原因,方便看出是被体积挡住还是网络。
48
+ */
49
+ /**
50
+ * 快速探一下 registry 通不通(npm 的 /-/ping 很轻)。
51
+ * 用来决定「懒人包要不要先按市场版本装」:没网就直接用包里自带的,
52
+ * 免得每个插件都等一遍超时,装个包要好几分钟。
53
+ */
54
+ export async function probeRegistry(config, timeoutMs = 4000) {
55
+ const registries = Array.isArray(config && config.registries) && config.registries.length
56
+ ? config.registries
57
+ : ['https://registry.npmjs.org']
58
+ let last = null
59
+ for (const base of registries.slice(0, 2)) {
60
+ try {
61
+ const url = String(base).replace(/\/+$/u, '') + '/-/ping'
62
+ await requestJson(url, config, { maxBytes: 64 * 1024, timeoutMs, retries: 0 })
63
+ return true
64
+ } catch (error) {
65
+ last = error
66
+ }
67
+ }
68
+ return false
69
+ }
70
+
71
+ export async function npmMetadata(name, config, options = {}) {
29
72
  validatePackageName(name)
30
73
  const registries = Array.isArray(config?.registries) && config.registries.length > 0
31
74
  ? config.registries
32
75
  : ['https://registry.npmjs.org']
76
+ const limit = metadataLimit(config)
77
+ const wanted = typeof options.version === 'string' ? options.version.trim() : ''
78
+ const exact = EXACT_VERSION_RE.test(wanted) ? wanted : ''
33
79
  const errors = []
34
80
  for (const base of registries) {
35
- try {
36
- const url = base.replace(/\/+$/u, '') + '/' + encodeURIComponent(name).replace(/^%40/u, '@')
37
- const meta = await fetchJson(url, config, { accept: 'application/json' })
38
- if (!meta || typeof meta !== 'object' || !meta.versions) throw new Error('元数据缺少 versions')
39
- return { meta, registry: base.replace(/\/+$/u, '') }
40
- } catch (error) {
41
- errors.push(base + ' → ' + String(error?.message || error))
81
+ const root = base.replace(/\/+$/u, '')
82
+ const url = root + '/' + encodeURIComponent(name).replace(/^%40/u, '@')
83
+ const attempts = [
84
+ { label: '精简清单', target: url, accept: META_ACCEPT, maxBytes: limit, full: false },
85
+ { label: '完整清单', target: url, accept: 'application/json', maxBytes: limit, full: true },
86
+ ]
87
+ if (options.full === true) attempts.reverse()
88
+ if (exact) {
89
+ attempts.push({
90
+ label: '单版本清单',
91
+ target: url + '/' + encodeURIComponent(exact),
92
+ accept: 'application/json',
93
+ maxBytes: Math.min(limit, 8 * 1024 * 1024),
94
+ version: exact,
95
+ })
96
+ }
97
+ for (const attempt of attempts) {
98
+ try {
99
+ const doc = await fetchJson(attempt.target, config, { accept: attempt.accept, maxBytes: attempt.maxBytes, timeoutMs: 45000 })
100
+ if (attempt.version) {
101
+ if (!doc || typeof doc !== 'object' || !doc.version) throw new Error('没有版本信息')
102
+ return {
103
+ meta: { 'dist-tags': { latest: doc.version }, versions: { [doc.version]: doc }, time: {} },
104
+ registry: root,
105
+ doc: 'version',
106
+ }
107
+ }
108
+ if (!doc || typeof doc !== 'object' || !doc.versions || Object.keys(doc.versions).length === 0) {
109
+ throw new Error('元数据缺少 versions')
110
+ }
111
+ return { meta: doc, registry: root, doc: attempt.full ? 'full' : 'abbrev' }
112
+ } catch (error) {
113
+ errors.push(root + '(' + attempt.label + ')→ ' + String((error && error.message) || error))
114
+ }
42
115
  }
43
116
  }
44
- throw new Error('registry 都失败了:' + errors.join(';'))
117
+ const oversize = errors.some((line) => /超过上限/u.test(line))
118
+ const hint = oversize
119
+ ? '(版本清单太大:可在设置里把 maxMetadataBytes 调大,或改用确定的版本号,插件会直接取单版本清单)'
120
+ : ''
121
+ throw new Error('registry 都失败了:' + errors.join(';') + hint)
45
122
  }
46
123
 
47
124
  /** 选版本:精确版 > dist-tags.latest > 范围里最高的稳定版。 */
@@ -74,7 +151,7 @@ export function relativeTime(iso) {
74
151
  * @returns {Promise<{name, version, registry, tarball, integrity, sha256, license, repository, pkg, entries, files, unpackedBytes}>}
75
152
  */
76
153
  export async function downloadPackage(name, spec, config) {
77
- const { meta, registry } = await npmMetadata(name, config)
154
+ const { meta, registry } = await npmMetadata(name, config, { version: spec })
78
155
  const version = pickVersion(meta, spec)
79
156
  const manifest = meta.versions[version]
80
157
  if (!manifest || !manifest.dist || !manifest.dist.tarball) throw new Error('版本 ' + version + ' 没有 tarball')
package/lib/store.mjs CHANGED
@@ -61,6 +61,9 @@ export const DEFAULT_CONFIG = {
61
61
  netRetries: 1,
62
62
  curlFallback: true,
63
63
  maxDownloadBytes: 256 * 1024 * 1024,
64
+ // 版本清单(packument)的体积上限,单位 MB。
65
+ // 有的包清单十几 MB(billion-context 曾经超过 16 MB),旧版固定 16 MB 会直接装不上。
66
+ maxMetadataBytes: 64,
64
67
  maxPackBytes: 256 * 1024 * 1024,
65
68
  maxFileBytes: 16 * 1024 * 1024,
66
69
  // 进度窗里「收尾」的记录留多久(秒):0 = 留到 DSH 下次启动(或手动清空);给正数就按秒自动清
@@ -128,6 +131,8 @@ export function clampConfig(raw) {
128
131
  cfg.maxPackBytes = Math.min(4096 * oneMb, Math.max(16 * oneMb, Math.floor(Number(cfg.maxPackBytes) || DEFAULT_CONFIG.maxPackBytes)))
129
132
  cfg.maxFileBytes = Math.min(256 * oneMb, Math.max(1 * oneMb, Math.floor(Number(cfg.maxFileBytes) || DEFAULT_CONFIG.maxFileBytes)))
130
133
  cfg.maxDownloadBytes = Math.min(4096 * oneMb, Math.max(16 * oneMb, Math.floor(Number(cfg.maxDownloadBytes) || DEFAULT_CONFIG.maxDownloadBytes)))
134
+ // 版本清单上限:4~512 MB,默认 64
135
+ cfg.maxMetadataBytes = Math.min(512, Math.max(4, Math.floor(Number(cfg.maxMetadataBytes) || DEFAULT_CONFIG.maxMetadataBytes)))
131
136
  // 进度窗位置不在这里管:它由界面自己拖动并存在浏览器本地,服务端不需要知道
132
137
  // 打包前安全检测是强制的:设置里怎么写都不认,打包一律扫。
133
138
  cfg.scanBeforePack = true
@@ -186,6 +191,20 @@ export function appendHistory(entry, limit = DEFAULT_CONFIG.historyLimit) {
186
191
  return list
187
192
  }
188
193
 
194
+ /** 清空最近记录(文件留着,只是写成空数组)。 */
195
+ export function clearHistory() {
196
+ writeJsonAtomic(pathsFor({}).history, [])
197
+ return []
198
+ }
199
+
200
+ /** 删掉一条最近记录:按 at 时间戳匹配(每条只有这一个稳定标识)。 */
201
+ export function removeHistory(at) {
202
+ const stamp = String(at || '')
203
+ const list = readHistory().filter((item) => String((item && item.at) || '') !== stamp)
204
+ writeJsonAtomic(pathsFor({}).history, list)
205
+ return list
206
+ }
207
+
189
208
  export function appendLog(line) {
190
209
  try {
191
210
  fs.mkdirSync(pluginHome(), { recursive: true })
package/locale/en.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
- "title": "Modpack",
4
- "description": "Provides HMCL/PCL-launcher-style modpack packaging and installation for DeepSeek Harness: bundle several plugins with their configuration and data into one .dshpack and install it in a single pass. Two forms: a self-contained full pack that a machine with only DSH installed can install, and a lite pack that records names and versions and fetches them on install. Each plugin can be packed from its upstream release with default configuration or from a local copy (code, config entries, data snapshot); configuration is re-applied by entry, data is restored under ~/.dsh without overwriting existing files, and suspected credentials become ${REDACTED}. Categories, search, paging and entries come from the plugin-market catalog, and market versions are preferred when online. Packing always runs an in-memory scan for secrets and risky code (masked, never written to disk); high-risk hits pause the job until confirmed, then it resumes from the checkpoint without rescanning. Installation re-checks sha256 integrity, compatibility and licences, and can finish without enabling or enable right away. The UI can live in settings, the sidebar or the plugins tab, each switchable. Installing the plugin market (dshmarket) first is recommended, not required.",
3
+ "title": "Modpack Kit",
4
+ "description": "PCL/HMCL-style modpacks for DeepSeek Harness: bundle plugins with their config and data into one .dshpack and install in one pass. Three strategies: full (installs offline), download-only (smallest), hybrid (per-plugin — only what cannot be fetched by version ships inside). Packing scans in memory and redacts suspected credentials (never written to disk; high-risk findings pause until confirmed); installing re-checks sha256, dependencies and licences. Categories, search, paging and groups share the plugin market, and installed plugins register as market versions. The plugin market is recommended, not required.",
5
5
  "detail": "docs/DETAIL.md"
6
6
  }
7
7
  }
package/locale/zh.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "整合包",
4
- "description": "为 DeepSeek Harness 提供类似 HMCL / PCL 这类我的世界启动器的整合包打包与安装:把多个插件连同各自的配置与数据打成一个 .dshpack 一次装好。支持懒人包(完整包,自带插件本体,目标机器只装 DSH 本体即可安装)与轻量包(只记录插件名与版本,安装时按记录取包);支持按插件逐个定制打包内容(基础配置或本地改动),配置按原结构回填、数据写回 ~/.dsh 且默认不覆盖已有文件,疑似凭据替换为 ${REDACTED};分类、搜索、分页与条目与插件市场目录同源,联网时可优先按市场版本安装。打包前强制做敏感信息与风险代码静态检测(命中只留掩码、原文不落盘),高风险停在「等决定」,确认后从检测点续跑、不重复扫描;安装前校验 sha256 完整性、兼容性与许可证,装完可选先不启用或直接启用;设置页、侧边栏、插件页三处入口各自独立开关。建议先安装插件市场(dshmarket),但不是必须。",
4
+ "description": "类似 HMCL / PCL 的 DSH 整合包工具:把多个插件连同配置与数据打成一个 .dshpack,换台机器一次装好。三种策略——完整包(不联网也能装)、仅下载码(体积最小)、混合包(按插件分档,只把离不开本体的那几个打全)。打包前在内存里强制做安全扫描并擦除疑似凭据(原文不落盘,高危先停下等确认),安装前校验 sha256、依赖与许可证;分类、搜索、分页与分组和插件市场同源,装完按市场版登记。建议先装插件市场(dshmarket),不是必须。",
5
5
  "detail": "docs/DETAIL.md"
6
6
  }
7
7
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-modpack-kit",
3
- "version": "0.1.8",
4
- "description": "Provides HMCL/PCL-launcher-style modpack packaging and installation for DeepSeek Harness: bundle several plugins with their configuration and data into one .dshpack and install it in a single pass. Two forms: a self-contained full pack that a machine with only DSH installed can install, and a lite pack that records names and versions and fetches them on install. Each plugin can be packed from its upstream release with default configuration or from a local copy (code, config entries, data snapshot); configuration is re-applied by entry, data is restored under ~/.dsh without overwriting existing files, and suspected credentials become ${REDACTED}. Categories, search, paging and entries come from the plugin-market catalog, and market versions are preferred when online. Packing always runs an in-memory scan for secrets and risky code (masked, never written to disk); high-risk hits pause the job until confirmed, then it resumes from the checkpoint without rescanning. Installation re-checks sha256 integrity, compatibility and licences, and can finish without enabling or enable right away. The UI can live in settings, the sidebar or the plugins tab, each switchable. Installing the plugin market (dshmarket) first is recommended, not required.",
3
+ "version": "0.2.0",
4
+ "description": "PCL/HMCL-style modpacks for DeepSeek Harness: bundle plugins with their config and data into one .dshpack and install in one pass. Three strategies: full (installs offline), download-only (smallest), hybrid (per-plugin — only what cannot be fetched by version ships inside). Packing scans in memory and redacts suspected credentials (never written to disk; high-risk findings pause until confirmed); installing re-checks sha256, dependencies and licences. Categories, search, paging and groups share the plugin market, and installed plugins register as market versions. The plugin market is recommended, not required.",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "exports": {