dsh-pluginmarket-plus 0.0.0-stage → 0.1.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/index.js ADDED
@@ -0,0 +1,739 @@
1
+ /**
2
+ * dsh-pluginmarket-plus —— 插件市场索引本地缓存(Host 半边)。
3
+ *
4
+ * ## 它解决什么问题
5
+ *
6
+ * 官方插件市场(插件页 → 发现)由 `pluginMarket` 服务读取索引源,单次抓取限时
7
+ * 15 秒、失败不落盘。真实的索引动辄 1–8 MB,从这里访问 `cdn.dsh.so` 要 80 秒、
8
+ * `api.dshfind.com` 要 18 秒,于是「搜索不出来 / 索引超时」。本插件在后台用更长
9
+ * 的时间窗把索引抓下来、写到本地磁盘,再通过本机 HTTP 路由提供一份镜像;把发现页
10
+ * 的索引源换成本地镜像后,抓取是毫秒级的,搜索不再超时。
11
+ *
12
+ * ## 组成
13
+ *
14
+ * - 磁盘缓存:`<profile>/.pluginmarket-plus/index-<id>.json` + `state.json`。
15
+ * - 定时刷新:默认每 4 小时一次(可关、可调);启动时补一次过期/缺失的源。
16
+ * - 本地镜像:`http://127.0.0.1:<port>/pluginmarket-plus/index/<id>.json`。
17
+ * 这份路由必须免登录——`pluginMarket` 是在 Host 进程里用裸 `fetch` 取索引的。
18
+ * - 设置页桥:`/api/pluginmarket-plus/*`(经 `connection.fetch`,仅 owner 可访问)。
19
+ * - 发现页接管:把 `plugin-market` 的 `indexes` 在「上游地址」和「本地镜像」之间
20
+ * 切换;只替换已经缓存成功的源,没缓存成功的继续保持直连。
21
+ *
22
+ * @module dsh-pluginmarket-plus
23
+ */
24
+
25
+ import { join, resolve } from 'node:path'
26
+ import z from '@deepseek-ai/schemastery'
27
+ import { CacheStore, sourceId } from './store.js'
28
+ import { fetchIndex, indexTitle, messageOf } from './refresh.js'
29
+
30
+ /** 包名(Client 模块 id 必须与它一致)。 */
31
+ export const name = 'dsh-pluginmarket-plus'
32
+
33
+ /** 本地镜像路由前缀。 */
34
+ export const MIRROR_PATH = '/pluginmarket-plus/index'
35
+
36
+ /** 公开状态路由(只读,便于排查问题)。 */
37
+ const PUBLIC_STATUS_PATH = '/pluginmarket-plus/status.json'
38
+
39
+ /** 设置页桥前缀。 */
40
+ const API_PREFIX = '/api/pluginmarket-plus'
41
+
42
+ /** 镜像 id 的路径匹配。 */
43
+ const MIRROR_ID = /^\/pluginmarket-plus\/index\/([a-f0-9]{16})\.json$/u
44
+
45
+ /** 最长 7 天的刷新间隔,避免 setTimeout 溢出。 */
46
+ const MAX_INTERVAL_HOURS = 168
47
+
48
+ /** 配置。面板上可改的字段都声明为 volatile,修改后无需重载插件。 */
49
+ export const Config = z.object({
50
+ /** 要缓存的索引源;留空时自动接管「发现」页当前配置的源。 */
51
+ sources: z.array(z.string()).default([]).volatile(),
52
+ /** 是否按间隔自动刷新。 */
53
+ autoRefresh: z.boolean().default(true).volatile(),
54
+ /** 自动刷新间隔(小时)。 */
55
+ refreshIntervalHours: z.number().min(0.25).max(MAX_INTERVAL_HOURS).default(4).volatile(),
56
+ /** 是否让「发现」页优先使用本地镜像。 */
57
+ managePluginMarket: z.boolean().default(true).volatile(),
58
+ /** 单次抓取超时(毫秒)。索引很大,默认给到 2 分钟。 */
59
+ fetchTimeoutMs: z.natural().min(1000).default(120000),
60
+ /** 单个索引正文上限(字节)。 */
61
+ maxBytes: z.natural().min(1).default(64 * 1024 * 1024),
62
+ /** 失败重试次数。 */
63
+ retries: z.natural().min(0).max(5).default(2),
64
+ /** 缓存目录,相对 profile 目录。 */
65
+ cacheDir: z.string().default('.pluginmarket-plus'),
66
+ })
67
+
68
+ /**
69
+ * 读取一个可能是 volatile 引用的配置值。
70
+ * @param {unknown} value - 配置字段(普通值或 `{ get() }` 引用)。
71
+ * @param {unknown} fallback - 引用缺失时的回退值。
72
+ * @returns {unknown} 当前值。
73
+ */
74
+ function live(value, fallback) {
75
+ if (value !== null && typeof value === 'object' && typeof (/** @type {{ get?: unknown }} */ (value).get) === 'function') {
76
+ return /** @type {{ get: () => unknown }} */ (value).get()
77
+ }
78
+ return value ?? fallback
79
+ }
80
+
81
+ /**
82
+ * 归一化源列表:只保留 http(s) 绝对地址、去重、保持顺序。
83
+ * @param {unknown} list - 原始列表。
84
+ * @returns {string[]} 归一化后的地址。
85
+ */
86
+ function normalizeSources(list) {
87
+ if (!Array.isArray(list)) return []
88
+ const urls = []
89
+ for (const item of list) {
90
+ if (typeof item !== 'string') continue
91
+ const text = item.trim()
92
+ if (text === '') continue
93
+ let url
94
+ try {
95
+ url = new URL(text).href
96
+ } catch {
97
+ continue
98
+ }
99
+ if (!url.startsWith('http://') && !url.startsWith('https://')) continue
100
+ if (!urls.includes(url)) urls.push(url)
101
+ }
102
+ return urls
103
+ }
104
+
105
+ /**
106
+ * 从一个地址里读出镜像 id。
107
+ * @param {string} url - 任意地址。
108
+ * @returns {string|undefined} 镜像 id;不是本插件的镜像地址时为 undefined。
109
+ */
110
+ export function mirrorIdOf(url) {
111
+ try {
112
+ const pathname = new URL(url).pathname
113
+ return MIRROR_ID.exec(pathname)?.[1]
114
+ } catch {
115
+ return undefined
116
+ }
117
+ }
118
+
119
+ /**
120
+ * 构造某个源的本地镜像地址。
121
+ * @param {string} origin - 本机 Web 服务根地址,例如 `http://127.0.0.1:3080`。
122
+ * @param {string} url - 上游索引地址。
123
+ * @returns {string} 镜像地址。
124
+ */
125
+ export function mirrorUrl(origin, url) {
126
+ return `${origin}${MIRROR_PATH}/${sourceId(url)}.json`
127
+ }
128
+
129
+ /**
130
+ * 两个地址列表是否等价(顺序敏感)。
131
+ * @param {string[]} left - 列表一。
132
+ * @param {string[]} right - 列表二。
133
+ * @returns {boolean} 等价时为 true。
134
+ */
135
+ function sameList(left, right) {
136
+ return left.length === right.length && left.every((value, index) => value === right[index])
137
+ }
138
+
139
+ /**
140
+ * 读 JSON 请求体。
141
+ * @param {Request} request - Fetch 请求。
142
+ * @returns {Promise<Record<string, unknown>>} 解析后的对象;空体返回 {}。
143
+ */
144
+ async function readJsonBody(request) {
145
+ const text = await request.text()
146
+ if (text.trim() === '') return {}
147
+ const parsed = JSON.parse(text)
148
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
149
+ ? /** @type {Record<string, unknown>} */ (parsed)
150
+ : {}
151
+ }
152
+
153
+ /**
154
+ * 构造 JSON 响应。
155
+ * @param {unknown} payload - 响应体。
156
+ * @param {number} [status] - HTTP 状态码。
157
+ * @returns {Response} Fetch 响应。
158
+ */
159
+ function jsonResponse(payload, status = 200) {
160
+ return new Response(JSON.stringify(payload), {
161
+ status,
162
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
163
+ })
164
+ }
165
+
166
+ /**
167
+ * 插件主函数。
168
+ * @param {import('@deepseek-ai/cordis').Context} ctx - 插件上下文。
169
+ * @param {z.infer<typeof Config>} config - 插件配置。
170
+ * @returns {void}
171
+ */
172
+ export function apply(ctx, config) {
173
+ const profileDir = ctx.get('profileContext')?.dir ?? process.env.DSH_PROFILE_DIR ?? process.cwd()
174
+ const cacheDir = resolve(profileDir, String(config.cacheDir ?? '.pluginmarket-plus'))
175
+ const store = new CacheStore(cacheDir)
176
+
177
+ /** @type {import('@deepseek-ai/cordis').Context|undefined} */
178
+ let webService
179
+ /** @type {any} */
180
+ let marketService
181
+ /** @type {Map<string, Promise<unknown>>} */
182
+ const inflight = new Map()
183
+ /** @type {ReturnType<typeof setTimeout>|undefined} */
184
+ let refreshTimer
185
+ /** @type {ReturnType<typeof setTimeout>|undefined} */
186
+ let bootTimer
187
+ /** @type {ReturnType<typeof setTimeout>|undefined} */
188
+ let marketChangeTimer
189
+ let nextRefreshAt = 0
190
+ let marketError = null
191
+ /** 本插件最近一次写进「发现」页的完整列表,用来识别“这是我自己写的”事件。 */
192
+ let lastWrittenIndexes = []
193
+
194
+ const entryId = ctx.fiber?.entry?.options?.id
195
+ const logger = {
196
+ info: (/** @type {string} */ message, /** @type {unknown} */ detail) => ctx.logger?.info?.(`dsh-pluginmarket-plus: ${message}`, detail),
197
+ warn: (/** @type {string} */ message, /** @type {unknown} */ detail) => ctx.logger?.warn?.(`dsh-pluginmarket-plus: ${message}`, detail),
198
+ }
199
+
200
+ /**
201
+ * 当前生效的源:配置里写了就用配置,否则用自动接管时记住的列表。
202
+ * @returns {string[]} 源列表。
203
+ */
204
+ function effectiveSources() {
205
+ const configured = normalizeSources(live(config.sources, []))
206
+ if (configured.length > 0) return configured
207
+ return normalizeSources(store.sources)
208
+ }
209
+
210
+ /**
211
+ * 本机 Web 服务根地址;服务尚未 listen 时返回空串。
212
+ * @returns {string} 例如 `http://127.0.0.1:3080`。
213
+ */
214
+ function origin() {
215
+ try {
216
+ return webService?.getOrigin?.() ?? ''
217
+ } catch {
218
+ return ''
219
+ }
220
+ }
221
+
222
+ /**
223
+ * 通过 Settings 服务写本插件自己的配置字段。
224
+ * @param {Record<string, unknown>} patch - 要写入的字段。
225
+ * @returns {Promise<boolean>} 是否写入成功。
226
+ */
227
+ async function writeConfig(patch) {
228
+ const settings = ctx.get('settings')
229
+ if (settings === undefined || entryId === undefined) return false
230
+ try {
231
+ const descriptors = settings.describe()
232
+ const descriptor = Array.isArray(descriptors) ? descriptors.find(item => item?.ns === entryId) : undefined
233
+ const ops = Object.entries(patch).map(([key, value]) => ({ op: 'set', path: [key], value }))
234
+ if (ops.length === 0) return true
235
+ await settings.mutate(entryId, ops, descriptor?.revision)
236
+ return true
237
+ } catch (error) {
238
+ logger.warn(`保存配置失败:${messageOf(error)}`)
239
+ return false
240
+ }
241
+ }
242
+
243
+ /**
244
+ * 当前每个源的展示状态。
245
+ * @returns {object[]} 状态数组。
246
+ */
247
+ function sourceStatuses() {
248
+ const base = origin()
249
+ const hours = Number(live(config.refreshIntervalHours, 4))
250
+ const intervalMs = hours * 3600_000
251
+ return effectiveSources().map((url) => {
252
+ const id = sourceId(url)
253
+ const entry = store.entry(id)
254
+ const hasBody = store.hasBody(id)
255
+ const refreshing = inflight.has(id)
256
+ const ageMs = typeof entry?.fetchedAt === 'number' ? Date.now() - entry.fetchedAt : undefined
257
+ /** @type {'ok'|'stale'|'empty'|'error'} */
258
+ let state
259
+ if (!hasBody) state = 'empty'
260
+ else if (entry?.error) state = 'error'
261
+ else if (ageMs !== undefined && intervalMs > 0 && ageMs > intervalMs) state = 'stale'
262
+ else state = 'ok'
263
+ return {
264
+ id,
265
+ url,
266
+ mirrorUrl: base === '' ? '' : mirrorUrl(base, url),
267
+ state,
268
+ refreshing,
269
+ fetchedAt: entry?.fetchedAt ?? null,
270
+ ageMs: ageMs ?? null,
271
+ bytes: entry?.bytes ?? null,
272
+ plugins: entry?.plugins ?? null,
273
+ title: indexTitle(entry?.title),
274
+ error: entry?.error ?? null,
275
+ errorAt: entry?.errorAt ?? null,
276
+ }
277
+ })
278
+ }
279
+
280
+ /**
281
+ * 汇总状态(公开状态路由与设置页共用)。
282
+ * @returns {object} 状态对象。
283
+ */
284
+ function statusPayload() {
285
+ /** @type {string[]} */
286
+ let indexes = []
287
+ /** @type {{url: string, title: string, error: string|null}[]} */
288
+ let summaries = []
289
+ if (marketService !== undefined) {
290
+ try {
291
+ const listed = marketService.listIndexes()
292
+ indexes = listed.map((item) => item.url)
293
+ summaries = listed.map(item => ({ url: item.url, title: indexTitle(item.title), error: item.error ?? null }))
294
+ } catch {
295
+ indexes = []
296
+ summaries = []
297
+ }
298
+ }
299
+ return {
300
+ ok: true,
301
+ origin: origin(),
302
+ mirrorBase: origin() === '' ? '' : `${origin()}${MIRROR_PATH}`,
303
+ cacheDir,
304
+ entryId: entryId ?? null,
305
+ nextRefreshAt: nextRefreshAt || null,
306
+ config: {
307
+ autoRefresh: live(config.autoRefresh, true) !== false,
308
+ refreshIntervalHours: Number(live(config.refreshIntervalHours, 4)),
309
+ managePluginMarket: live(config.managePluginMarket, true) !== false,
310
+ fetchTimeoutMs: Number(config.fetchTimeoutMs ?? 120000),
311
+ maxBytes: Number(config.maxBytes ?? 64 * 1024 * 1024),
312
+ retries: Number(config.retries ?? 2),
313
+ },
314
+ sources: sourceStatuses(),
315
+ pluginMarket: {
316
+ available: marketService !== undefined,
317
+ managed: indexes.some(url => mirrorIdOf(url) !== undefined),
318
+ indexes,
319
+ summaries,
320
+ error: marketError,
321
+ },
322
+ writable: ctx.get('settings') !== undefined && entryId !== undefined,
323
+ }
324
+ }
325
+
326
+ /**
327
+ * 刷新一个源;同一源并发调用共享一次抓取。
328
+ * @param {string} url - 上游索引地址。
329
+ * @returns {Promise<unknown>} 抓取结果。
330
+ */
331
+ function refreshOne(url) {
332
+ const id = sourceId(url)
333
+ const running = inflight.get(id)
334
+ if (running !== undefined) return running
335
+ const promise = (async () => {
336
+ const startedAt = Date.now()
337
+ try {
338
+ const fetched = await fetchIndex(url, {
339
+ timeoutMs: Number(config.fetchTimeoutMs ?? 120000),
340
+ maxBytes: Number(config.maxBytes ?? 64 * 1024 * 1024),
341
+ retries: Number(config.retries ?? 2),
342
+ })
343
+ store.writeBody(id, fetched.bytes)
344
+ store.update(id, {
345
+ url,
346
+ fetchedAt: Date.now(),
347
+ bytes: fetched.bytes.byteLength,
348
+ plugins: fetched.plugins,
349
+ title: fetched.title,
350
+ error: null,
351
+ })
352
+ logger.info(`已缓存 ${url}`, { bytes: fetched.bytes.byteLength, plugins: fetched.plugins, ms: Date.now() - startedAt })
353
+ return fetched
354
+ } catch (error) {
355
+ store.update(id, { url, error: messageOf(error), errorAt: Date.now() })
356
+ logger.warn(`抓取失败 ${url}`, { error: messageOf(error) })
357
+ throw error
358
+ } finally {
359
+ store.save()
360
+ inflight.delete(id)
361
+ }
362
+ })()
363
+ inflight.set(id, promise)
364
+ return promise
365
+ }
366
+
367
+ /**
368
+ * 刷新若干源;不传 urls 时刷新全部。
369
+ * @param {{urls?: string[]}} [options] - 目标源。
370
+ * @returns {Promise<{url: string, ok: boolean, error?: string}[]>} 每个源的结果。
371
+ */
372
+ async function refreshMany(options = {}) {
373
+ const sources = effectiveSources()
374
+ const targets = options.urls === undefined ? sources : sources.filter(url => options.urls?.includes(url))
375
+ if (targets.length === 0) return []
376
+ const results = await Promise.allSettled(targets.map(url => refreshOne(url)))
377
+ await syncMarket()
378
+ return results.map((result, index) => ({
379
+ url: targets[index],
380
+ ok: result.status === 'fulfilled',
381
+ ...(result.status === 'rejected' ? { error: messageOf(result.reason) } : {}),
382
+ }))
383
+ }
384
+
385
+ /**
386
+ * 只刷新缺失或已过期的源(启动时用,避免每次启动都全量下载)。
387
+ * @returns {Promise<void>} 完成。
388
+ */
389
+ async function refreshDue() {
390
+ const hours = Number(live(config.refreshIntervalHours, 4))
391
+ const intervalMs = hours * 3600_000
392
+ const due = effectiveSources().filter((url) => {
393
+ const id = sourceId(url)
394
+ if (!store.hasBody(id)) return true
395
+ const fetchedAt = store.entry(id)?.fetchedAt
396
+ return typeof fetchedAt !== 'number' || Date.now() - fetchedAt > intervalMs
397
+ })
398
+ if (due.length > 0) await refreshMany({ urls: due })
399
+ }
400
+
401
+ /**
402
+ * 把「发现」页的索引源同步为本地镜像(只替换已缓存成功的源)。
403
+ * @param {boolean} [ensureAll] - 为 true 时把本插件清单里、发现页还没有的源补进去
404
+ * (在缓存插件页新增源时用)。
405
+ * @returns {Promise<void>} 完成。
406
+ */
407
+ async function syncMarket(ensureAll = false) {
408
+ if (marketService === undefined) return
409
+ if (live(config.managePluginMarket, true) === false) return
410
+ const base = origin()
411
+ if (base === '') return
412
+ try {
413
+ const current = marketService.listIndexes().map((item) => item.url)
414
+ const sources = effectiveSources()
415
+ const known = new Set(sources)
416
+ /** 已出现在发现页列表里的上游地址,避免 ensureAll 重复追加。 */
417
+ const seen = new Set()
418
+ /** @type {string[]} */
419
+ const desired = []
420
+ for (const url of current) {
421
+ const mirror = mirrorIdOf(url)
422
+ if (mirror !== undefined) {
423
+ const upstream = store.entry(mirror)?.url ?? sources.find(source => sourceId(source) === mirror)
424
+ // 镜像对应的源已经不存在(被移除或清单丢了):直接把它从列表里去掉,
425
+ // 而不是留下一个可能 404 的地址。
426
+ if (upstream === undefined) continue
427
+ seen.add(upstream)
428
+ if (known.has(upstream)) desired.push(store.hasBody(mirror) ? mirrorUrl(base, upstream) : upstream)
429
+ else desired.push(upstream)
430
+ continue
431
+ }
432
+ seen.add(url)
433
+ desired.push(known.has(url) && store.hasBody(sourceId(url)) ? mirrorUrl(base, url) : url)
434
+ }
435
+ if (ensureAll) {
436
+ for (const url of sources) {
437
+ if (seen.has(url)) continue
438
+ desired.push(store.hasBody(sourceId(url)) ? mirrorUrl(base, url) : url)
439
+ }
440
+ }
441
+ if (sameList(current, desired)) {
442
+ marketError = null
443
+ return
444
+ }
445
+ lastWrittenIndexes = desired.slice()
446
+ await marketService.setIndexes(desired)
447
+ marketError = null
448
+ logger.info('已更新「发现」页索引源', { indexes: desired })
449
+ } catch (error) {
450
+ marketError = messageOf(error)
451
+ logger.warn(`更新「发现」页索引源失败:${marketError}`)
452
+ }
453
+ }
454
+
455
+ /**
456
+ * 把「发现」页的索引源还原成上游地址。
457
+ * @returns {Promise<void>} 完成。
458
+ */
459
+ async function restoreMarket() {
460
+ if (marketService === undefined) return
461
+ try {
462
+ const current = marketService.listIndexes().map((item) => item.url)
463
+ const desired = current.map((url) => {
464
+ const mirror = mirrorIdOf(url)
465
+ if (mirror === undefined) return url
466
+ return store.entry(mirror)?.url ?? url
467
+ })
468
+ if (sameList(current, desired)) return
469
+ lastWrittenIndexes = desired.slice()
470
+ await marketService.setIndexes(desired)
471
+ marketError = null
472
+ logger.info('已还原「发现」页索引源', { indexes: desired })
473
+ } catch (error) {
474
+ marketError = messageOf(error)
475
+ logger.warn(`还原「发现」页索引源失败:${marketError}`)
476
+ }
477
+ }
478
+
479
+ /**
480
+ * 从「发现」页当前配置里接管还没有镜像的上游地址。
481
+ * @returns {Promise<void>} 完成。
482
+ */
483
+ async function adoptFromMarket() {
484
+ if (marketService === undefined) return
485
+ const configured = normalizeSources(live(config.sources, []))
486
+ if (configured.length > 0) return
487
+ const remembered = normalizeSources(store.sources)
488
+ if (remembered.length > 0) {
489
+ // 之前已经接管过:把上游清单补写进配置,避免缓存目录丢失后无法还原。
490
+ await writeConfig({ sources: remembered })
491
+ return
492
+ }
493
+ let current = []
494
+ try {
495
+ current = marketService.listIndexes().map((item) => item.url)
496
+ } catch {
497
+ return
498
+ }
499
+ const upstreams = current.filter(url => mirrorIdOf(url) === undefined)
500
+ const normalized = normalizeSources(upstreams)
501
+ if (normalized.length === 0) return
502
+ store.sources = normalized
503
+ store.save()
504
+ // 上游清单同时写进插件配置:即使缓存目录被清掉,也知道该回到哪些地址。
505
+ await writeConfig({ sources: normalized })
506
+ logger.info('已接管「发现」页索引源', { sources: normalized })
507
+ }
508
+
509
+ /**
510
+ * 把「发现」页上的增删同步回本插件的源清单。
511
+ *
512
+ * 用户在发现页自己加了一个原始索引地址 → 收进清单并立刻缓存,缓存成功后再换成镜像;
513
+ * 用户删掉一个镜像 → 对应上游也从清单和磁盘里移除。本插件自己写索引源时列表与
514
+ * `lastWrittenIndexes` 相同,直接跳过,避免来回抖动。
515
+ * @returns {Promise<void>} 完成。
516
+ */
517
+ async function reconcileFromMarket() {
518
+ if (marketService === undefined) return
519
+ let current = []
520
+ try {
521
+ current = marketService.listIndexes().map((item) => item.url)
522
+ } catch {
523
+ return
524
+ }
525
+ if (sameList(current, lastWrittenIndexes)) return
526
+ const previous = effectiveSources()
527
+ /** @type {string[]} */
528
+ const upstreams = []
529
+ for (const url of current) {
530
+ const mirror = mirrorIdOf(url)
531
+ if (mirror === undefined) {
532
+ upstreams.push(url)
533
+ continue
534
+ }
535
+ const upstream = store.entry(mirror)?.url ?? previous.find(source => sourceId(source) === mirror)
536
+ if (upstream !== undefined) upstreams.push(upstream)
537
+ }
538
+ const next = normalizeSources(upstreams)
539
+ const added = next.filter(url => !previous.includes(url))
540
+ const removed = previous.filter(url => !next.includes(url))
541
+ if (added.length === 0 && removed.length === 0) return
542
+ store.sources = next
543
+ for (const url of removed) store.remove(sourceId(url))
544
+ store.save()
545
+ await writeConfig({ sources: next })
546
+ if (added.length > 0) await refreshMany({ urls: added })
547
+ else await syncMarket()
548
+ logger.info('已同步「发现」页的索引源变更', { added, removed })
549
+ }
550
+
551
+ /** 重新安排下一次自动刷新。 */
552
+ function schedule() {
553
+ if (refreshTimer !== undefined) clearTimeout(refreshTimer)
554
+ refreshTimer = undefined
555
+ nextRefreshAt = 0
556
+ if (live(config.autoRefresh, true) === false) return
557
+ const hours = Number(live(config.refreshIntervalHours, 4))
558
+ if (!Number.isFinite(hours) || hours <= 0) return
559
+ const delay = Math.min(Math.max(hours * 3600_000, 60_000), MAX_INTERVAL_HOURS * 3600_000)
560
+ nextRefreshAt = Date.now() + delay
561
+ refreshTimer = setTimeout(() => {
562
+ void refreshMany().catch(error => logger.warn(`定时刷新失败:${messageOf(error)}`)).finally(schedule)
563
+ }, delay)
564
+ }
565
+
566
+ // --- 公开镜像路由(必须免登录:pluginMarket 在 Host 进程里裸 fetch)---------
567
+ ctx.inject(['webServer'], (webCtx) => {
568
+ webService = webCtx.webServer
569
+ webCtx.effect(() => webCtx.webServer.register({
570
+ kind: 'prefix',
571
+ path: MIRROR_PATH,
572
+ async handler(req, res) {
573
+ const method = req.method ?? 'GET'
574
+ if (method !== 'GET' && method !== 'HEAD') {
575
+ res.writeHead(405, { allow: 'GET, HEAD' })
576
+ res.end()
577
+ return
578
+ }
579
+ const pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname
580
+ const id = MIRROR_ID.exec(pathname)?.[1]
581
+ const body = id === undefined ? undefined : store.readBody(id)
582
+ if (body === undefined) {
583
+ const message = id === undefined ? 'unknown mirror id' : 'index is not cached yet'
584
+ res.writeHead(503, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
585
+ res.end(method === 'HEAD' ? undefined : JSON.stringify({ error: message }))
586
+ return
587
+ }
588
+ res.writeHead(200, {
589
+ 'content-type': 'application/json; charset=utf-8',
590
+ 'content-length': String(body.byteLength),
591
+ 'cache-control': 'no-store',
592
+ 'x-pluginmarket-plus': 'cached',
593
+ })
594
+ res.end(method === 'HEAD' ? undefined : body)
595
+ },
596
+ }), 'dsh-pluginmarket-plus: mirror route')
597
+
598
+ webCtx.effect(() => webCtx.webServer.register({
599
+ kind: 'exact',
600
+ path: PUBLIC_STATUS_PATH,
601
+ async handler(req, res) {
602
+ const body = JSON.stringify(statusPayload())
603
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'content-length': String(Buffer.byteLength(body)) })
604
+ res.end(req.method === 'HEAD' ? undefined : body)
605
+ },
606
+ }), 'dsh-pluginmarket-plus: status route')
607
+ })
608
+
609
+ // --- 设置页 API(经 connection,只有 owner 浏览器能访问)-------------------
610
+ ctx.inject(['connection'], (connCtx) => {
611
+ /**
612
+ * @param {string} path - `/api/...` 路径。
613
+ * @param {('GET'|'POST')[]} methods - 允许的方法。
614
+ * @param {(request: Request) => Promise<Response>} fetch - 处理函数。
615
+ */
616
+ const route = (path, methods, handler) => {
617
+ connCtx.effect(() => connCtx.connection.fetch.register({
618
+ path,
619
+ methods,
620
+ requestBody: 'buffered',
621
+ fetch: handler,
622
+ }), `dsh-pluginmarket-plus: ${path}`)
623
+ }
624
+
625
+ route(`${API_PREFIX}/status`, ['GET'], async () => jsonResponse(statusPayload()))
626
+
627
+ route(`${API_PREFIX}/refresh`, ['POST'], async (request) => {
628
+ try {
629
+ const body = await readJsonBody(request)
630
+ const url = typeof body.url === 'string' ? body.url : undefined
631
+ if (url !== undefined && !effectiveSources().includes(url)) {
632
+ return jsonResponse({ ok: false, error: 'unknown-source', message: `未配置的源:${url}` }, 400)
633
+ }
634
+ const results = await refreshMany(url === undefined ? {} : { urls: [url] })
635
+ return jsonResponse({ ok: true, results, status: statusPayload() })
636
+ } catch (error) {
637
+ return jsonResponse({ ok: false, error: 'refresh-failed', message: messageOf(error) }, 500)
638
+ }
639
+ })
640
+
641
+ route(`${API_PREFIX}/settings`, ['POST'], async (request) => {
642
+ try {
643
+ const body = await readJsonBody(request)
644
+ /** @type {Record<string, unknown>} */
645
+ const patch = {}
646
+ /** @type {string[]} */
647
+ let added = []
648
+ if (typeof body.autoRefresh === 'boolean') patch.autoRefresh = body.autoRefresh
649
+ if (body.refreshIntervalHours !== undefined) {
650
+ const hours = Number(body.refreshIntervalHours)
651
+ if (!Number.isFinite(hours) || hours < 0.25 || hours > MAX_INTERVAL_HOURS) {
652
+ return jsonResponse({ ok: false, error: 'invalid-interval', message: '刷新间隔需在 0.25–168 小时之间' }, 400)
653
+ }
654
+ patch.refreshIntervalHours = hours
655
+ }
656
+ if (typeof body.managePluginMarket === 'boolean') patch.managePluginMarket = body.managePluginMarket
657
+ if (body.sources !== undefined) {
658
+ const next = normalizeSources(body.sources)
659
+ const previous = effectiveSources()
660
+ const removed = previous.filter(url => !next.includes(url))
661
+ added = next.filter(url => !previous.includes(url))
662
+ store.sources = next
663
+ for (const url of removed) store.remove(sourceId(url))
664
+ store.save()
665
+ patch.sources = next
666
+ }
667
+ const saved = await writeConfig(patch)
668
+ if (added.length > 0) await refreshMany({ urls: added })
669
+ if (patch.managePluginMarket === false) await restoreMarket()
670
+ else if (patch.managePluginMarket === true || patch.sources !== undefined) await syncMarket(patch.sources !== undefined)
671
+ schedule()
672
+ return jsonResponse({ ok: true, saved, status: statusPayload() })
673
+ } catch (error) {
674
+ return jsonResponse({ ok: false, error: 'settings-failed', message: messageOf(error) }, 500)
675
+ }
676
+ })
677
+
678
+ route(`${API_PREFIX}/market`, ['POST'], async (request) => {
679
+ try {
680
+ const body = await readJsonBody(request)
681
+ const action = typeof body.action === 'string' ? body.action : 'apply'
682
+ if (action === 'restore') await restoreMarket()
683
+ else await syncMarket(true)
684
+ return jsonResponse({ ok: true, status: statusPayload() })
685
+ } catch (error) {
686
+ return jsonResponse({ ok: false, error: 'market-failed', message: messageOf(error) }, 500)
687
+ }
688
+ })
689
+ })
690
+
691
+ // --- 发现页服务:接管已有索引源、首次补缓存、定时刷新 ----------------------
692
+ ctx.inject(['pluginMarket'], (marketCtx) => {
693
+ marketService = marketCtx.pluginMarket
694
+ void (async () => {
695
+ await adoptFromMarket()
696
+ await reconcileFromMarket()
697
+ await syncMarket()
698
+ await refreshDue()
699
+ schedule()
700
+ })().catch(error => logger.warn(`接管「发现」页索引源失败:${messageOf(error)}`))
701
+ })
702
+
703
+ // 用户在「发现 → 索引源」里增删时,跟随同步(防抖,忽略本插件自己的写入)。
704
+ ctx.on('plugin-market/changed', () => {
705
+ if (marketChangeTimer !== undefined) clearTimeout(marketChangeTimer)
706
+ marketChangeTimer = setTimeout(() => {
707
+ marketChangeTimer = undefined
708
+ void reconcileFromMarket().catch(error => logger.warn(`同步索引源失败:${messageOf(error)}`))
709
+ }, 600)
710
+ })
711
+
712
+ // 启动后补一次缺失/过期的缓存;此时 Web 服务与插件市场服务都已就位。
713
+ bootTimer = setTimeout(() => {
714
+ void refreshDue()
715
+ .catch(error => logger.warn(`启动刷新失败:${messageOf(error)}`))
716
+ .finally(schedule)
717
+ }, 2000)
718
+
719
+ // 配置热更新后重新排期。
720
+ ctx.on('loader/volatile-update', () => {
721
+ schedule()
722
+ })
723
+
724
+ ctx.effect(() => () => {
725
+ if (refreshTimer !== undefined) clearTimeout(refreshTimer)
726
+ if (bootTimer !== undefined) clearTimeout(bootTimer)
727
+ if (marketChangeTimer !== undefined) clearTimeout(marketChangeTimer)
728
+ // 卸载/停用时尽量把「发现」页的索引源还原成上游地址,避免留下指向已消失
729
+ // 本地镜像的死链。失败也不影响卸载。
730
+ if (live(config.managePluginMarket, true) !== false) {
731
+ try {
732
+ const current = marketService?.listIndexes?.().map((item) => item.url) ?? []
733
+ if (current.some(url => mirrorIdOf(url) !== undefined)) void restoreMarket()
734
+ } catch {
735
+ // 服务已先一步销毁时忽略。
736
+ }
737
+ }
738
+ }, 'dsh-pluginmarket-plus: timers')
739
+ }