dsh-modpack-kit 0.0.0-stage → 0.1.3
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/LICENSE +75 -0
- package/README.md +224 -2
- package/assets/icon-180.png +0 -0
- package/assets/install-stub.cmd +15 -0
- package/assets/install-stub.mjs +259 -0
- package/assets/install-stub.sh +9 -0
- package/client.js +1275 -0
- package/cordis.patch.yml +3 -0
- package/docs/DETAIL.md +97 -0
- package/icon.svg +14 -0
- package/index.js +820 -0
- package/lib/classify.mjs +105 -0
- package/lib/compat.mjs +112 -0
- package/lib/install.mjs +349 -0
- package/lib/manifest.mjs +197 -0
- package/lib/market-catalog.mjs +419 -0
- package/lib/pack.mjs +460 -0
- package/lib/profile.mjs +274 -0
- package/lib/registry.mjs +223 -0
- package/lib/scan.mjs +325 -0
- package/lib/semver.mjs +143 -0
- package/lib/store.mjs +183 -0
- package/lib/tar.mjs +107 -0
- package/lib/yamlish.mjs +385 -0
- package/lib/zip.mjs +232 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +54 -3
package/index.js
ADDED
|
@@ -0,0 +1,820 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-modpack —— Host 侧。
|
|
3
|
+
*
|
|
4
|
+
* 只做四件事:把本机状况喂给页面、在内存里打包、在安装前把包拆开看清楚、调官方 CLI 装。
|
|
5
|
+
* 所有网络请求走 lib/registry 的白名单与体积上限;所有文件写入落在 <DSH_HOME>/dsh-modpack。
|
|
6
|
+
*/
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import path from 'node:path'
|
|
9
|
+
import { randomBytes } from 'node:crypto'
|
|
10
|
+
import { loadConfig, saveConfig, pathsFor, profileName, readHistory, appendHistory, appendLog, ensureDir, slugify, DEFAULT_CONFIG } from './lib/store.mjs'
|
|
11
|
+
import { listInstalled, dshVersion, readProfilePackage, readBundles } from './lib/profile.mjs'
|
|
12
|
+
import { downloadPackage, npmMetadata, fetchLimited, relativeTime } from './lib/registry.mjs'
|
|
13
|
+
import { buildPack, PackRefused } from './lib/pack.mjs'
|
|
14
|
+
import { inspectPackBuffer, installPack, readPackFromUrl, InstallRefused } from './lib/install.mjs'
|
|
15
|
+
import { checkCompatibility } from './lib/compat.mjs'
|
|
16
|
+
import { classifyPlugin } from './lib/classify.mjs'
|
|
17
|
+
import { groupFindings } from './lib/scan.mjs'
|
|
18
|
+
import { catalogSummary, searchCatalog, syncCatalog, categoryMapFor, lookupPlugins } from './lib/market-catalog.mjs'
|
|
19
|
+
import { parseYaml } from './lib/yamlish.mjs'
|
|
20
|
+
import { readPatch } from './lib/profile.mjs'
|
|
21
|
+
import { buildReadme, pluginSummary } from './lib/manifest.mjs'
|
|
22
|
+
|
|
23
|
+
const VERSION = '0.1.0'
|
|
24
|
+
const MAX_JSON_BODY = 1024 * 1024
|
|
25
|
+
const PENDING_TTL = 30 * 60 * 1000
|
|
26
|
+
const PENDING_MAX = 4
|
|
27
|
+
const PENDING_BYTES = 512 * 1024 * 1024
|
|
28
|
+
|
|
29
|
+
const json = (res, code, obj) => {
|
|
30
|
+
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' })
|
|
31
|
+
res.end(JSON.stringify(obj))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const readBody = (req, limit = MAX_JSON_BODY) => new Promise((resolve, reject) => {
|
|
35
|
+
let size = 0
|
|
36
|
+
const chunks = []
|
|
37
|
+
req.on('data', (chunk) => {
|
|
38
|
+
size += chunk.length
|
|
39
|
+
if (size > limit) { reject(Object.assign(new Error('请求体过大'), { statusCode: 413 })); req.destroy(); return }
|
|
40
|
+
chunks.push(chunk)
|
|
41
|
+
})
|
|
42
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
|
|
43
|
+
req.on('error', reject)
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
const asJson = (text, fallback) => {
|
|
47
|
+
try { return JSON.parse(text) } catch { return fallback }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export default {
|
|
51
|
+
name: 'dsh-modpack-kit',
|
|
52
|
+
inject: ['webServer'],
|
|
53
|
+
apply(ctx) {
|
|
54
|
+
let config = loadConfig()
|
|
55
|
+
let pending = new Map()
|
|
56
|
+
const disposers = []
|
|
57
|
+
const log = (...args) => { try { console.log('[dsh-modpack-kit]', ...args) } catch {} }
|
|
58
|
+
|
|
59
|
+
const profileDir = () => pathsFor(config).profile
|
|
60
|
+
|
|
61
|
+
const snapshot = () => {
|
|
62
|
+
const dir = profileDir()
|
|
63
|
+
let installed = []
|
|
64
|
+
let version = ''
|
|
65
|
+
let bundles = []
|
|
66
|
+
let error = ''
|
|
67
|
+
try {
|
|
68
|
+
installed = listInstalled(dir)
|
|
69
|
+
version = dshVersion(dir)
|
|
70
|
+
bundles = readBundles(readProfilePackage(dir))
|
|
71
|
+
} catch (e) {
|
|
72
|
+
error = String((e && e.message) || e)
|
|
73
|
+
}
|
|
74
|
+
let catalog = null
|
|
75
|
+
try { catalog = catalogSummary(config) } catch {}
|
|
76
|
+
// 词条分类以插件市场为准;市场目录里没有的(本机私有插件)才退回本地猜测
|
|
77
|
+
let marketCategories = {}
|
|
78
|
+
try { marketCategories = categoryMapFor(config, installed.map((p) => p.name)) } catch {}
|
|
79
|
+
return {
|
|
80
|
+
ok: !error,
|
|
81
|
+
error,
|
|
82
|
+
version,
|
|
83
|
+
platform: process.platform,
|
|
84
|
+
node: process.version,
|
|
85
|
+
electron: process.versions.electron || '',
|
|
86
|
+
dshVersion: version,
|
|
87
|
+
pluginVersion: VERSION,
|
|
88
|
+
profile: profileName(config),
|
|
89
|
+
paths: pathsFor(config),
|
|
90
|
+
catalog,
|
|
91
|
+
placements: {
|
|
92
|
+
settings: config.showInSettings !== false,
|
|
93
|
+
sidebar: config.showInSidebar !== false,
|
|
94
|
+
pluginsTab: config.showInPluginsTab === true,
|
|
95
|
+
},
|
|
96
|
+
installedTotal: installed.length,
|
|
97
|
+
installed: installed.filter((p) => p.isPlugin).map((p) => ({
|
|
98
|
+
name: p.name,
|
|
99
|
+
version: p.version,
|
|
100
|
+
description: p.description || '',
|
|
101
|
+
category: marketCategories[p.name] || classifyPlugin({ name: p.name, description: p.description || '' }).id,
|
|
102
|
+
dirName: p.dirName,
|
|
103
|
+
isBundle: p.isBundle,
|
|
104
|
+
hasClient: p.hasClient,
|
|
105
|
+
hasPatch: p.hasPatch,
|
|
106
|
+
size: p.size,
|
|
107
|
+
})),
|
|
108
|
+
market: (() => {
|
|
109
|
+
const hit = installed.find((p) => p.name === 'dshmarket' || p.name === '@dsh-market/client')
|
|
110
|
+
return { installed: Boolean(hit), name: hit ? hit.name : 'dshmarket', version: hit ? hit.version : '' }
|
|
111
|
+
})(),
|
|
112
|
+
bundled: bundles,
|
|
113
|
+
config,
|
|
114
|
+
defaults: DEFAULT_CONFIG,
|
|
115
|
+
history: readHistory().slice(-12).reverse(),
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function trusted(req) {
|
|
120
|
+
const host = String(req.headers?.host ?? '').toLowerCase()
|
|
121
|
+
const h = host.startsWith('[') ? host.slice(0, host.indexOf(']') + 1) : host.split(':')[0]
|
|
122
|
+
if (h === '127.0.0.1' || h === 'localhost' || h === '[::1]' || h === '::1') return true
|
|
123
|
+
try {
|
|
124
|
+
const conn = ctx.get('connection')
|
|
125
|
+
if (conn && typeof conn.isTrusted === 'function') return conn.isTrusted(req) === true
|
|
126
|
+
} catch {}
|
|
127
|
+
return false
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function fenced(req, res) {
|
|
131
|
+
if (!trusted(req)) { json(res, 403, { ok: false, error: '不受信任的访问来源' }); return true }
|
|
132
|
+
try {
|
|
133
|
+
const conn = ctx.get('connection')
|
|
134
|
+
if (conn && typeof conn.requestRejection === 'function') {
|
|
135
|
+
const code = conn.requestRejection(req)
|
|
136
|
+
if (code !== undefined && code !== null && code !== false) {
|
|
137
|
+
res.statusCode = typeof code === 'number' ? code : 403
|
|
138
|
+
res.end()
|
|
139
|
+
return true
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
} catch {}
|
|
143
|
+
return false
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function route(pathname, handler) {
|
|
147
|
+
disposers.push(ctx.webServer.register({
|
|
148
|
+
kind: 'exact',
|
|
149
|
+
path: pathname,
|
|
150
|
+
handler: async (req, res) => {
|
|
151
|
+
if (fenced(req, res)) return
|
|
152
|
+
try {
|
|
153
|
+
await handler(req, res)
|
|
154
|
+
} catch (error) {
|
|
155
|
+
const code = error && error.statusCode ? error.statusCode : 500
|
|
156
|
+
try { json(res, code, { ok: false, error: String((error && error.message) || error) }) } catch {}
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
}))
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const needPost = (req, res) => {
|
|
163
|
+
if (req.method === 'POST') return true
|
|
164
|
+
json(res, 405, { ok: false, error: '只接受 POST' })
|
|
165
|
+
return false
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function pendingBytes() {
|
|
169
|
+
let total = 0
|
|
170
|
+
for (const item of pending.values()) total += item.buffer ? item.buffer.length : 0
|
|
171
|
+
return total
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function rememberPending(fileName, payload) {
|
|
175
|
+
const size = payload && payload.buffer ? payload.buffer.length : 0
|
|
176
|
+
// 按条数与总字节双重淘汰:4 个 256MB 的包不该常驻 1GB
|
|
177
|
+
while (pending.size > 0 && (pending.size >= PENDING_MAX || pendingBytes() + size > PENDING_BYTES)) {
|
|
178
|
+
const oldest = [...pending.entries()].sort((a, b) => a[1].at - b[1].at)[0]
|
|
179
|
+
pending.delete(oldest[0])
|
|
180
|
+
}
|
|
181
|
+
const token = randomBytes(12).toString('hex')
|
|
182
|
+
pending.set(token, { at: Date.now(), fileName, ...payload })
|
|
183
|
+
return token
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function sweeper() {
|
|
187
|
+
const now = Date.now()
|
|
188
|
+
for (const [token, item] of pending) if (now - item.at > PENDING_TTL) pending.delete(token)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const installedOrEmpty = () => {
|
|
192
|
+
try { return listInstalled(profileDir()) } catch { return [] }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const compatFor = (manifest) => checkCompatibility(manifest.plugins, {
|
|
196
|
+
installed: installedOrEmpty(),
|
|
197
|
+
dshVersion: (() => { try { return dshVersion(profileDir()) } catch { return '' } })(),
|
|
198
|
+
nodeVersion: process.versions.node,
|
|
199
|
+
config,
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
// —— 概览 ——
|
|
203
|
+
route('/dsh-modpack-kit/api/status', async (req, res) => {
|
|
204
|
+
if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
|
|
205
|
+
json(res, 200, snapshot())
|
|
206
|
+
})
|
|
207
|
+
|
|
208
|
+
// —— 设置 ——
|
|
209
|
+
route('/dsh-modpack-kit/api/settings', async (req, res) => {
|
|
210
|
+
if (req.method === 'GET') { json(res, 200, { ok: true, config, defaults: DEFAULT_CONFIG }); return }
|
|
211
|
+
if (!needPost(req, res)) return
|
|
212
|
+
const body = asJson(await readBody(req), null)
|
|
213
|
+
if (!body || typeof body !== 'object') { json(res, 400, { ok: false, error: '请求体不是对象' }); return }
|
|
214
|
+
const patch = body.patch && typeof body.patch === 'object' ? body.patch : body
|
|
215
|
+
const next = { ...config }
|
|
216
|
+
for (const key of Object.keys(DEFAULT_CONFIG)) {
|
|
217
|
+
if (Object.prototype.hasOwnProperty.call(patch, key)) next[key] = patch[key]
|
|
218
|
+
}
|
|
219
|
+
// 三处显示位全关 = 插件没有入口了,拦掉
|
|
220
|
+
if (next.showInSettings === false && next.showInSidebar === false && next.showInPluginsTab === false) {
|
|
221
|
+
json(res, 400, { ok: false, error: '三处显示至少留一处,否则就没有入口能关回来了' })
|
|
222
|
+
return
|
|
223
|
+
}
|
|
224
|
+
config = saveConfig(next)
|
|
225
|
+
json(res, 200, { ok: true, config })
|
|
226
|
+
})
|
|
227
|
+
|
|
228
|
+
// —— 插件目录:分类、词条、分页搜索都照插件市场的来 ——
|
|
229
|
+
// 首屏只要「已装 + 分类」,不再整份目录下发;搜索走服务端分页,一次一页。
|
|
230
|
+
route('/dsh-modpack-kit/api/catalog', async (req, res) => {
|
|
231
|
+
if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
|
|
232
|
+
const installedList = installedOrEmpty().filter((p) => p.isPlugin).map((p) => ({
|
|
233
|
+
name: p.name, version: p.version, isBundle: p.isBundle, hasClient: p.hasClient, description: p.description || '',
|
|
234
|
+
}))
|
|
235
|
+
let catalog = null
|
|
236
|
+
try { catalog = catalogSummary(config) } catch (e) { catalog = { present: false, error: String((e && e.message) || e) } }
|
|
237
|
+
json(res, 200, { ok: true, catalog, installed: installedList, categories: catalog ? catalog.categories : [] })
|
|
238
|
+
})
|
|
239
|
+
|
|
240
|
+
route('/dsh-modpack-kit/api/catalog/status', async (req, res) => {
|
|
241
|
+
if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
|
|
242
|
+
try {
|
|
243
|
+
const summary = catalogSummary(config)
|
|
244
|
+
// 没有或者过期了就在后台自己去补,不让页面等
|
|
245
|
+
if (!summary.present || summary.stale) ensureCatalog(false)
|
|
246
|
+
json(res, 200, { ok: true, ...summary, pageSize: config.catalogPageSize, refreshHours: config.catalogRefreshHours })
|
|
247
|
+
} catch (e) {
|
|
248
|
+
json(res, 500, { ok: false, error: String((e && e.message) || e) })
|
|
249
|
+
}
|
|
250
|
+
})
|
|
251
|
+
|
|
252
|
+
route('/dsh-modpack-kit/api/catalog/lookup', async (req, res) => {
|
|
253
|
+
if (!needPost(req, res)) return
|
|
254
|
+
const body = asJson(await readBody(req), {}) || {}
|
|
255
|
+
const names = Array.isArray(body.names) ? body.names.filter((n) => typeof n === 'string').slice(0, 400) : []
|
|
256
|
+
try {
|
|
257
|
+
json(res, 200, { ok: true, items: lookupPlugins(config, names) })
|
|
258
|
+
} catch (e) {
|
|
259
|
+
json(res, 200, { ok: false, error: String((e && e.message) || e), items: {} })
|
|
260
|
+
}
|
|
261
|
+
})
|
|
262
|
+
|
|
263
|
+
route('/dsh-modpack-kit/api/catalog/sync', async (req, res) => {
|
|
264
|
+
if (!needPost(req, res)) return
|
|
265
|
+
const body = asJson(await readBody(req), {}) || {}
|
|
266
|
+
const hours = Math.max(1, Number(config.catalogRefreshHours) || 24)
|
|
267
|
+
const result = await syncCatalog(config, { force: body.force === true, maxAgeMs: hours * 3600 * 1000 })
|
|
268
|
+
if (result.ok && !result.skipped) appendLog(`目录同步 ${result.count} 条(${result.source},${Math.round((result.ms || 0) / 100) / 10}s)`)
|
|
269
|
+
json(res, result.ok ? 200 : 502, { ...result, catalog: (() => { try { return catalogSummary(config) } catch { return null } })() })
|
|
270
|
+
})
|
|
271
|
+
|
|
272
|
+
route('/dsh-modpack-kit/api/catalog/search', async (req, res) => {
|
|
273
|
+
if (!needPost(req, res)) return
|
|
274
|
+
const body = asJson(await readBody(req), {}) || {}
|
|
275
|
+
const localPlugins = installedOrEmpty().filter((p) => p.isPlugin)
|
|
276
|
+
const localCategories = categoryMapFor(config, localPlugins.map((p) => p.name))
|
|
277
|
+
const installed = localPlugins.map((p) => ({
|
|
278
|
+
name: p.name, version: p.version, description: p.description || '',
|
|
279
|
+
// 和市场侧统一用同一套 23 类,否则按 theme/memory 筛时本机独有的插件会被漏掉
|
|
280
|
+
category: localCategories[p.name] || classifyPlugin({ name: p.name, description: p.description || '' }).id,
|
|
281
|
+
}))
|
|
282
|
+
try {
|
|
283
|
+
json(res, 200, searchCatalog(config, {
|
|
284
|
+
query: body.query,
|
|
285
|
+
category: body.category,
|
|
286
|
+
page: body.page,
|
|
287
|
+
pageSize: body.pageSize,
|
|
288
|
+
sort: body.sort,
|
|
289
|
+
installed,
|
|
290
|
+
}))
|
|
291
|
+
} catch (e) {
|
|
292
|
+
json(res, 500, { ok: false, error: String((e && e.message) || e), items: [] })
|
|
293
|
+
}
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
// —— 查某个包的可用版本 ——
|
|
298
|
+
route('/dsh-modpack-kit/api/versions', async (req, res) => {
|
|
299
|
+
if (!needPost(req, res)) return
|
|
300
|
+
const body = asJson(await readBody(req), {})
|
|
301
|
+
const name = String(body.name || '')
|
|
302
|
+
try {
|
|
303
|
+
const { meta, registry } = await npmMetadata(name, config)
|
|
304
|
+
const versions = Object.keys((meta && meta.versions) || {})
|
|
305
|
+
.map((v) => ({ version: v, time: (meta.time && meta.time[v]) || '', deprecated: Boolean(meta.versions[v] && meta.versions[v].deprecated) }))
|
|
306
|
+
.reverse()
|
|
307
|
+
json(res, 200, { ok: true, name, registry, versions: versions.slice(0, 60), relative: relativeTime })
|
|
308
|
+
} catch (e) {
|
|
309
|
+
json(res, 200, { ok: false, error: String((e && e.message) || e) })
|
|
310
|
+
}
|
|
311
|
+
})
|
|
312
|
+
|
|
313
|
+
// —— 打包(支持后台任务:左下角悬浮窗要进度,且允许同时打多个包) ——
|
|
314
|
+
const jobs = new Map()
|
|
315
|
+
let jobSeq = 0
|
|
316
|
+
const JOBS_KEEP = 10 * 60 * 1000
|
|
317
|
+
const pruneJobs = () => {
|
|
318
|
+
const cut = Date.now() - JOBS_KEEP
|
|
319
|
+
for (const [id, job] of jobs) {
|
|
320
|
+
if (job.status === 'running') continue
|
|
321
|
+
const stamp = Date.parse(job.finishedAt || job.startedAt) || 0
|
|
322
|
+
if (stamp && stamp < cut) jobs.delete(id)
|
|
323
|
+
}
|
|
324
|
+
for (const id of [...jobs.keys()]) {
|
|
325
|
+
if (jobs.size <= 20) break
|
|
326
|
+
const job = jobs.get(id)
|
|
327
|
+
if (job.status === 'running') continue
|
|
328
|
+
jobs.delete(id)
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
const createJob = (kind, label) => {
|
|
332
|
+
const job = {
|
|
333
|
+
id: 'job_' + (++jobSeq).toString(36) + '_' + Date.now().toString(36),
|
|
334
|
+
kind,
|
|
335
|
+
label,
|
|
336
|
+
status: 'running',
|
|
337
|
+
pct: 0,
|
|
338
|
+
note: '准备中',
|
|
339
|
+
startedAt: new Date().toISOString(),
|
|
340
|
+
finishedAt: '',
|
|
341
|
+
error: '',
|
|
342
|
+
data: null,
|
|
343
|
+
// 风险停下来的任务:保留原始请求,等你选「立即停止」还是「我知道在干什么」
|
|
344
|
+
risk: null,
|
|
345
|
+
body: null,
|
|
346
|
+
}
|
|
347
|
+
jobs.set(job.id, job)
|
|
348
|
+
pruneJobs()
|
|
349
|
+
return job
|
|
350
|
+
}
|
|
351
|
+
const publicJob = (job) => ({
|
|
352
|
+
id: job.id,
|
|
353
|
+
kind: job.kind,
|
|
354
|
+
label: job.label,
|
|
355
|
+
status: job.status,
|
|
356
|
+
pct: job.pct,
|
|
357
|
+
note: job.note,
|
|
358
|
+
startedAt: job.startedAt,
|
|
359
|
+
finishedAt: job.finishedAt,
|
|
360
|
+
error: job.error,
|
|
361
|
+
data: job.data,
|
|
362
|
+
risk: job.risk,
|
|
363
|
+
// 只有「可确认继续」的风险任务才给「我知道在干什么」;停下来的任务都能删
|
|
364
|
+
canAck: Boolean(job.risk && job.risk.needsAck && job.status === 'paused'),
|
|
365
|
+
canDismiss: job.status !== 'running',
|
|
366
|
+
})
|
|
367
|
+
|
|
368
|
+
class JobCancelled extends Error {}
|
|
369
|
+
const performPack = async (body, job, resume = null) => {
|
|
370
|
+
const selection = Array.isArray(body.selection) ? body.selection : []
|
|
371
|
+
const options = body.options && typeof body.options === 'object' ? body.options : {}
|
|
372
|
+
const dir = profileDir()
|
|
373
|
+
const installed = installedOrEmpty()
|
|
374
|
+
const dshVersionNow = (() => { try { return dshVersion(dir) } catch { return '' } })()
|
|
375
|
+
// 市场目录里能查到的插件:风险项默认放行,但需调用方 acknowledge
|
|
376
|
+
let trusted = []
|
|
377
|
+
try {
|
|
378
|
+
const look = lookupPlugins(config, selection.map((item) => String(item.name || '')).filter(Boolean))
|
|
379
|
+
trusted = Object.keys(look || {})
|
|
380
|
+
} catch { trusted = [] }
|
|
381
|
+
const onProgress = (event) => {
|
|
382
|
+
if (!job) return
|
|
383
|
+
if (job.cancelled) throw new JobCancelled('已取消')
|
|
384
|
+
job.pct = event.pct
|
|
385
|
+
job.note = event.note || job.note
|
|
386
|
+
}
|
|
387
|
+
try {
|
|
388
|
+
const result = await buildPack({
|
|
389
|
+
selection: selection.map((item) => ({
|
|
390
|
+
name: String(item.name || ''),
|
|
391
|
+
source: item.source === 'npm' ? 'npm' : 'profile',
|
|
392
|
+
spec: item.spec ? String(item.spec) : '',
|
|
393
|
+
mode: item.mode === 'local' ? 'local' : item.mode === 'base' ? 'base' : undefined,
|
|
394
|
+
download: (spec) => downloadPackage(String(item.name || ''), spec || item.spec || '', config),
|
|
395
|
+
})),
|
|
396
|
+
options: {
|
|
397
|
+
includePayload: options.includePayload !== false,
|
|
398
|
+
includeConfig: options.includeConfig !== false,
|
|
399
|
+
includeLocalEdits: options.includeLocalEdits === true,
|
|
400
|
+
confirmLicense: options.confirmLicense === true,
|
|
401
|
+
force: options.force === true,
|
|
402
|
+
acknowledge: options.acknowledge === true,
|
|
403
|
+
trusted,
|
|
404
|
+
keepLocal: options.keepLocal !== false,
|
|
405
|
+
scanBeforePack: true,
|
|
406
|
+
onProgress,
|
|
407
|
+
name: String(options.name || 'DSH 整合包'),
|
|
408
|
+
description: String(options.description || ''),
|
|
409
|
+
author: String(options.author || ''),
|
|
410
|
+
license: String(options.license || ''),
|
|
411
|
+
homepage: String(options.homepage || ''),
|
|
412
|
+
extensions: options.extensions && typeof options.extensions === 'object' ? options.extensions : {},
|
|
413
|
+
resume: resume && typeof resume === 'object' ? resume : null,
|
|
414
|
+
},
|
|
415
|
+
context: {
|
|
416
|
+
config,
|
|
417
|
+
profileDir: dir,
|
|
418
|
+
dshVersion: dshVersionNow,
|
|
419
|
+
installed,
|
|
420
|
+
pluginVersion: VERSION,
|
|
421
|
+
extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [],
|
|
422
|
+
parsePatch: parseYaml,
|
|
423
|
+
patchText: readPatch(dir),
|
|
424
|
+
},
|
|
425
|
+
})
|
|
426
|
+
const token = rememberPending(result.fileName, { buffer: result.buffer, manifest: result.manifest, report: result.report, scan: result.scan })
|
|
427
|
+
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)
|
|
428
|
+
return {
|
|
429
|
+
ok: true,
|
|
430
|
+
token,
|
|
431
|
+
fileName: result.fileName,
|
|
432
|
+
size: result.size,
|
|
433
|
+
manifest: result.manifest,
|
|
434
|
+
scan: result.scan,
|
|
435
|
+
scanGroups: result.scanGroups,
|
|
436
|
+
report: result.report,
|
|
437
|
+
notes: result.notes,
|
|
438
|
+
compat: checkCompatibility(result.manifest.plugins, { installed, dshVersion: dshVersionNow, nodeVersion: process.versions.node, config }),
|
|
439
|
+
}
|
|
440
|
+
} catch (error) {
|
|
441
|
+
if (error instanceof JobCancelled) {
|
|
442
|
+
// 取消发生在内存里:没有写入任何文件,直接丢弃缓冲
|
|
443
|
+
return { ok: false, cancelled: true, error: '已取消(未生成文件,本地没有残留)' }
|
|
444
|
+
}
|
|
445
|
+
if (error instanceof PackRefused) {
|
|
446
|
+
const scanGroups = (() => { try { return error.scan ? groupFindings(error.scan.findings, (selection || []).map((item) => ({ name: String(item.name || '') }))) : [] } catch { return [] } })()
|
|
447
|
+
return {
|
|
448
|
+
ok: false,
|
|
449
|
+
refused: true,
|
|
450
|
+
needsAck: error.needsAck === true,
|
|
451
|
+
trustedOnly: error.trustedOnly === true,
|
|
452
|
+
error: error.message,
|
|
453
|
+
scan: error.scan,
|
|
454
|
+
scanGroups,
|
|
455
|
+
checkpoint: error.checkpoint || null,
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
return { ok: false, error: String((error && error.message) || error) }
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// 任务收尾:只有「能确认继续」的风险才停下等你点一下;其余情况照旧判失败
|
|
463
|
+
const finishPackJob = (job, payload) => {
|
|
464
|
+
if (payload && payload.ok !== true && payload.refused === true) {
|
|
465
|
+
const counts = (payload.scan && payload.scan.counts) || {}
|
|
466
|
+
job.risk = {
|
|
467
|
+
high: counts.high || 0,
|
|
468
|
+
medium: counts.medium || 0,
|
|
469
|
+
low: counts.low || 0,
|
|
470
|
+
needsAck: payload.needsAck === true,
|
|
471
|
+
trustedOnly: payload.trustedOnly === true,
|
|
472
|
+
message: payload.error || '检测到风险',
|
|
473
|
+
// 只留分组摘要,不给界面塞整份 findings
|
|
474
|
+
groups: Array.isArray(payload.scanGroups)
|
|
475
|
+
? payload.scanGroups.map((g) => ({
|
|
476
|
+
plugin: g.plugin || '',
|
|
477
|
+
label: g.label,
|
|
478
|
+
origin: g.origin,
|
|
479
|
+
counts: g.counts,
|
|
480
|
+
samples: Array.isArray(g.findings)
|
|
481
|
+
? g.findings.slice(0, 4).map((f) => ({ label: f.label, severity: f.severity, file: f.file, line: f.line }))
|
|
482
|
+
: [],
|
|
483
|
+
}))
|
|
484
|
+
: [],
|
|
485
|
+
}
|
|
486
|
+
job.finishedAt = new Date().toISOString()
|
|
487
|
+
if (payload.needsAck === true) {
|
|
488
|
+
job.status = 'paused'
|
|
489
|
+
job.note = '检测到风险,等你决定'
|
|
490
|
+
job.pct = Math.min(job.pct || 0, 66)
|
|
491
|
+
job.checkpoint = payload.checkpoint || null
|
|
492
|
+
} else {
|
|
493
|
+
// 市场目录里查不到:没有「我知道在干什么」这条路,直接判失败
|
|
494
|
+
job.status = 'failed'
|
|
495
|
+
job.error = payload.error || '检测到风险'
|
|
496
|
+
job.note = '检测到风险,已拒绝出包'
|
|
497
|
+
job.data = payload
|
|
498
|
+
}
|
|
499
|
+
return
|
|
500
|
+
}
|
|
501
|
+
job.status = payload && payload.ok ? 'done' : payload && payload.cancelled === true ? 'cancelled' : 'failed'
|
|
502
|
+
job.data = payload
|
|
503
|
+
job.pct = payload && payload.ok ? 100 : job.pct
|
|
504
|
+
job.note = payload && payload.ok ? '完成' : ((payload && payload.error) || '已停止')
|
|
505
|
+
// 失败/取消也把原因放进 error,进度窗那一行能直接看到为什么卡住
|
|
506
|
+
if (!(payload && payload.ok)) job.error = (payload && payload.error) || job.note
|
|
507
|
+
job.finishedAt = new Date().toISOString()
|
|
508
|
+
}
|
|
509
|
+
const startPackJob = (body, label) => {
|
|
510
|
+
const job = createJob('pack', label || ('打包「' + String((body.options && body.options.name) || 'DSH 整合包') + '」'))
|
|
511
|
+
// 留一份原始请求:风险停下来之后,界面上点「我知道在干什么」要能照原样再跑一次
|
|
512
|
+
try {
|
|
513
|
+
job.body = JSON.parse(JSON.stringify({
|
|
514
|
+
selection: Array.isArray(body.selection) ? body.selection : [],
|
|
515
|
+
options: body.options && typeof body.options === 'object' ? body.options : {},
|
|
516
|
+
}))
|
|
517
|
+
} catch { job.body = null }
|
|
518
|
+
performPack(body, job)
|
|
519
|
+
.then((payload) => finishPackJob(job, payload))
|
|
520
|
+
.catch((error) => {
|
|
521
|
+
job.status = 'failed'
|
|
522
|
+
job.error = String((error && error.message) || error)
|
|
523
|
+
job.note = '失败'
|
|
524
|
+
job.finishedAt = new Date().toISOString()
|
|
525
|
+
})
|
|
526
|
+
return job
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
route('/dsh-modpack-kit/api/pack', async (req, res) => {
|
|
530
|
+
if (!needPost(req, res)) return
|
|
531
|
+
const body = asJson(await readBody(req), {})
|
|
532
|
+
const selection = Array.isArray(body.selection) ? body.selection : []
|
|
533
|
+
if (selection.length === 0) { json(res, 400, { ok: false, error: '没有选择任何插件' }); return }
|
|
534
|
+
if (body.async === true || body.background === true) {
|
|
535
|
+
const job = startPackJob(body)
|
|
536
|
+
json(res, 200, { ok: true, async: true, job: publicJob(job) })
|
|
537
|
+
return
|
|
538
|
+
}
|
|
539
|
+
const payload = await performPack(body, null)
|
|
540
|
+
json(res, 200, payload)
|
|
541
|
+
})
|
|
542
|
+
|
|
543
|
+
// 风险停下来之后:只有「我知道在干什么」,点它就在同一个任务里接着跑完
|
|
544
|
+
route('/dsh-modpack-kit/api/jobs/ack', async (req, res) => {
|
|
545
|
+
if (!needPost(req, res)) return
|
|
546
|
+
const body = asJson(await readBody(req), {})
|
|
547
|
+
const job = jobs.get(String(body.id || ''))
|
|
548
|
+
if (!job) { json(res, 404, { ok: false, error: '没有这个任务(可能已完成并过期)' }); return }
|
|
549
|
+
if (!job.risk) { json(res, 400, { ok: false, error: '这个任务没有风险项,不需要确认' }); return }
|
|
550
|
+
if (job.risk.needsAck !== true) { json(res, 400, { ok: false, error: '这些风险不在插件市场目录里,没法确认继续' }); return }
|
|
551
|
+
if (job.status === 'running') { json(res, 409, { ok: false, error: '任务还在跑,等它到风险点再说' }); return }
|
|
552
|
+
if (job.status !== 'paused') { json(res, 400, { ok: false, error: '这个任务已经收尾了,不能再确认' }); return }
|
|
553
|
+
// 同一个任务接着跑:复用停下来的那份检测结果,进度从检测点继续,不重新检测
|
|
554
|
+
const checkpoint = job.checkpoint || null
|
|
555
|
+
job.checkpoint = null
|
|
556
|
+
job.status = 'running'
|
|
557
|
+
job.cancelled = false
|
|
558
|
+
job.acked = true
|
|
559
|
+
// 确认过了就不该再吓人:红字(risk)撤掉,只留 status 与进度
|
|
560
|
+
job.risk = null
|
|
561
|
+
job.error = ''
|
|
562
|
+
job.note = checkpoint ? '已确认风险,从检测点继续' : '已确认风险,继续完成'
|
|
563
|
+
job.pct = Math.min(job.pct || 0, 66)
|
|
564
|
+
job.finishedAt = ''
|
|
565
|
+
const source = job.body || { selection: [] }
|
|
566
|
+
const replay = { selection: source.selection || [], options: { ...(source.options || {}), acknowledge: true } }
|
|
567
|
+
performPack(replay, job, checkpoint)
|
|
568
|
+
.then((payload) => finishPackJob(job, payload))
|
|
569
|
+
.catch((error) => {
|
|
570
|
+
job.status = 'failed'
|
|
571
|
+
job.error = String((error && error.message) || error)
|
|
572
|
+
job.note = '失败'
|
|
573
|
+
job.finishedAt = new Date().toISOString()
|
|
574
|
+
})
|
|
575
|
+
json(res, 200, { ok: true, job: publicJob(job) })
|
|
576
|
+
})
|
|
577
|
+
|
|
578
|
+
route('/dsh-modpack-kit/api/jobs/dismiss', async (req, res) => {
|
|
579
|
+
if (!needPost(req, res)) return
|
|
580
|
+
const body = asJson(await readBody(req), {})
|
|
581
|
+
const id = String(body.id || '')
|
|
582
|
+
const job = jobs.get(id)
|
|
583
|
+
if (!job) { json(res, 404, { ok: false, error: '没有这个任务(可能已经删了)' }); return }
|
|
584
|
+
if (job.status === 'running') { json(res, 400, { ok: false, error: '还在跑,先终止再删' }); return }
|
|
585
|
+
jobs.delete(id)
|
|
586
|
+
json(res, 200, { ok: true, removed: id })
|
|
587
|
+
})
|
|
588
|
+
|
|
589
|
+
// 清空进程:删掉所有收尾记录(完成的、失败的、取消的、超上限卡住的都算),
|
|
590
|
+
// 只有还在跑的与停在风险点等决定的留着。
|
|
591
|
+
route('/dsh-modpack-kit/api/jobs/clear', async (req, res) => {
|
|
592
|
+
if (!needPost(req, res)) return
|
|
593
|
+
const keep = new Set(['running', 'paused'])
|
|
594
|
+
const removed = []
|
|
595
|
+
for (const [id, job] of [...jobs.entries()]) {
|
|
596
|
+
if (keep.has(job.status)) continue
|
|
597
|
+
jobs.delete(id)
|
|
598
|
+
removed.push(id)
|
|
599
|
+
}
|
|
600
|
+
json(res, 200, { ok: true, removed, jobs: [...jobs.values()].map(publicJob) })
|
|
601
|
+
})
|
|
602
|
+
|
|
603
|
+
route('/dsh-modpack-kit/api/jobs/cancel', async (req, res) => {
|
|
604
|
+
if (!needPost(req, res)) return
|
|
605
|
+
const body = asJson(await readBody(req), {})
|
|
606
|
+
const job = jobs.get(String(body.id || ''))
|
|
607
|
+
if (!job) { json(res, 404, { ok: false, error: '没有这个任务(可能已完成并过期)' }); return }
|
|
608
|
+
if (job.status !== 'running') {
|
|
609
|
+
// 停在风险点的任务:立即停止就是把它标成已停止,不留文件
|
|
610
|
+
if (job.status === 'paused') {
|
|
611
|
+
job.checkpoint = null
|
|
612
|
+
job.status = 'cancelled'
|
|
613
|
+
job.note = '已停止(未生成文件,本地没有残留)'
|
|
614
|
+
job.finishedAt = job.finishedAt || new Date().toISOString()
|
|
615
|
+
json(res, 200, { ok: true, job: publicJob(job) })
|
|
616
|
+
return
|
|
617
|
+
}
|
|
618
|
+
json(res, 200, { ok: true, already: true, job: publicJob(job) })
|
|
619
|
+
return
|
|
620
|
+
}
|
|
621
|
+
job.cancelled = true
|
|
622
|
+
job.note = '正在停止…'
|
|
623
|
+
json(res, 200, { ok: true, job: publicJob(job) })
|
|
624
|
+
})
|
|
625
|
+
|
|
626
|
+
route('/dsh-modpack-kit/api/jobs', (req, res) => {
|
|
627
|
+
if (req.method !== 'GET') { json(res, 405, { ok: false, error: '只支持 GET' }); return }
|
|
628
|
+
pruneJobs()
|
|
629
|
+
json(res, 200, { ok: true, jobs: [...jobs.values()].map(publicJob) })
|
|
630
|
+
})
|
|
631
|
+
|
|
632
|
+
// —— 下载 / 落盘 ——
|
|
633
|
+
route('/dsh-modpack-kit/api/download', async (req, res) => {
|
|
634
|
+
if (!needPost(req, res)) return
|
|
635
|
+
const body = asJson(await readBody(req), {})
|
|
636
|
+
const item = pending.get(String(body.token || ''))
|
|
637
|
+
if (!item) { json(res, 404, { ok: false, error: '打包结果已过期,请重新打包' }); return }
|
|
638
|
+
const safeName = String(body.fileName || item.fileName || 'pack.dshpack').replace(/[^\w.\-]+/gu, '_')
|
|
639
|
+
res.writeHead(200, {
|
|
640
|
+
'Content-Type': 'application/octet-stream',
|
|
641
|
+
'Content-Disposition': 'attachment; filename="' + safeName + '"',
|
|
642
|
+
'Content-Length': item.buffer.length,
|
|
643
|
+
'Cache-Control': 'no-store',
|
|
644
|
+
})
|
|
645
|
+
res.end(item.buffer)
|
|
646
|
+
})
|
|
647
|
+
|
|
648
|
+
route('/dsh-modpack-kit/api/save', async (req, res) => {
|
|
649
|
+
if (!needPost(req, res)) return
|
|
650
|
+
const body = asJson(await readBody(req), {})
|
|
651
|
+
const item = pending.get(String(body.token || ''))
|
|
652
|
+
if (!item) { json(res, 404, { ok: false, error: '打包结果已过期,请重新打包' }); return }
|
|
653
|
+
const paths = pathsFor(config)
|
|
654
|
+
ensureDir(paths.packs)
|
|
655
|
+
const fileName = slugify(body.fileName || item.fileName.replace(/\.dshpack$/u, ''), 'pack') + '.dshpack'
|
|
656
|
+
const target = path.join(paths.packs, fileName)
|
|
657
|
+
fs.writeFileSync(target, item.buffer)
|
|
658
|
+
pending.delete(String(body.token || ''))
|
|
659
|
+
json(res, 200, { ok: true, path: target, size: item.buffer.length })
|
|
660
|
+
})
|
|
661
|
+
|
|
662
|
+
route('/dsh-modpack-kit/api/packs', async (req, res) => {
|
|
663
|
+
if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
|
|
664
|
+
const dir = pathsFor(config).packs
|
|
665
|
+
const items = []
|
|
666
|
+
try {
|
|
667
|
+
for (const dirent of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
668
|
+
if (!dirent.isFile() || !dirent.name.endsWith('.dshpack')) continue
|
|
669
|
+
const stat = fs.statSync(path.join(dir, dirent.name))
|
|
670
|
+
items.push({ name: dirent.name, size: stat.size, mtime: stat.mtime.toISOString() })
|
|
671
|
+
}
|
|
672
|
+
} catch {}
|
|
673
|
+
items.sort((a, b) => (a.mtime < b.mtime ? 1 : -1))
|
|
674
|
+
json(res, 200, { ok: true, dir, items })
|
|
675
|
+
})
|
|
676
|
+
|
|
677
|
+
async function inspectInput(body) {
|
|
678
|
+
if (body.url) {
|
|
679
|
+
const buffer = await readPackFromUrl(String(body.url), config, fetchLimited)
|
|
680
|
+
return inspectPackBuffer(buffer, { config, force: body.force === true, scanBeforeInstall: config.scanBeforeInstall !== false, extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [] })
|
|
681
|
+
}
|
|
682
|
+
if (body.token) {
|
|
683
|
+
const item = pending.get(String(body.token))
|
|
684
|
+
if (!item) throw new Error('打包结果已过期,请重新打包')
|
|
685
|
+
return inspectPackBuffer(item.buffer, { config, force: body.force === true, scanBeforeInstall: config.scanBeforeInstall !== false, extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [] })
|
|
686
|
+
}
|
|
687
|
+
if (body.file) {
|
|
688
|
+
const target = path.isAbsolute(String(body.file)) ? String(body.file) : path.join(pathsFor(config).packs, path.basename(String(body.file)))
|
|
689
|
+
if (!target.endsWith('.dshpack')) throw new Error('只读取 .dshpack 文件')
|
|
690
|
+
return inspectPackBuffer(fs.readFileSync(target), { config, force: body.force === true, scanBeforeInstall: config.scanBeforeInstall !== false, extraScanRules: Array.isArray(config.extraScanRules) ? config.extraScanRules : [] })
|
|
691
|
+
}
|
|
692
|
+
throw new Error('需要 url、token 或 file 之一')
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// —— 预览 ——
|
|
696
|
+
route('/dsh-modpack-kit/api/inspect', async (req, res) => {
|
|
697
|
+
if (!needPost(req, res)) return
|
|
698
|
+
const body = asJson(await readBody(req), {})
|
|
699
|
+
try {
|
|
700
|
+
const inspected = await inspectInput(body)
|
|
701
|
+
const compat = compatFor(inspected.manifest)
|
|
702
|
+
json(res, 200, {
|
|
703
|
+
ok: true,
|
|
704
|
+
manifest: inspected.manifest,
|
|
705
|
+
integrity: inspected.integrity,
|
|
706
|
+
scan: inspected.scan,
|
|
707
|
+
scanGroups: groupFindings(inspected.scan.findings, inspected.manifest.plugins),
|
|
708
|
+
report: inspected.report,
|
|
709
|
+
blockingReasons: inspected.blockingReasons,
|
|
710
|
+
notes: inspected.notes,
|
|
711
|
+
compat,
|
|
712
|
+
readme: buildReadme(inspected.manifest),
|
|
713
|
+
})
|
|
714
|
+
} catch (error) {
|
|
715
|
+
json(res, 200, { ok: false, error: String((error && error.message) || error) })
|
|
716
|
+
}
|
|
717
|
+
})
|
|
718
|
+
|
|
719
|
+
// —— 安装 ——
|
|
720
|
+
route('/dsh-modpack-kit/api/install', async (req, res) => {
|
|
721
|
+
if (!needPost(req, res)) return
|
|
722
|
+
const body = asJson(await readBody(req), {})
|
|
723
|
+
const options = {
|
|
724
|
+
force: body.force === true,
|
|
725
|
+
keepLocal: body.keepLocal !== false,
|
|
726
|
+
applyConfig: body.applyConfig !== false,
|
|
727
|
+
dryRun: body.dryRun === true,
|
|
728
|
+
// 是否登记 bundle:请求里给了就听请求的,没给就听设置里的 enableOnInstall(默认关)。
|
|
729
|
+
enableBundles: typeof body.enableBundles === 'boolean' ? body.enableBundles : config.enableOnInstall === true,
|
|
730
|
+
}
|
|
731
|
+
try {
|
|
732
|
+
const inspected = await inspectInput(body)
|
|
733
|
+
if (inspected.blockingReasons.length > 0 && !options.force) {
|
|
734
|
+
const refused = new InstallRefused(inspected.blockingReasons.join(';'), inspected.scan)
|
|
735
|
+
json(res, 200, { ok: false, refused: true, error: refused.message, integrity: inspected.integrity, scan: inspected.scan, scanGroups: groupFindings(inspected.scan.findings, inspected.manifest.plugins), report: inspected.report })
|
|
736
|
+
return
|
|
737
|
+
}
|
|
738
|
+
const result = await installPack({
|
|
739
|
+
manifest: inspected.manifest,
|
|
740
|
+
entries: inspected.entries,
|
|
741
|
+
config,
|
|
742
|
+
options,
|
|
743
|
+
context: {
|
|
744
|
+
profileDir: profileDir(),
|
|
745
|
+
resolveSource: async (plugin, packRoot) => {
|
|
746
|
+
const downloaded = await downloadPackage(plugin.name, plugin.version || plugin.requested || '', config)
|
|
747
|
+
const target = path.join(packRoot, 'plugins', plugin.dirName || plugin.name)
|
|
748
|
+
ensureDir(target)
|
|
749
|
+
for (const entry of downloaded.entries) {
|
|
750
|
+
const dest = path.join(target, entry.name)
|
|
751
|
+
if (!path.resolve(dest).startsWith(path.resolve(target) + path.sep)) continue
|
|
752
|
+
ensureDir(path.dirname(dest))
|
|
753
|
+
fs.writeFileSync(dest, entry.data)
|
|
754
|
+
}
|
|
755
|
+
appendLog('resolve ' + plugin.name + '@' + downloaded.version + ' from ' + downloaded.registry)
|
|
756
|
+
return target
|
|
757
|
+
},
|
|
758
|
+
},
|
|
759
|
+
})
|
|
760
|
+
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)
|
|
761
|
+
json(res, 200, { ok: result.ok, ...result, manifest: inspected.manifest, scan: inspected.scan, scanGroups: groupFindings(inspected.scan.findings, inspected.manifest.plugins), report: inspected.report, integrity: inspected.integrity })
|
|
762
|
+
} catch (error) {
|
|
763
|
+
json(res, 200, { ok: false, error: String((error && error.message) || error) })
|
|
764
|
+
}
|
|
765
|
+
})
|
|
766
|
+
|
|
767
|
+
// —— 历史 ——
|
|
768
|
+
route('/dsh-modpack-kit/api/history', async (req, res) => {
|
|
769
|
+
if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
|
|
770
|
+
json(res, 200, { ok: true, items: readHistory().slice().reverse() })
|
|
771
|
+
})
|
|
772
|
+
|
|
773
|
+
route('/dsh-modpack-kit/api/plugin-summary', async (req, res) => {
|
|
774
|
+
if (req.method !== 'GET') { json(res, 405, { ok: false }); return }
|
|
775
|
+
const installed = installedOrEmpty()
|
|
776
|
+
json(res, 200, { ok: true, items: installed.map((p) => ({ name: p.name, version: p.version, size: p.size, isBundle: p.isBundle, hasClient: p.hasClient })) })
|
|
777
|
+
})
|
|
778
|
+
|
|
779
|
+
// —— 目录:启动后自己补一次(不阻塞启动);太旧了在问状态时补一次 ——
|
|
780
|
+
let catalogJob = null
|
|
781
|
+
let lastAutoTry = 0
|
|
782
|
+
const ensureCatalog = (force) => {
|
|
783
|
+
if (catalogJob) return catalogJob
|
|
784
|
+
// 自动尝试十分钟内只来一次,避免没网时每个请求都去敲一遍
|
|
785
|
+
if (force !== true && Date.now() - lastAutoTry < 10 * 60 * 1000) return Promise.resolve({ ok: false, skipped: true })
|
|
786
|
+
if (force !== true) lastAutoTry = Date.now()
|
|
787
|
+
const hours = Math.max(1, Number(config.catalogRefreshHours) || 24)
|
|
788
|
+
catalogJob = syncCatalog(config, { force: force === true, maxAgeMs: hours * 3600 * 1000 })
|
|
789
|
+
.then((result) => {
|
|
790
|
+
if (result && result.ok && !result.skipped) {
|
|
791
|
+
appendLog(`目录自动更新 ${result.count} 条(${result.source},${Math.round((result.ms || 0) / 100) / 10}s)`)
|
|
792
|
+
} else if (result && !result.ok) {
|
|
793
|
+
log('catalog sync failed:', result.error)
|
|
794
|
+
}
|
|
795
|
+
return result
|
|
796
|
+
})
|
|
797
|
+
.catch((error) => {
|
|
798
|
+
log('catalog sync failed:', String((error && error.message) || error))
|
|
799
|
+
return { ok: false, error: String((error && error.message) || error) }
|
|
800
|
+
})
|
|
801
|
+
.finally(() => { catalogJob = null })
|
|
802
|
+
return catalogJob
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
log('routes ready')
|
|
806
|
+
// 起来就把目录补一次;没有网也不影响其它功能,失败只写日志
|
|
807
|
+
if (process.env.DSH_MODPACK_OFFLINE !== '1') ensureCatalog(false).catch(() => {})
|
|
808
|
+
ctx.effect(() => {
|
|
809
|
+
const timer = setInterval(sweeper, 60 * 1000)
|
|
810
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
811
|
+
return () => {
|
|
812
|
+
clearInterval(timer)
|
|
813
|
+
pending.clear()
|
|
814
|
+
for (const dispose of disposers) { try { dispose() } catch {} }
|
|
815
|
+
}
|
|
816
|
+
}, 'dsh-modpack-kit:routes')
|
|
817
|
+
},
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
export { pluginSummary }
|