dsh-modpack-kit 0.0.0-stage → 0.1.1

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/pack.mjs ADDED
@@ -0,0 +1,382 @@
1
+ /**
2
+ * dsh-modpack —— 打包。
3
+ *
4
+ * 两个版本:
5
+ * full 完整版:插件本体一起装进 zip,没装 dsh-modpack 的人解压也能按 README 手工装;
6
+ * lite 轻量版:只有清单和来源,必须由 dsh-modpack 联网按版本取包。
7
+ *
8
+ * 打包顺序是刻意的:先收集 → 先扫描 → 再决定是否允许写盘。扫描在内存里做,
9
+ * 命中原文不落盘;高风险默认拒绝出包,除非调用方显式 force 并写进报告。
10
+ */
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+ import { writeZip } from './zip.mjs'
14
+ import { scanEntries, renderScanReport } from './scan.mjs'
15
+ import { MANIFEST_NAME, SCHEMA, KIND, normalizeManifest, buildReadme, sha256, shortHash } from './manifest.mjs'
16
+ import { scanFileName } from './scan.mjs'
17
+ import { slugify } from './store.mjs'
18
+
19
+ const SKIP_DIRS = new Set(['node_modules', '.git', '.svn', '__pycache__', '.cache', '.turbo', '.next', 'coverage'])
20
+ const SKIP_FILES = new Set(['.DS_Store', 'Thumbs.db', 'desktop.ini'])
21
+ const DATA_EXT = new Set(['.json', '.md', '.txt', '.yml', '.yaml', '.csv', '.toml', '.ini'])
22
+
23
+ export class PackRefused extends Error {
24
+ constructor(message, scan) {
25
+ super(message)
26
+ this.name = 'PackRefused'
27
+ this.scan = scan
28
+ }
29
+ }
30
+
31
+ /** 递归收集目录里的普通文件;符号链接一律跳过(不跟随、不打包)。 */
32
+ export function collectFiles(root, options = {}) {
33
+ const maxFileBytes = options.maxFileBytes ?? 16 * 1024 * 1024
34
+ const maxTotalBytes = options.maxTotalBytes ?? 256 * 1024 * 1024
35
+ const prefix = options.prefix ?? ''
36
+ const out = []
37
+ const notes = []
38
+ let total = 0
39
+
40
+ const walk = (dir, rel) => {
41
+ let dirents
42
+ try {
43
+ dirents = fs.readdirSync(dir, { withFileTypes: true })
44
+ } catch (error) {
45
+ notes.push('读不到目录 ' + rel + ':' + String(error?.message || error))
46
+ return
47
+ }
48
+ for (const dirent of dirents) {
49
+ const abs = path.join(dir, dirent.name)
50
+ const relPath = rel ? rel + '/' + dirent.name : dirent.name
51
+ if (dirent.isSymbolicLink()) { notes.push('跳过符号链接 ' + prefix + relPath); continue }
52
+ if (dirent.isDirectory()) {
53
+ if (SKIP_DIRS.has(dirent.name)) continue
54
+ walk(abs, relPath)
55
+ continue
56
+ }
57
+ if (!dirent.isFile()) continue
58
+ if (SKIP_FILES.has(dirent.name)) continue
59
+ let stat
60
+ try { stat = fs.statSync(abs) } catch { continue }
61
+ if (stat.size > maxFileBytes) { notes.push('跳过超大文件 ' + prefix + relPath + '(' + stat.size + ' 字节)'); continue }
62
+ total += stat.size
63
+ if (total > maxTotalBytes) throw new Error('内容超过打包上限(' + maxTotalBytes + ' 字节),请减少插件')
64
+ let data
65
+ try { data = fs.readFileSync(abs) } catch (error) { notes.push('读不到 ' + prefix + relPath + ':' + String(error?.message || error)); continue }
66
+ out.push({ name: prefix + relPath, data, mtime: stat.mtime })
67
+ }
68
+ }
69
+ walk(root, '')
70
+ return { files: out, notes }
71
+ }
72
+
73
+ /** 从 profile 读一个已装插件。 */
74
+ export function readInstalledPlugin(installed, options = {}) {
75
+ const { files, notes } = collectFiles(installed.dir, {
76
+ prefix: 'plugins/' + installed.dirName + '/',
77
+ maxFileBytes: options.maxFileBytes,
78
+ maxTotalBytes: options.maxTotalBytes,
79
+ })
80
+ return { files, notes, pkg: installed.pkg }
81
+ }
82
+
83
+ /**
84
+ * 抓 profile 补丁层里的配置(每个插件一条)。
85
+ * 解析失败就整体放弃自动抓取,只留一句 note——宁可少带,也不带错。
86
+ */
87
+ export function captureConfigs(patchText, plugins, parsePatch) {
88
+ const captured = new Map()
89
+ const notes = []
90
+ let items = []
91
+ try {
92
+ items = parsePatch(patchText)
93
+ } catch (error) {
94
+ notes.push('配置层解析失败,未抓取任何配置:' + String(error?.message || error))
95
+ return { captured, notes }
96
+ }
97
+ if (!Array.isArray(items)) return { captured, notes }
98
+ const byName = new Map(plugins.map((p) => [p.name, p]))
99
+ for (const item of items) {
100
+ if (!item || typeof item !== 'object') continue
101
+ const name = typeof item.name === 'string' ? item.name : ''
102
+ const id = typeof item.id === 'string' ? item.id : ''
103
+ const hit = byName.get(name) || byName.get(id)
104
+ if (!hit) continue
105
+ captured.set(hit.name, { id: item.id, name: item.name, disabled: item.disabled === true ? true : undefined, config: item.config ?? null })
106
+ }
107
+ return { captured, notes }
108
+ }
109
+
110
+ function dataDirsFor(name) {
111
+ const home = process.env.DSH_HOME || path.join(process.env.USERPROFILE || '', '.dsh')
112
+ const candidates = [name, name.replace(/^dsh-/u, '')].filter(Boolean)
113
+ const out = []
114
+ for (const candidate of candidates) {
115
+ const dir = path.join(home, candidate)
116
+ try {
117
+ if (fs.statSync(dir).isDirectory()) out.push({ dir, prefix: 'data/' + name + '/' })
118
+ } catch {}
119
+ }
120
+ return out
121
+ }
122
+
123
+ /** 插件数据快照:只收小体积文本类,凭证类文件名直接跳过。 */
124
+ export function captureData(name, options = {}) {
125
+ const files = []
126
+ const notes = []
127
+ let total = 0
128
+ const limit = options.maxBytes ?? 8 * 1024 * 1024
129
+ for (const { dir, prefix } of dataDirsFor(name)) {
130
+ const entries = []
131
+ const walk = (d, rel) => {
132
+ let dirents
133
+ try { dirents = fs.readdirSync(d, { withFileTypes: true }) } catch { return }
134
+ for (const dirent of dirents) {
135
+ if (dirent.isSymbolicLink()) continue
136
+ const abs = path.join(d, dirent.name)
137
+ const relPath = rel ? rel + '/' + dirent.name : dirent.name
138
+ if (dirent.isDirectory()) { if (!SKIP_DIRS.has(dirent.name)) walk(abs, relPath); continue }
139
+ if (!dirent.isFile()) continue
140
+ const ext = path.extname(dirent.name).toLowerCase()
141
+ if (!DATA_EXT.has(ext)) continue
142
+ if (scanFileName(prefix + relPath).some((f) => f.severity === 'high')) { notes.push('跳过疑似凭证文件 ' + prefix + relPath); continue }
143
+ let stat
144
+ try { stat = fs.statSync(abs) } catch { continue }
145
+ if (stat.size > 1024 * 1024) continue
146
+ total += stat.size
147
+ if (total > limit) { notes.push('数据快照超过上限,后面的没带'); return }
148
+ entries.push({ abs, name: prefix + relPath, size: stat.size })
149
+ }
150
+ }
151
+ walk(dir, '')
152
+ for (const entry of entries) {
153
+ try { files.push({ name: entry.name, data: fs.readFileSync(entry.abs), mtime: new Date() }) } catch {}
154
+ }
155
+ }
156
+ return { files, notes }
157
+ }
158
+
159
+ function licenseId(pkg) {
160
+ if (typeof pkg.license === 'string') return pkg.license
161
+ if (pkg.license && typeof pkg.license.type === 'string') return pkg.license.type
162
+ if (Array.isArray(pkg.licenses) && pkg.licenses[0]) return String(pkg.licenses[0].type || '')
163
+ return ''
164
+ }
165
+
166
+ function authorOf(pkg) {
167
+ if (typeof pkg.author === 'string') return pkg.author
168
+ if (pkg.author && typeof pkg.author.name === 'string') return pkg.author.name
169
+ return ''
170
+ }
171
+
172
+ /**
173
+ * 生成整合包。
174
+ * @param {object} input
175
+ * @param {{name: string, source: 'profile'|'npm'|'url', spec?: string, download?: Function}[]} input.selection
176
+ * @param {object} input.options {includePayload, includeConfig, includeLocalEdits, blockHighRisk, force, confirmLicense}
177
+ * @param {object} input.context {config, profileDir, dshVersion, installed, pluginVersion, extraScanRules, parsePatch}
178
+ */
179
+ export async function buildPack(input) {
180
+ const { selection, options, context } = input
181
+ const config = context.config
182
+ const plugins = []
183
+ const payload = []
184
+ const notes = []
185
+ const manifestPlugins = []
186
+ const scanRules = context.extraScanRules || []
187
+ const format = options.includePayload === false ? 'lite' : 'full'
188
+
189
+ for (const pick of selection) {
190
+ if (!pick || typeof pick.name !== 'string') continue
191
+ let files = []
192
+ let pkg = null
193
+ let source = pick.source
194
+ let registry = ''
195
+ let tarball = ''
196
+ let integrity = ''
197
+ let requested = pick.spec || ''
198
+ let localEdits = false
199
+ let payloadDir = ''
200
+ // 每个插件可以单独选:base = 上游原版 + 插件基础配置;local = 连本机改动一起打
201
+ const wantLocal = pick.mode === 'local' ? true : pick.mode === 'base' ? false : options.includeLocalEdits === true
202
+
203
+ if (source === 'profile') {
204
+ const installed = context.installed.find((p) => p.name === pick.name)
205
+ if (!installed) throw new Error('本地找不到插件:' + pick.name)
206
+ const loaded = readInstalledPlugin(installed, { maxFileBytes: config?.maxFileBytes, maxTotalBytes: config?.maxPackBytes })
207
+ files = loaded.files
208
+ pkg = loaded.pkg
209
+ notes.push(...loaded.notes)
210
+ payloadDir = installed.dirName || installed.name
211
+ localEdits = true
212
+ if (!wantLocal && typeof pick.download === 'function') {
213
+ // 想打“上游原版”就从 registry 重下,失败则保留本地并标注
214
+ try {
215
+ const downloaded = await pick.download(installed.version)
216
+ files = downloaded.entries
217
+ .filter((e) => !SKIP_DIRS.has(e.name.split('/')[0]))
218
+ .map((e) => ({ name: 'plugins/' + installed.dirName + '/' + e.name, data: e.data }))
219
+ pkg = downloaded.pkg
220
+ registry = downloaded.registry
221
+ tarball = downloaded.tarball
222
+ integrity = downloaded.integrity
223
+ localEdits = false
224
+ } catch (error) {
225
+ notes.push(pick.name + ':取上游原版失败,改打本地文件(' + String(error?.message || error) + ')')
226
+ }
227
+ }
228
+ } else if (source === 'npm') {
229
+ if (typeof pick.download !== 'function') throw new Error('缺少下载器')
230
+ const downloaded = await pick.download(requested)
231
+ pkg = downloaded.pkg
232
+ registry = downloaded.registry
233
+ tarball = downloaded.tarball
234
+ integrity = downloaded.integrity
235
+ const dirName = pkg.name
236
+ payloadDir = dirName
237
+ files = downloaded.entries.map((e) => ({ name: 'plugins/' + dirName + '/' + e.name, data: e.data }))
238
+ localEdits = false
239
+ } else {
240
+ throw new Error('不支持的来源:' + source)
241
+ }
242
+
243
+ const name = (pkg && pkg.name) || pick.name
244
+ const dirName = payloadDir || name
245
+ if (!pkg || typeof pkg !== 'object') throw new Error('插件缺少 package.json:' + name)
246
+ const license = licenseId(pkg)
247
+ const allow = new Set((config?.licenseAllow || []).map((x) => String(x).toLowerCase()))
248
+ let licenseState = 'ok'
249
+ if (!license || /^unlicensed$/iu.test(license)) licenseState = 'missing'
250
+ else if (!allow.has(license.toLowerCase())) licenseState = 'unlisted'
251
+ if (licenseState !== 'ok' && !options.confirmLicense) {
252
+ throw new Error(pick.name + ':license 为「' + (license || '未标注') + '」,不在允许列表。确认你有权再分发后再打包(需要显式勾选)。')
253
+ }
254
+
255
+ const entry = {
256
+ name,
257
+ version: typeof pkg.version === 'string' ? pkg.version : '0.0.0',
258
+ requested,
259
+ source,
260
+ registry,
261
+ tarball,
262
+ integrity,
263
+ license,
264
+ repository: typeof pkg.repository === 'string' ? pkg.repository : (pkg.repository && pkg.repository.url) || '',
265
+ author: authorOf(pkg),
266
+ files: files.length,
267
+ size: files.reduce((sum, f) => sum + f.data.length, 0),
268
+ hasClient: Boolean(pkg.dsh && pkg.dsh.client) || Boolean(pkg.exports && (pkg.exports['./client'] || pkg.exports['./client.js'])),
269
+ hasPatch: Boolean(pkg.dsh && pkg.dsh.bundle && pkg.dsh.bundle.patch),
270
+ isBundle: Boolean(pkg.dsh && (pkg.dsh.bundle || pkg.dsh.client)),
271
+ localEdits,
272
+ mode: localEdits ? 'local' : 'base',
273
+ configIncluded: false,
274
+ dataIncluded: false,
275
+ peerDependencies: pkg.peerDependencies && typeof pkg.peerDependencies === 'object' ? pkg.peerDependencies : {},
276
+ engines: pkg.engines && typeof pkg.engines === 'object' ? pkg.engines : {},
277
+ dirName,
278
+ }
279
+ manifestPlugins.push(entry)
280
+ payload.push(...files.map((f) => ({ ...f, plugin: name })))
281
+ }
282
+
283
+ // 配置与数据快照
284
+ const capturedFiles = []
285
+ if (options.includeConfig) {
286
+ const { captured, notes: configNotes } = captureConfigs(context.patchText || '', manifestPlugins, context.parsePatch)
287
+ notes.push(...configNotes)
288
+ for (const plugin of manifestPlugins) {
289
+ // 选了「基础配置」就没有本地改动可打
290
+ if (plugin.mode === 'base') continue
291
+ const snap = captured.get(plugin.name)
292
+ if (snap && (snap.config !== null || snap.disabled !== undefined)) {
293
+ const body = JSON.stringify({ id: snap.id, name: snap.name, disabled: snap.disabled, config: snap.config, capturedAt: new Date().toISOString() }, null, 2)
294
+ capturedFiles.push({ name: 'configs/' + plugin.name + '.json', data: Buffer.from(body, 'utf8') })
295
+ plugin.configIncluded = true
296
+ plugin.config = snap.config
297
+ if (snap.disabled) plugin.note = '打包时该插件被禁用'
298
+ }
299
+ const data = captureData(plugin.name, { maxBytes: 8 * 1024 * 1024 })
300
+ if (data.files.length > 0) {
301
+ capturedFiles.push(...data.files)
302
+ plugin.dataIncluded = true
303
+ notes.push(...data.notes)
304
+ }
305
+ }
306
+ }
307
+
308
+ // 先扫描,再决定要不要写盘。扫描是强制的:没有「关掉扫描」这条路,
309
+ // 只有高风险默认阻断、显式 force 才继续(决定会写进清单 security.approvedRisk)。
310
+ const scanTargets = [...payload, ...capturedFiles]
311
+ const scan = scanEntries(scanTargets.map((f) => ({ name: f.name, data: f.data })), { extraRules: scanRules })
312
+
313
+ if (config?.blockHighRisk !== false && scan.counts.high > 0 && !options.force) {
314
+ throw new PackRefused('安全检测发现 ' + scan.counts.high + ' 个高风险项,已停止打包', scan)
315
+ }
316
+
317
+ const manifestBase = {
318
+ schema: SCHEMA,
319
+ kind: KIND,
320
+ format,
321
+ id: 'mp_' + Date.now().toString(36) + '_' + shortHash(Buffer.from(String(Math.random()))),
322
+ name: options.name || 'DSH 整合包',
323
+ description: options.description || '',
324
+ author: options.author || '',
325
+ license: options.license || '',
326
+ homepage: options.homepage || '',
327
+ createdAt: new Date().toISOString(),
328
+ generator: { name: 'dsh-modpack', version: context.pluginVersion || '0.0.0' },
329
+ dshVersion: context.dshVersion || '',
330
+ options: {
331
+ includePayload: format === 'full',
332
+ includeConfig: Boolean(options.includeConfig),
333
+ includeLocalEdits: Boolean(options.includeLocalEdits),
334
+ keepLocalOnInstall: options.keepLocal !== false,
335
+ },
336
+ plugins: manifestPlugins,
337
+ files: [...payload, ...capturedFiles].map((f) => ({ path: f.name, sha256: sha256(f.data), size: f.data.length })),
338
+ security: {
339
+ scanned: true,
340
+ high: scan.counts.high,
341
+ medium: scan.counts.medium,
342
+ low: scan.counts.low,
343
+ approvedRisk: scan.counts.high > 0,
344
+ note: scan.note,
345
+ },
346
+ install: {
347
+ restartRequired: true,
348
+ notes: notes.slice(0, 30),
349
+ },
350
+ extensions: options.extensions || {},
351
+ }
352
+
353
+ const manifest = normalizeManifest(manifestBase)
354
+ const manifestText = JSON.stringify(manifest, null, 2)
355
+ const manifestBuf = Buffer.from(manifestText, 'utf8')
356
+
357
+ const report = renderScanReport(manifest.name, scan, { approvedRisk: manifest.security.approvedRisk })
358
+ const readme = buildReadme(manifest)
359
+
360
+ const entries = [
361
+ { name: MANIFEST_NAME, data: manifestBuf },
362
+ { name: 'README.txt', data: Buffer.from(readme, 'utf8') },
363
+ { name: 'security/report.txt', data: Buffer.from(report, 'utf8') },
364
+ ...(options.includePayload === false ? [] : payload),
365
+ ...capturedFiles,
366
+ ]
367
+
368
+ const integrity = {
369
+ generatedAt: new Date().toISOString(),
370
+ algorithm: 'sha256',
371
+ files: Object.fromEntries(entries.map((e) => [e.name, sha256(e.data)])),
372
+ }
373
+ entries.push({ name: 'integrity.json', data: Buffer.from(JSON.stringify(integrity, null, 2), 'utf8') })
374
+
375
+ const buffer = writeZip(entries)
376
+ if (config?.maxPackBytes && buffer.length > config.maxPackBytes) {
377
+ throw new Error('整合包体积 ' + buffer.length + ' 字节,超过上限 ' + config.maxPackBytes)
378
+ }
379
+ const stamp = new Date().toISOString().slice(0, 10)
380
+ const fileName = slugify(manifest.name) + '-' + stamp + '-' + format + '.dshpack'
381
+ return { buffer, fileName, manifest, scan, report, notes, size: buffer.length }
382
+ }
@@ -0,0 +1,274 @@
1
+ /**
2
+ * dsh-modpack —— 只读 + 受控写入 DSH profile。
3
+ *
4
+ * 读:profile/package.json、bundles 列表、node_modules 里已装插件、DSH 版本。
5
+ * 写:只有三处,且每处先备份——
6
+ * 1. package.json 的 `dsh.profile.bundles`(让 DSH 下次启动加载整合包里的插件);
7
+ * 2. cordis.patch.yml 里按 id 覆盖单条配置(只改那一条,其他字节不动);
8
+ * 3. 调用官方 CLI `dsh plugin --profile <p> add …` 装包(和插件市场同一条路径)。
9
+ */
10
+ import fs from 'node:fs'
11
+ import path from 'node:path'
12
+ import { spawn } from 'node:child_process'
13
+ import { writeJsonAtomic, appendLog } from './store.mjs'
14
+
15
+ export function readJson(file, fallback = null) {
16
+ try {
17
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
18
+ } catch {
19
+ return fallback
20
+ }
21
+ }
22
+
23
+ export function readProfilePackage(profileDir) {
24
+ return readJson(path.join(profileDir, 'package.json'), null)
25
+ }
26
+
27
+ export function listInstalled(profileDir) {
28
+ const modulesDir = path.join(profileDir, 'node_modules')
29
+ const out = []
30
+ let dirents
31
+ try {
32
+ dirents = fs.readdirSync(modulesDir, { withFileTypes: true })
33
+ } catch {
34
+ return out
35
+ }
36
+ const push = (dir, namePrefix) => {
37
+ const name = namePrefix ? namePrefix + '/' + dir : dir
38
+ const dirPath = path.join(modulesDir, name)
39
+ const pkg = readJson(path.join(dirPath, 'package.json'), null)
40
+ if (!pkg || typeof pkg !== 'object') return
41
+ let real = dirPath
42
+ try { real = fs.realpathSync(dirPath) } catch {}
43
+ let size = 0
44
+ try {
45
+ const stat = fs.statSync(real)
46
+ size = stat.isDirectory() ? 0 : stat.size
47
+ } catch {}
48
+ out.push({
49
+ name: typeof pkg.name === 'string' ? pkg.name : name,
50
+ dirName: name,
51
+ version: typeof pkg.version === 'string' ? pkg.version : '0.0.0',
52
+ dir: dirPath,
53
+ realDir: real,
54
+ pkg,
55
+ isBundle: Boolean(pkg.dsh && (pkg.dsh.bundle || pkg.dsh.client)),
56
+ hasClient: Boolean(pkg.dsh && pkg.dsh.client) || Boolean(pkg.exports && (pkg.exports['./client'] || pkg.exports['./client.js'])),
57
+ hasPatch: Boolean(pkg.dsh && pkg.dsh.bundle && pkg.dsh.bundle.patch),
58
+ // 是不是"给 DSH 用的插件",而不是某个插件的传递依赖
59
+ description: typeof pkg.description === 'string' ? pkg.description.slice(0, 300) : '',
60
+ isPlugin: Boolean(
61
+ pkg.dsh
62
+ || (Array.isArray(pkg.keywords) && pkg.keywords.includes('dsh-plugin'))
63
+ || /^(?:@[^/]+\/)?dsh[-.]/u.test(name),
64
+ ),
65
+ size,
66
+ })
67
+ }
68
+ for (const dirent of dirents) {
69
+ if (!dirent.isDirectory() && !dirent.isSymbolicLink()) continue
70
+ if (dirent.name.startsWith('.')) continue
71
+ if (dirent.name.startsWith('@')) {
72
+ let scoped = []
73
+ try { scoped = fs.readdirSync(path.join(modulesDir, dirent.name), { withFileTypes: true }) } catch {}
74
+ for (const sub of scoped) {
75
+ if (sub.isDirectory() || sub.isSymbolicLink()) push(sub.name, dirent.name)
76
+ }
77
+ continue
78
+ }
79
+ push(dirent.name, '')
80
+ }
81
+ out.sort((a, b) => (a.isBundle === b.isBundle ? a.name.localeCompare(b.name) : a.isBundle ? -1 : 1))
82
+ return out
83
+ }
84
+
85
+ export function dshVersion(profileDir) {
86
+ for (const name of ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app']) {
87
+ const pkg = readJson(path.join(profileDir, 'node_modules', name, 'package.json'), null)
88
+ if (pkg && typeof pkg.version === 'string') return pkg.version
89
+ }
90
+ return ''
91
+ }
92
+
93
+ export function readBundles(profilePkg) {
94
+ const list = profilePkg && profilePkg.dsh && profilePkg.dsh.profile && profilePkg.dsh.profile.bundles
95
+ return Array.isArray(list) ? list.filter((x) => typeof x === 'string') : []
96
+ }
97
+
98
+ function backup(file) {
99
+ if (!fs.existsSync(file)) return ''
100
+ const stamp = new Date().toISOString().replace(/[:.]/gu, '-')
101
+ const target = file + '.bak-modpack-' + stamp
102
+ fs.copyFileSync(file, target)
103
+ return target
104
+ }
105
+
106
+ /** 把名字补进 bundles 列表;已存在就什么都不做。返回 {changed, backup, added}。 */
107
+ export function ensureBundles(profileDir, names) {
108
+ const file = path.join(profileDir, 'package.json')
109
+ const pkg = readProfilePackage(profileDir)
110
+ if (!pkg) throw new Error('profile/package.json 读不到:' + file)
111
+ if (!pkg.dsh) pkg.dsh = {}
112
+ if (!pkg.dsh.profile) pkg.dsh.profile = {}
113
+ if (!Array.isArray(pkg.dsh.profile.bundles)) pkg.dsh.profile.bundles = []
114
+ const added = []
115
+ for (const name of names) {
116
+ if (!name || typeof name !== 'string') continue
117
+ if (!pkg.dsh.profile.bundles.includes(name)) {
118
+ pkg.dsh.profile.bundles.push(name)
119
+ added.push(name)
120
+ }
121
+ }
122
+ if (added.length === 0) return { changed: false, backup: '', added }
123
+ const bak = backup(file)
124
+ writeJsonAtomic(file, pkg)
125
+ return { changed: true, backup: bak, added }
126
+ }
127
+
128
+ /** 把 bundles 精确恢复成给定列表(CLI 自己也会登记,装好先不启用时用它撤回)。返回是否改过。 */
129
+ export function setBundles(profileDir, names) {
130
+ const file = path.join(profileDir, 'package.json')
131
+ const pkg = readProfilePackage(profileDir)
132
+ if (!pkg) throw new Error('profile/package.json 读不到:' + file)
133
+ const want = names.filter((x) => typeof x === 'string')
134
+ const now = readBundles(pkg)
135
+ if (now.length === want.length && now.every((x, i) => x === want[i])) return false
136
+ if (!pkg.dsh) pkg.dsh = {}
137
+ if (!pkg.dsh.profile) pkg.dsh.profile = {}
138
+ pkg.dsh.profile.bundles = want
139
+ backup(file)
140
+ writeJsonAtomic(file, pkg)
141
+ return true
142
+ }
143
+
144
+ export function patchPath(profileDir) {
145
+ return path.join(profileDir, 'cordis.patch.yml')
146
+ }
147
+
148
+ export function readPatch(profileDir) {
149
+ try {
150
+ return fs.readFileSync(patchPath(profileDir), 'utf8')
151
+ } catch {
152
+ return ''
153
+ }
154
+ }
155
+
156
+ /** 原子写补丁文件,返回备份路径。 */
157
+ export function writePatch(profileDir, text) {
158
+ const file = patchPath(profileDir)
159
+ const bak = backup(file)
160
+ const tmp = file + '.' + Date.now() + '.tmp'
161
+ fs.writeFileSync(tmp, text, 'utf8')
162
+ fs.renameSync(tmp, file)
163
+ return bak
164
+ }
165
+
166
+ function cliPath() {
167
+ if (process.env.DSH_CLI) return process.env.DSH_CLI
168
+ const root = path.dirname(process.execPath)
169
+ return path.join(root, 'resources', 'runtime', 'cli', 'bin', 'dsh.cmd')
170
+ }
171
+
172
+ /** 宿主自带的 CLI 入口(app.asar 里的 cli.js);有它就不用走 .cmd,省掉 cmd 的引号与编码问题。 */
173
+ function cliEntry() {
174
+ const roots = []
175
+ if (process.resourcesPath) roots.push(process.resourcesPath)
176
+ try { roots.push(path.join(path.dirname(process.execPath), 'resources')) } catch {}
177
+ for (const root of roots) {
178
+ if (!root) continue
179
+ const js = path.join(root, 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'lib', 'cli.js')
180
+ try { if (fs.existsSync(js)) return js } catch {}
181
+ }
182
+ return ''
183
+ }
184
+
185
+ function quoteArg(arg) {
186
+ if (/[&|<>^%!"\r\n\u0000-\u001f]/u.test(arg)) throw new Error('安装参数含不允许的字符:' + arg)
187
+ return /\s/u.test(arg) ? '"' + arg + '"' : arg
188
+ }
189
+
190
+ /** argv 直传时只挡控制字符与双引号;中文用户名、`Program Files (x86)` 这类路径照常放行。 */
191
+ function safeArg(arg) {
192
+ return typeof arg === 'string' && arg.length > 0 && arg.length < 4096 && !/[\u0000-\u001f"]/u.test(arg)
193
+ }
194
+
195
+ /** 允许调用方连 `plugin --profile x` 一起传(install.mjs 就是那么传的),这里统一剥成纯 pnpm 参数。 */
196
+ function normalizePluginArgs(args) {
197
+ const list = []
198
+ for (let i = 0; i < args.length; i += 1) {
199
+ const arg = args[i]
200
+ if (arg === 'plugin') continue
201
+ if (arg === '--profile') { i += 1; continue }
202
+ list.push(arg)
203
+ }
204
+ return list
205
+ }
206
+
207
+ /** Windows 下的 CLI 输出是 GBK,直接按 UTF-8 解会把中文变乱码;乱码率过高时换 GBK 再解。 */
208
+ function decodeOutput(buffer) {
209
+ const utf8 = buffer.toString('utf8')
210
+ if (!utf8.includes('\uFFFD')) return utf8
211
+ try {
212
+ const gbk = new TextDecoder('gbk', { fatal: false }).decode(buffer)
213
+ return gbk.includes('\uFFFD') ? utf8 : gbk
214
+ } catch { return utf8 }
215
+ }
216
+
217
+ /**
218
+ * 调官方 CLI(内部就是 pnpm),和插件市场安装走同一条路。
219
+ * 优先直接起 exe + cli.js:参数不经 cmd,引号与中文编码都不会被吞;找不到才退回 .cmd。
220
+ * @returns {Promise<{code: number, output: string}>}
221
+ */
222
+ export function runDshPlugin(profile, args, options = {}) {
223
+ return new Promise((resolve, reject) => {
224
+ if (!/^[A-Za-z0-9_-]{1,64}$/u.test(profile)) { reject(new Error('profile 名不合法')); return }
225
+ for (const arg of args) if (!safeArg(arg)) { reject(new Error('参数含不允许的字符:' + arg)); return }
226
+ const pluginArgs = normalizePluginArgs(args)
227
+ const entry = cliEntry()
228
+ const env = { ...process.env, CI: '1' }
229
+ let child
230
+ if (entry) {
231
+ env.ELECTRON_RUN_AS_NODE = '1'
232
+ child = spawn(process.execPath, ['--expose-internals', entry, 'plugin', '--profile', profile, ...pluginArgs], {
233
+ cwd: options.cwd,
234
+ windowsHide: true,
235
+ env,
236
+ })
237
+ } else {
238
+ const cli = cliPath()
239
+ if (!fs.existsSync(cli)) { reject(new Error('找不到 DSH CLI:' + cli)); return }
240
+ const comspec = process.env.ComSpec || 'C:\\Windows\\System32\\cmd.exe'
241
+ // cmd 回退:整串用一对引号包住,/s 只会剥掉最外层那一对,里面的 "cli" 才守得住
242
+ const command = '""' + cli + '" plugin --profile ' + profile + ' ' + pluginArgs.map(quoteArg).join(' ') + '"'
243
+ child = spawn(comspec, ['/d', '/s', '/c', command], {
244
+ cwd: options.cwd,
245
+ windowsHide: true,
246
+ env,
247
+ windowsVerbatimArguments: true,
248
+ })
249
+ }
250
+ let buffer = Buffer.alloc(0)
251
+ let output = ''
252
+ const append = (chunk) => {
253
+ buffer = Buffer.concat([buffer, chunk])
254
+ if (buffer.length > 400000) buffer = buffer.subarray(buffer.length - 400000)
255
+ output = decodeOutput(buffer)
256
+ if (output.length > 200000) output = output.slice(-200000)
257
+ if (options.onLine) {
258
+ for (const line of output.split(/\r?\n/u).slice(-4)) options.onLine(line)
259
+ }
260
+ }
261
+ child.stdout.on('data', append)
262
+ child.stderr.on('data', append)
263
+ const timer = setTimeout(() => {
264
+ try { child.kill('SIGKILL') } catch {}
265
+ reject(new Error('安装超时(' + Math.round((options.timeoutMs ?? 300000) / 1000) + ' 秒):' + output.slice(-2000)))
266
+ }, options.timeoutMs ?? 300000)
267
+ child.on('error', (error) => { clearTimeout(timer); reject(error) })
268
+ child.on('close', (code) => {
269
+ clearTimeout(timer)
270
+ appendLog('cli ' + args.join(' ') + ' -> ' + code + ' :: ' + output.slice(-400).replace(/\n/gu, ' | '))
271
+ resolve({ code: code ?? -1, output })
272
+ })
273
+ })
274
+ }