dsh-plugin-update-hub 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/client.js ADDED
@@ -0,0 +1,957 @@
1
+ window.__ModuleLoader__.load((() => {
2
+ const strip = (value) => String(value || '').replace(/\/+$/, '')
3
+ const fromPath = (path) => {
4
+ const match = /^(.*?)\/plugins\//.exec(String(path || ''))
5
+ return match ? strip(match[1]) : null
6
+ }
7
+ const detectAppBase = (doc, href) => {
8
+ if (!doc) return ''
9
+ try {
10
+ const src = doc.currentScript && doc.currentScript.src
11
+ if (src) {
12
+ const base = fromPath(new URL(src, doc.baseURI || href).pathname)
13
+ if (base !== null) return base
14
+ }
15
+ } catch (error) { /* ignore */ }
16
+ try {
17
+ for (const el of doc.querySelectorAll('script[src]')) {
18
+ const base = fromPath(new URL(el.src, doc.baseURI || href).pathname)
19
+ if (base !== null) return base
20
+ }
21
+ } catch (error) { /* ignore */ }
22
+ try {
23
+ const path = new URL(doc.baseURI).pathname
24
+ if (path.endsWith('/')) return strip(path)
25
+ } catch (error) { /* ignore */ }
26
+ return ''
27
+ }
28
+ const APP_BASE = detectAppBase(typeof document === 'undefined' ? null : document, typeof location === 'undefined' ? '' : location.href)
29
+ const absAppPath = (value) => {
30
+ const path = String(value == null ? '' : value)
31
+ if (!path || path[0] !== '/' || path[1] === '/') return path
32
+ if (!APP_BASE || path === APP_BASE || path.indexOf(APP_BASE + '/') === 0) return path
33
+ return APP_BASE + path
34
+ }
35
+
36
+ return {
37
+ id: 'dsh-plugin-update-hub',
38
+ factory: (require) => {
39
+ var module = { exports: {} }
40
+ var exports = module.exports
41
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
42
+
43
+ const React = require('react')
44
+ const h = React.createElement
45
+
46
+ const STYLE_OWNER_ID = 'dsh-plugin-update-hub'
47
+ const API = '/dsh-plugin-update-hub-api'
48
+ const PREF_KEY = 'dsh-plugin-update-hub:prefs'
49
+ const CHECK_KEY = 'dsh-plugin-update-hub:last-check'
50
+ const AUTO_CHECK_AFTER = 6 * 60 * 60 * 1000
51
+ const STEP_PERCENT = { checking: 12, removing: 38, installing: 72, restoring: 88, applied: 100, failed: 100 }
52
+ const STEP_LABEL = { checking: '正在校验目标版本', removing: '正在移除当前版本', installing: '正在安装新版本', restoring: '目标版本不可用,正在回滚', applied: '更新完成', failed: '更新失败' }
53
+
54
+ const CSS = `
55
+ .dpu-root { display: flex; flex-direction: column; gap: 12px; padding: 4px 0 8px; font-size: 13px; color: var(--dsw-alias-label-primary); }
56
+ .dpu-head { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; justify-content: space-between; }
57
+ .dpu-head-main { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
58
+ .dpu-head-title { font-size: 14px; font-weight: 600; }
59
+ .dpu-head-sub { font-size: 12px; color: var(--dsw-alias-label-secondary); }
60
+ .dpu-toolbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
61
+ .dpu-input { width: 200px; box-sizing: border-box; padding: 5px 9px; font-size: 13px; color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-layer-1); border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; outline: none; }
62
+ .dpu-input::placeholder { color: var(--dsw-alias-label-secondary); }
63
+ .dpu-input:focus { border-color: var(--dsw-alias-brand-primary); }
64
+ .dpu-select { padding: 4px 6px; font-size: 12px; color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-layer-2); border: 1px solid var(--dsw-alias-border-l1); border-radius: 7px; outline: none; }
65
+ .dpu-check { display: inline-flex; gap: 5px; align-items: center; font-size: 12px; color: var(--dsw-alias-label-secondary); cursor: pointer; user-select: none; }
66
+ .dpu-check input { margin: 0; accent-color: var(--dsw-alias-brand-primary); }
67
+ .dpu-btn { display: inline-flex; align-items: center; gap: 5px; padding: 5px 11px; font-size: 13px; color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-layer-2); border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; cursor: pointer; white-space: nowrap; }
68
+ .dpu-btn:hover:not(:disabled) { border-color: var(--dsw-alias-border-l2); background: var(--dsw-alias-bg-layer-1); }
69
+ .dpu-btn:disabled { opacity: 0.5; cursor: default; }
70
+ .dpu-btn-primary { color: #ffffff; background: var(--dsw-alias-brand-primary); border-color: var(--dsw-alias-brand-primary); }
71
+ .dpu-btn-primary:hover:not(:disabled) { background: var(--dsw-alias-brand-primary); border-color: var(--dsw-alias-brand-primary); opacity: 0.92; }
72
+ .dpu-btn-ghost { background: transparent; }
73
+ .dpu-notice { display: flex; gap: 8px; align-items: flex-start; padding: 8px 10px; font-size: 12px; border-radius: 8px; background: var(--dsw-alias-bg-layer-2); border: 1px solid var(--dsw-alias-border-l1); color: var(--dsw-alias-label-secondary); }
74
+ .dpu-notice-error { color: var(--dsw-alias-state-error-primary); border-color: var(--dsw-alias-state-error-primary); }
75
+ .dpu-notice-text { flex: 1; min-width: 0; word-break: break-word; }
76
+ .dpu-empty { padding: 28px 12px; text-align: center; font-size: 12px; color: var(--dsw-alias-label-secondary); border: 1px dashed var(--dsw-alias-border-l1); border-radius: 10px; }
77
+ .dpu-list { display: flex; flex-direction: column; gap: 8px; }
78
+ .dpu-row { display: flex; flex-direction: column; gap: 6px; padding: 10px 12px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 10px; background: var(--dsw-alias-bg-layer-1); }
79
+ .dpu-row-outdated { border-color: var(--dsw-alias-state-warn-primary); }
80
+ .dpu-row-head { display: flex; gap: 10px; align-items: flex-start; justify-content: space-between; }
81
+ .dpu-row-title { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; min-width: 0; }
82
+ .dpu-title { font-size: 13px; font-weight: 600; }
83
+ .dpu-row-actions { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; flex: none; }
84
+ .dpu-name { font-size: 11px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--dsw-alias-label-secondary); }
85
+ .dpu-desc { font-size: 12px; line-height: 1.5; color: var(--dsw-alias-label-secondary); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
86
+ .dpu-meta { display: flex; flex-wrap: wrap; gap: 12px; font-size: 11px; color: var(--dsw-alias-label-secondary); }
87
+ .dpu-meta b { font-weight: 600; color: var(--dsw-alias-label-primary); }
88
+ .dpu-tag { padding: 0 7px; font-size: 11px; line-height: 18px; border-radius: 999px; border: 1px solid transparent; white-space: nowrap; }
89
+ .dpu-tag-warn { color: var(--dsw-alias-state-warn-primary); border-color: var(--dsw-alias-state-warn-primary); }
90
+ .dpu-tag-error { color: var(--dsw-alias-state-error-primary); border-color: var(--dsw-alias-state-error-primary); }
91
+ .dpu-tag-success { color: var(--dsw-alias-state-success-primary); border-color: var(--dsw-alias-state-success-primary); }
92
+ .dpu-tag-muted { color: var(--dsw-alias-label-secondary); border-color: var(--dsw-alias-border-l1); }
93
+ .dpu-progress { display: flex; flex-direction: column; gap: 4px; }
94
+ .dpu-progress-track { height: 4px; border-radius: 999px; background: var(--dsw-alias-bg-layer-2); overflow: hidden; }
95
+ .dpu-progress-bar { height: 100%; border-radius: 999px; background: var(--dsw-alias-brand-primary); transition: width 0.35s ease; }
96
+ .dpu-progress-bar-failed { background: var(--dsw-alias-state-error-primary); }
97
+ .dpu-progress-bar-done { background: var(--dsw-alias-state-success-primary); }
98
+ .dpu-progress-text { display: flex; gap: 8px; font-size: 11px; color: var(--dsw-alias-label-secondary); }
99
+ .dpu-error { font-size: 11px; color: var(--dsw-alias-state-error-primary); word-break: break-word; }
100
+ .dpu-queue { display: flex; flex-direction: column; gap: 6px; padding: 8px 10px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 10px; background: var(--dsw-alias-bg-layer-2); }
101
+ .dpu-queue-head { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; }
102
+ .dpu-queue-toggle { display: inline-flex; gap: 6px; align-items: center; padding: 0; font: inherit; color: inherit; background: transparent; border: 0; cursor: pointer; }
103
+ .dpu-chevron { font-size: 10px; color: var(--dsw-alias-label-secondary); }
104
+ .dpu-queue-title { font-size: 12px; font-weight: 600; }
105
+ .dpu-queue-percent { font-size: 11px; color: var(--dsw-alias-label-secondary); }
106
+ .dpu-queue-track { margin-top: 2px; }
107
+ .dpu-queue-actions { display: flex; gap: 6px; }
108
+ .dpu-task { display: flex; flex-direction: column; gap: 4px; padding: 6px 8px; border-radius: 8px; background: var(--dsw-alias-bg-layer-1); border: 1px solid var(--dsw-alias-border-l1); }
109
+ .dpu-task-head { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
110
+ .dpu-task-title { font-size: 12px; font-weight: 600; }
111
+ .dpu-task-version { font-size: 11px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--dsw-alias-label-secondary); }
112
+ .dpu-foot { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; padding-top: 4px; font-size: 12px; color: var(--dsw-alias-label-secondary); }
113
+ .dpu-pager { display: flex; gap: 6px; align-items: center; }
114
+ `
115
+
116
+ function createOwnedStyle(css) {
117
+ const el = document.createElement('style')
118
+ el.setAttribute('data-plugin', STYLE_OWNER_ID)
119
+ el.textContent = css
120
+ document.head.appendChild(el)
121
+ return el
122
+ }
123
+
124
+ function readPrefs() {
125
+ try {
126
+ const raw = localStorage.getItem(PREF_KEY)
127
+ const parsed = raw ? JSON.parse(raw) : null
128
+ const pageSize = parsed && parsed.pageSize
129
+ return {
130
+ pageSize: pageSize === 10 || pageSize === 50 ? pageSize : 20,
131
+ showOfficial: !!(parsed && parsed.showOfficial),
132
+ }
133
+ } catch (error) {
134
+ return { pageSize: 20, showOfficial: false }
135
+ }
136
+ }
137
+
138
+ function writePrefs(patch) {
139
+ try {
140
+ const next = Object.assign({}, readPrefs(), patch)
141
+ localStorage.setItem(PREF_KEY, JSON.stringify(next))
142
+ } catch (error) { /* ignore */ }
143
+ }
144
+
145
+ function messageOf(error) {
146
+ if (error === null || error === undefined) return '未知错误'
147
+ if (typeof error === 'string') return error
148
+ const code = error.code
149
+ const message = error.message
150
+ if (message && code && String(message).indexOf(String(code)) === -1) return String(message) + ' (' + String(code) + ')'
151
+ return String(message || code || error)
152
+ }
153
+
154
+ function localized(value) {
155
+ if (value === null || value === undefined) return ''
156
+ if (typeof value === 'string') return value
157
+ if (typeof value !== 'object') return String(value)
158
+ for (const key of ['zh-CN', 'zh', 'en', 'default']) {
159
+ const text = value[key]
160
+ if (typeof text === 'string' && text) return text
161
+ }
162
+ for (const key of Object.keys(value)) {
163
+ if (typeof value[key] === 'string' && value[key]) return value[key]
164
+ }
165
+ return ''
166
+ }
167
+
168
+ const pad = (value) => String(value).padStart(2, '0')
169
+
170
+ function formatTime(ms) {
171
+ if (!ms) return '—'
172
+ const date = new Date(ms)
173
+ if (Number.isNaN(date.getTime())) return '—'
174
+ return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes())
175
+ }
176
+
177
+ function elapsedText(startedAt) {
178
+ const seconds = Math.max(0, Math.round((Date.now() - startedAt) / 1000))
179
+ return seconds < 60 ? String(seconds) + ' 秒' : Math.floor(seconds / 60) + ' 分 ' + (seconds % 60) + ' 秒'
180
+ }
181
+
182
+ function toRow(bundle, extra) {
183
+ const meta = bundle.meta || {}
184
+ const info = (extra && extra.info) || {}
185
+ const name = String(bundle.name)
186
+ const target = bundle.installTarget || {}
187
+ return {
188
+ name,
189
+ title: localized(meta.title) || name,
190
+ description: localized(meta.description) || info.description || localized(bundle.description) || '',
191
+ version: bundle.version || target.version || info.version || '',
192
+ installedAt: (extra && extra.installedAt) || 0,
193
+ official: bundle.official === true,
194
+ updatable: bundle.update === 'registry',
195
+ git: bundle.update === 'git',
196
+ enabled: bundle.enabled !== false,
197
+ availability: bundle.availability,
198
+ check: null,
199
+ }
200
+ }
201
+
202
+ function statusOf(row) {
203
+ if (row.official) return { tone: 'muted', text: '内置插件,随 DSH 发行' }
204
+ if (row.git) return { tone: 'muted', text: 'Git 安装,不支持版本升级' }
205
+ if (!row.updatable) return { tone: 'muted', text: '不可检查更新' }
206
+ const check = row.check
207
+ if (!check) return { tone: 'muted', text: '未检查' }
208
+ if (check.state === 'checking') return { tone: 'muted', text: '检查中…' }
209
+ if (check.state === 'waiting') return { tone: 'muted', text: '等待检查…' }
210
+ if (check.state === 'error') return { tone: 'error', text: '检查失败' }
211
+ if (check.state === 'missing') return { tone: 'muted', text: '市场未收录' }
212
+ if (check.state === 'n/a') return { tone: 'muted', text: '不支持版本升级' }
213
+ if (check.state === 'done') {
214
+ if (check.versions.length > 0) return { tone: 'warn', text: '落后 ' + check.versions.length + ' 个版本' }
215
+ return { tone: 'success', text: '已是最新' }
216
+ }
217
+ return { tone: 'muted', text: '未检查' }
218
+ }
219
+
220
+ function rankOf(row) {
221
+ if (row.official) return 3
222
+ const check = row.check
223
+ if (check && check.state === 'done' && check.versions.length > 0) return 0
224
+ if (!row.updatable) return 2
225
+ return 1
226
+ }
227
+
228
+ const store = {
229
+ phase: 'idle',
230
+ error: '',
231
+ rows: [],
232
+ checking: false,
233
+ checkProgress: null,
234
+ checkedAt: 0,
235
+ notice: '',
236
+ /**
237
+ * Updates run one at a time through this queue. Finished tasks keep a
238
+ * terminal state so the panel can report what happened, and the queue
239
+ * only ever lives in memory: when DSH goes away, every queued task goes
240
+ * with it instead of resuming on the next launch.
241
+ */
242
+ queue: [],
243
+ }
244
+
245
+ let queueSeq = 0
246
+ const concurrency = { limit: 0, ceiling: 0, latency: 0 }
247
+
248
+ function coreLimit() {
249
+ const cores = Number(typeof navigator !== 'undefined' && navigator.hardwareConcurrency) || 4
250
+ const memory = Number(typeof navigator !== 'undefined' && navigator.deviceMemory) || 4
251
+ const base = cores >= 8 && memory >= 8 ? 4 : cores >= 4 ? 3 : 2
252
+ return Math.max(1, Math.min(4, base))
253
+ }
254
+
255
+ /** How many version checks may run at once, given what the last ones cost. */
256
+ function checkLimit() {
257
+ if (concurrency.limit === 0) {
258
+ concurrency.ceiling = coreLimit()
259
+ concurrency.limit = concurrency.ceiling
260
+ }
261
+ return concurrency.limit
262
+ }
263
+
264
+ function adaptConcurrency(latency) {
265
+ concurrency.latency = concurrency.latency === 0 ? latency : Math.round(concurrency.latency * 0.6 + latency * 0.4)
266
+ if (concurrency.latency > 1500) concurrency.limit = Math.max(1, concurrency.limit - 1)
267
+ else if (concurrency.latency < 400 && concurrency.limit < concurrency.ceiling) concurrency.limit += 1
268
+ }
269
+
270
+ function runningTask() {
271
+ for (const task of store.queue) if (task.status === 'running') return task
272
+ return null
273
+ }
274
+
275
+ function isUpdating() {
276
+ return runningTask() !== null
277
+ }
278
+
279
+ /** The queued or running task for one package, if any. */
280
+ function taskOf(name) {
281
+ for (const task of store.queue) {
282
+ if (task.name === name && (task.status === 'running' || task.status === 'queued')) return task
283
+ }
284
+ return null
285
+ }
286
+
287
+ function taskStatusText(task) {
288
+ if (task.status === 'queued') return '等待更新…'
289
+ if (task.status === 'running') return STEP_LABEL[task.step] || '更新中…'
290
+ if (task.status === 'done') return '已完成'
291
+ if (task.status === 'cancelled') return '已取消'
292
+ return '失败'
293
+ }
294
+
295
+ function taskTagTone(task) {
296
+ if (task.status === 'done') return 'dpu-tag-success'
297
+ if (task.status === 'failed' || task.status === 'cancelled') return 'dpu-tag-error'
298
+ if (task.status === 'running') return 'dpu-tag-warn'
299
+ return 'dpu-tag-muted'
300
+ }
301
+
302
+ function queueSummary() {
303
+ const counts = { queued: 0, running: 0, done: 0, failed: 0, cancelled: 0 }
304
+ for (const task of store.queue) counts[task.status] = (counts[task.status] || 0) + 1
305
+ const parts = []
306
+ if (counts.running) parts.push(counts.running + ' 个更新中')
307
+ if (counts.queued) parts.push(counts.queued + ' 个排队中')
308
+ if (counts.done) parts.push(counts.done + ' 个已完成')
309
+ if (counts.failed || counts.cancelled) parts.push((counts.failed + counts.cancelled) + ' 个失败')
310
+ return parts.join(' · ')
311
+ }
312
+
313
+ let revision = 0
314
+ const listeners = new Set()
315
+ let appCtx = null
316
+ let remote = null
317
+ let booted = false
318
+
319
+ function emit() {
320
+ revision += 1
321
+ for (const listener of Array.from(listeners)) {
322
+ try { listener() } catch (error) { /* ignore */ }
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Remote invocations resolve to a result envelope, never to a rejection:
328
+ * `{ok: true, value}` or `{ok: false, error}`. Turn a failure into a throw
329
+ * so call sites can keep ordinary try/catch shape.
330
+ */
331
+ function unwrap(result) {
332
+ if (result && typeof result === 'object' && typeof result.ok === 'boolean') {
333
+ if (result.ok) return result.value
334
+ const error = result.error || {}
335
+ const failure = new Error(error.message || ('远程调用失败:' + (error.code || 'unknown')))
336
+ failure.code = error.code
337
+ failure.details = error.details
338
+ throw failure
339
+ }
340
+ return result
341
+ }
342
+
343
+ function remoteService() {
344
+ if (remote) return remote
345
+ if (!appCtx) return null
346
+ try {
347
+ const found = appCtx.get('remote')
348
+ if (found) { remote = found; return remote }
349
+ } catch (error) { /* ignore */ }
350
+ return null
351
+ }
352
+
353
+ function manager() {
354
+ if (!appCtx) return null
355
+ try {
356
+ const scoped = appCtx.get('remote.pluginManager')
357
+ if (scoped) return scoped
358
+ } catch (error) { /* ignore */ }
359
+ const service = remoteService()
360
+ if (service && service.pluginManager && typeof service.pluginManager.listBundles === 'function') {
361
+ return service.pluginManager
362
+ }
363
+ return null
364
+ }
365
+
366
+ async function fetchInventory(names) {
367
+ const empty = { installedAt: {}, info: {} }
368
+ if (!names.length) return empty
369
+ try {
370
+ const url = absAppPath(API) + '?names=' + encodeURIComponent(names.join(','))
371
+ const response = await fetch(url, { headers: { accept: 'application/json' } })
372
+ if (!response.ok) return empty
373
+ const body = await response.json()
374
+ if (!body || typeof body !== 'object') return empty
375
+ return { installedAt: body.installedAt || {}, info: body.info || {} }
376
+ } catch (error) {
377
+ return empty
378
+ }
379
+ }
380
+
381
+ async function loadBundles() {
382
+ const pm = manager()
383
+ if (!pm) throw new Error('插件管理器尚未加载')
384
+ const bundles = unwrap(await pm.listBundles())
385
+ const visible = (bundles || []).filter((bundle) => bundle && bundle.installed !== false && bundle.availability !== 'missing')
386
+ const inventory = await fetchInventory(visible.filter((bundle) => !bundle.official).map((bundle) => String(bundle.name)))
387
+ const previous = new Map(store.rows.map((row) => [row.name, row]))
388
+ store.rows = visible.map((bundle) => {
389
+ const name = String(bundle.name)
390
+ const row = toRow(bundle, {
391
+ installedAt: inventory.installedAt[name],
392
+ info: inventory.info[name],
393
+ })
394
+ const old = previous.get(row.name)
395
+ if (old && old.version === row.version && old.check) row.check = old.check
396
+ return row
397
+ })
398
+ }
399
+
400
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
401
+
402
+ function rememberCheck() {
403
+ try { localStorage.setItem(CHECK_KEY, String(store.checkedAt)) } catch (error) { /* ignore */ }
404
+ }
405
+
406
+ /**
407
+ * Check every updatable row at once, a few in parallel. Rows waiting for a
408
+ * free slot say 等待检查…, running ones 检查中…; the fan-out follows the
409
+ * machine's size and shrinks by itself when answers come back slowly.
410
+ */
411
+ async function checkAll(options) {
412
+ const pm = manager()
413
+ if (!pm || store.checking) return
414
+ const force = !!(options && options.force)
415
+ const queue = store.rows.filter((row) => {
416
+ if (!row.updatable) return false
417
+ if (force) return true
418
+ return !(row.check && row.check.state === 'done' && row.check.installed === row.version)
419
+ })
420
+ if (!queue.length) {
421
+ store.checkedAt = Date.now()
422
+ rememberCheck()
423
+ emit()
424
+ return
425
+ }
426
+ store.checking = true
427
+ store.error = ''
428
+ store.checkProgress = { total: queue.length, done: 0 }
429
+ for (const row of queue) row.check = { state: 'waiting', versions: [], installed: row.version }
430
+ emit()
431
+
432
+ let cursor = 0
433
+ let active = 0
434
+ await new Promise((resolve) => {
435
+ const pump = () => {
436
+ while (active < Math.min(checkLimit(), queue.length) && cursor < queue.length) {
437
+ const row = queue[cursor]
438
+ cursor += 1
439
+ active += 1
440
+ row.check = { state: 'checking', versions: [], installed: row.version }
441
+ emit()
442
+ const startedAt = Date.now()
443
+ let pending
444
+ try { pending = pm.listVersions(row.name, {}) } catch (error) { pending = Promise.reject(error) }
445
+ Promise.resolve(pending).then((result) => {
446
+ row.check = interpretVersions(unwrap(result), row.version)
447
+ }, (error) => {
448
+ row.check = { state: 'error', versions: [], error: messageOf(error) }
449
+ }).then(() => {
450
+ adaptConcurrency(Date.now() - startedAt)
451
+ active -= 1
452
+ store.checkProgress.done += 1
453
+ emit()
454
+ pump()
455
+ })
456
+ }
457
+ if (active === 0 && cursor >= queue.length) resolve()
458
+ }
459
+ pump()
460
+ })
461
+
462
+ store.checking = false
463
+ store.checkProgress = null
464
+ store.checkedAt = Date.now()
465
+ rememberCheck()
466
+ emit()
467
+ }
468
+
469
+ function interpretVersions(answer, installed) {
470
+ if (!answer) return { state: 'error', versions: [], error: '没有收到响应' }
471
+ if (answer.status === 'refused') {
472
+ const problem = answer.problem
473
+ const state = problem === 'not-updatable' ? 'n/a' : problem === 'not-found' ? 'missing' : 'error'
474
+ return { state, versions: [], error: answer.reason || problem || '' }
475
+ }
476
+ const versions = (answer.versions || []).map((entry) => ({
477
+ version: entry.version,
478
+ prerelease: entry.prerelease === true,
479
+ deprecated: entry.deprecated ? localized(entry.deprecated) : '',
480
+ incompatible: entry.incompatible ? (entry.incompatible.requirements || {}) : null,
481
+ }))
482
+ return { state: 'done', versions, installed: answer.installed || installed, omitted: answer.omitted || 0 }
483
+ }
484
+
485
+ async function bootstrap() {
486
+ if (booted) return
487
+ booted = true
488
+ store.phase = 'loading'
489
+ emit()
490
+ try {
491
+ await loadBundles()
492
+ store.phase = 'ready'
493
+ emit()
494
+ } catch (error) {
495
+ store.phase = 'error'
496
+ store.error = messageOf(error)
497
+ emit()
498
+ booted = false
499
+ return
500
+ }
501
+ const last = Number((() => { try { return localStorage.getItem(CHECK_KEY) || '0' } catch (error) { return '0' } })())
502
+ if (Date.now() - last > AUTO_CHECK_AFTER) {
503
+ await sleep(1200)
504
+ await checkAll()
505
+ }
506
+ }
507
+
508
+ /**
509
+ * Queue bundle updates. Each task captures the version the user picked now,
510
+ * so a registry that moves on while the task waits cannot change it.
511
+ */
512
+ function enqueueUpdates(entries) {
513
+ if (!entries || !entries.length) return
514
+ const pending = new Set(store.queue
515
+ .filter((task) => task.status === 'queued' || task.status === 'running')
516
+ .map((task) => task.name))
517
+ let added = 0
518
+ for (const entry of entries) {
519
+ if (!entry || !entry.name || !entry.version || pending.has(entry.name)) continue
520
+ pending.add(entry.name)
521
+ queueSeq += 1
522
+ store.queue.push({
523
+ id: 'task-' + queueSeq,
524
+ requestId: 'updates-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8),
525
+ name: entry.name,
526
+ title: entry.title || entry.name,
527
+ version: entry.version,
528
+ status: 'queued',
529
+ step: 'checking',
530
+ percent: 0,
531
+ startedAt: 0,
532
+ finishedAt: 0,
533
+ error: '',
534
+ log: '',
535
+ })
536
+ added += 1
537
+ }
538
+ if (added) { store.notice = ''; emit() }
539
+ pumpQueue()
540
+ }
541
+
542
+ /** Run the queue one task at a time: installs share the profile's store. */
543
+ async function pumpQueue() {
544
+ if (isUpdating()) return
545
+ const task = store.queue.find((item) => item.status === 'queued')
546
+ if (!task) return
547
+ const pm = manager()
548
+ if (!pm) {
549
+ task.status = 'failed'
550
+ task.step = 'failed'
551
+ task.error = '插件管理器尚未加载'
552
+ emit()
553
+ return
554
+ }
555
+ task.status = 'running'
556
+ task.step = 'checking'
557
+ task.percent = STEP_PERCENT.checking
558
+ task.startedAt = Date.now()
559
+ emit()
560
+ try {
561
+ const result = unwrap(await pm.updateBundle(task.name, task.version, { requestId: task.requestId }))
562
+ const change = (result && result.result) || {}
563
+ const restore = result && result.restore
564
+ if (change.application === 'failed') {
565
+ task.status = 'failed'
566
+ task.step = 'failed'
567
+ task.error = describeFailure(change)
568
+ } else {
569
+ task.status = 'done'
570
+ task.step = 'applied'
571
+ task.percent = 100
572
+ const suffix = change.application === 'restart-required' ? ',重启 DSH 后生效' : ''
573
+ const rollback = restore && restore.application === 'failed' ? '(回滚未完成,请手动重装)' : ''
574
+ store.notice = task.title + ' 已更新到 ' + task.version + suffix + rollback
575
+ const stale = store.rows.find((row) => row.name === task.name)
576
+ if (stale) stale.check = null
577
+ await loadBundles()
578
+ }
579
+ } catch (error) {
580
+ task.status = 'failed'
581
+ task.step = 'failed'
582
+ task.error = messageOf(error)
583
+ }
584
+ task.finishedAt = Date.now()
585
+ emit()
586
+ if (task.status === 'done') {
587
+ const pm2 = manager()
588
+ const target = store.rows.find((row) => row.name === task.name)
589
+ if (pm2 && target) {
590
+ try {
591
+ target.check = interpretVersions(unwrap(await pm2.listVersions(target.name, {})), target.version)
592
+ } catch (error) {
593
+ target.check = null
594
+ }
595
+ emit()
596
+ }
597
+ }
598
+ pumpQueue()
599
+ }
600
+
601
+ /** Drop every task, cancelling the one in flight as far as the Host allows. */
602
+ function clearQueue() {
603
+ if (!store.queue.length) return
604
+ const running = runningTask()
605
+ if (running) {
606
+ const pm = manager()
607
+ if (pm && typeof pm.cancelInstall === 'function') {
608
+ try { Promise.resolve(pm.cancelInstall(running.requestId)).catch(() => {}) } catch (error) { /* ignore */ }
609
+ }
610
+ running.status = 'cancelled'
611
+ running.step = 'failed'
612
+ running.error = '已取消'
613
+ running.finishedAt = Date.now()
614
+ emit()
615
+ }
616
+ store.queue = []
617
+ emit()
618
+ }
619
+
620
+ function dismissFinished() {
621
+ store.queue = store.queue.filter((task) => task.status === 'queued' || task.status === 'running')
622
+ emit()
623
+ }
624
+
625
+ function describeFailure(change) {
626
+ const parts = []
627
+ const error = change && change.error
628
+ if (error) {
629
+ const inner = error.diagnostic || error.reason
630
+ parts.push(inner ? String(inner) : messageOf(error))
631
+ }
632
+ const pkg = change && change.packageResult
633
+ if (pkg && pkg.output) {
634
+ const lines = String(pkg.output).trim().split('\n').filter(Boolean)
635
+ parts.push(lines.slice(-3).join(' ').slice(0, 400))
636
+ if (pkg.logPath) parts.push('日志:' + pkg.logPath)
637
+ }
638
+ if (!parts.length) parts.push('更新未成功')
639
+ return parts.join(' · ')
640
+ }
641
+
642
+ function onUpdateState(progress) {
643
+ if (!progress) return
644
+ for (const task of store.queue) {
645
+ if (task.status !== 'running' || task.requestId !== progress.requestId) continue
646
+ task.step = progress.step
647
+ task.percent = STEP_PERCENT[progress.step] || task.percent
648
+ emit()
649
+ }
650
+ }
651
+
652
+ function onInstallLog(chunk) {
653
+ if (!chunk) return
654
+ const text = typeof chunk.text === 'string' ? chunk.text : typeof chunk.chunk === 'string' ? chunk.chunk : ''
655
+ if (!text) return
656
+ for (const task of store.queue) {
657
+ if (task.status !== 'running') continue
658
+ if (chunk.requestId && chunk.requestId !== task.requestId) continue
659
+ task.log = ((task.log || '') + text).slice(-4000)
660
+ }
661
+ emit()
662
+ }
663
+
664
+ function subscribe() {
665
+ const service = remoteService()
666
+ if (!service || typeof service.$on !== 'function') return
667
+ const disposers = []
668
+ const bind = (event, handler) => {
669
+ try {
670
+ const off = service.$on(event, handler)
671
+ if (off) disposers.push(off)
672
+ } catch (error) { /* forwarded events unavailable */ }
673
+ }
674
+ bind('plugin-manager/update-state', onUpdateState)
675
+ bind('plugin-manager/install-log', onInstallLog)
676
+ bind('plugin-manager/changed', () => { if (!isUpdating()) { loadBundles().then(emit).catch(() => {}) } })
677
+ if (appCtx) appCtx.effect(() => () => {
678
+ for (const off of disposers) {
679
+ try {
680
+ if (typeof off === 'function') off()
681
+ else if (typeof off.dispose === 'function') off.dispose()
682
+ } catch (error) { /* ignore */ }
683
+ }
684
+ })
685
+ }
686
+
687
+ function useRevision() {
688
+ const [, force] = React.useState(0)
689
+ React.useEffect(() => {
690
+ let active = true
691
+ const listener = () => { if (active) force((value) => value + 1) }
692
+ listeners.add(listener)
693
+ return () => { active = false; listeners.delete(listener) }
694
+ }, [])
695
+ return revision
696
+ }
697
+
698
+ function PluginUpdatesTab() {
699
+ useRevision()
700
+ const [query, setQuery] = React.useState('')
701
+ const [page, setPage] = React.useState(0)
702
+ const [pageSize, setPageSize] = React.useState(() => readPrefs().pageSize)
703
+ const [showOfficial, setShowOfficial] = React.useState(() => readPrefs().showOfficial)
704
+ const [selection, setSelection] = React.useState({})
705
+ const [queueExpanded, setQueueExpanded] = React.useState(false)
706
+ const [, tick] = React.useState(0)
707
+
708
+ const running = isUpdating()
709
+ React.useEffect(() => {
710
+ if (!running) return undefined
711
+ const timer = setInterval(() => tick((value) => value + 1), 1000)
712
+ return () => clearInterval(timer)
713
+ }, [running])
714
+
715
+ React.useEffect(() => { setPage(0) }, [query, pageSize, showOfficial])
716
+
717
+ const tokens = query.trim().toLowerCase().split(/\s+/).filter(Boolean)
718
+ const view = store.rows.filter((row) => {
719
+ if (!showOfficial && row.official) return false
720
+ if (!tokens.length) return true
721
+ const haystack = (row.title + ' ' + row.name + ' ' + row.description).toLowerCase()
722
+ return tokens.every((token) => haystack.indexOf(token) !== -1)
723
+ }).sort((left, right) => {
724
+ const delta = rankOf(left) - rankOf(right)
725
+ if (delta !== 0) return delta
726
+ return left.title.localeCompare(right.title, 'zh-CN')
727
+ })
728
+
729
+ const pageCount = Math.max(1, Math.ceil(view.length / pageSize))
730
+ const current = Math.min(page, pageCount - 1)
731
+ const start = current * pageSize
732
+ const pageRows = view.slice(start, start + pageSize)
733
+ const installedCount = store.rows.filter((row) => !row.official).length
734
+ const outdatedCount = store.rows.filter((row) => {
735
+ const check = row.check
736
+ return !row.official && check && check.state === 'done' && check.versions.length > 0
737
+ }).length
738
+
739
+ const checkProgress = store.checkProgress
740
+ const progressText = checkProgress ? '检查中 ' + checkProgress.done + '/' + checkProgress.total : '检查中…'
741
+ const outdated = view.filter((row) => row.check && row.check.state === 'done' && row.check.versions.length > 0)
742
+ const batch = outdated.map((row) => ({
743
+ name: row.name,
744
+ title: row.title,
745
+ version: selection[row.name] || row.check.versions[0].version,
746
+ }))
747
+ const batchIdle = batch.filter((entry) => !taskOf(entry.name)).length
748
+ const queueOpen = store.queue.length > 0
749
+
750
+ const head = h('div', { className: 'dpu-head' },
751
+ h('div', { className: 'dpu-head-main' },
752
+ h('div', { className: 'dpu-head-title' }, '插件版本更新'),
753
+ h('div', { className: 'dpu-head-sub' },
754
+ '共 ' + installedCount + ' 个 · ' + (outdatedCount > 0 ? outdatedCount + ' 个可升级' : '暂无可用升级')
755
+ + (store.checkedAt ? ' · 上次检查 ' + formatTime(store.checkedAt) : '')
756
+ + (store.checking ? ' · ' + progressText : ''))),
757
+ h('div', { className: 'dpu-toolbar' },
758
+ h('input', {
759
+ className: 'dpu-input',
760
+ placeholder: '搜索插件名 / 包名',
761
+ value: query,
762
+ onChange: (event) => setQuery(event.target.value),
763
+ }),
764
+ h('select', {
765
+ className: 'dpu-select',
766
+ value: String(pageSize),
767
+ title: '每页条数',
768
+ onChange: (event) => {
769
+ const next = Number(event.target.value) || 20
770
+ setPageSize(next)
771
+ writePrefs({ pageSize: next })
772
+ },
773
+ },
774
+ h('option', { value: '10' }, '每页 10'),
775
+ h('option', { value: '20' }, '每页 20'),
776
+ h('option', { value: '50' }, '每页 50')),
777
+ h('label', { className: 'dpu-check', title: '内置插件随 DSH 发行,不能单独升级' },
778
+ h('input', {
779
+ type: 'checkbox',
780
+ checked: showOfficial,
781
+ onChange: (event) => {
782
+ const next = event.target.checked
783
+ setShowOfficial(next)
784
+ writePrefs({ showOfficial: next })
785
+ },
786
+ }),
787
+ h('span', null, '显示内置')),
788
+ batch.length > 0 ? h('button', {
789
+ className: 'dpu-btn dpu-btn-primary',
790
+ disabled: batchIdle === 0,
791
+ title: '把当前筛选结果里所有可升级插件依次加入更新队列',
792
+ onClick: () => { enqueueUpdates(batch) },
793
+ }, '批量更新 (' + batch.length + ')') : null,
794
+ h('button', {
795
+ className: 'dpu-btn',
796
+ disabled: store.checking || store.phase === 'loading' || !manager(),
797
+ onClick: () => { checkAll() },
798
+ }, store.checking ? progressText : '检查更新')))
799
+
800
+ const notices = []
801
+ if (store.error) notices.push(h('div', { className: 'dpu-notice dpu-notice-error', key: 'error' }, h('div', { className: 'dpu-notice-text' }, '无法读取插件列表:' + store.error)))
802
+ if (store.notice) notices.push(h('div', { className: 'dpu-notice', key: 'notice' },
803
+ h('div', { className: 'dpu-notice-text' }, store.notice),
804
+ h('button', { className: 'dpu-btn dpu-btn-ghost', onClick: () => { store.notice = ''; emit() } }, '知道了')))
805
+
806
+ const activeTask = runningTask()
807
+ const queuePanel = !queueOpen ? null : h('div', { className: 'dpu-queue' },
808
+ h('div', { className: 'dpu-queue-head' },
809
+ h('button', {
810
+ className: 'dpu-queue-toggle',
811
+ title: queueExpanded ? '收起更新队列' : '展开更新队列',
812
+ onClick: () => setQueueExpanded(!queueExpanded),
813
+ },
814
+ h('span', { className: 'dpu-chevron' }, queueExpanded ? '▾' : '▸'),
815
+ h('span', { className: 'dpu-queue-title' }, '更新队列 · ' + queueSummary()),
816
+ activeTask ? h('span', { className: 'dpu-queue-percent' },
817
+ (STEP_LABEL[activeTask.step] || '更新中') + ' ' + Math.max(2, Math.min(100, activeTask.percent || STEP_PERCENT[activeTask.step] || 12)) + '%') : null),
818
+ queueExpanded ? h('div', { className: 'dpu-queue-actions' },
819
+ h('button', {
820
+ className: 'dpu-btn dpu-btn-ghost',
821
+ disabled: !store.queue.some((task) => task.status !== 'queued' && task.status !== 'running'),
822
+ onClick: () => dismissFinished(),
823
+ }, '清空已完成'),
824
+ h('button', { className: 'dpu-btn dpu-btn-ghost', onClick: () => clearQueue() }, '清空队列')) : null),
825
+ queueExpanded ? store.queue.map((task) => h('div', { className: 'dpu-task', key: task.id },
826
+ h('div', { className: 'dpu-task-head' },
827
+ h('span', { className: 'dpu-task-title' }, task.title),
828
+ h('span', { className: 'dpu-task-version' }, '→ ' + task.version),
829
+ h('span', { className: 'dpu-tag ' + taskTagTone(task) }, taskStatusText(task))),
830
+ task.status === 'running' ? h('div', { className: 'dpu-progress' },
831
+ h('div', { className: 'dpu-progress-track' },
832
+ h('div', {
833
+ className: 'dpu-progress-bar',
834
+ style: { width: Math.max(2, Math.min(100, task.percent || STEP_PERCENT[task.step] || 12)) + '%' },
835
+ })),
836
+ h('div', { className: 'dpu-progress-text' },
837
+ h('span', null, (STEP_LABEL[task.step] || '准备中') + ' · ' + elapsedText(task.startedAt)))) : null,
838
+ task.error ? h('div', { className: 'dpu-error' }, task.error) : null)) : null,
839
+ queueOpen && !queueExpanded && activeTask ? h('div', { className: 'dpu-progress-track dpu-queue-track' },
840
+ h('div', {
841
+ className: 'dpu-progress-bar',
842
+ style: { width: Math.max(2, Math.min(100, activeTask.percent || STEP_PERCENT[activeTask.step] || 12)) + '%' },
843
+ })) : null)
844
+
845
+ const rows = pageRows.map((row) => renderRow(row, selection, setSelection, running))
846
+
847
+ const empty = view.length === 0
848
+ ? h('div', { className: 'dpu-empty' }, store.phase === 'loading' ? '正在读取已安装插件…' : (query ? '没有匹配「' + query + '」的插件' : '没有已安装的插件'))
849
+ : null
850
+
851
+ const foot = h('div', { className: 'dpu-foot' },
852
+ h('span', null, '第 ' + (view.length === 0 ? 0 : start + 1) + ' - ' + Math.min(start + pageSize, view.length) + ' 项 / 共 ' + view.length + ' 项'),
853
+ h('div', { className: 'dpu-pager' },
854
+ h('button', { className: 'dpu-btn', disabled: current <= 0, onClick: () => setPage(current - 1) }, '上一页'),
855
+ h('span', null, (current + 1) + ' / ' + pageCount),
856
+ h('button', { className: 'dpu-btn', disabled: current >= pageCount - 1, onClick: () => setPage(current + 1) }, '下一页')))
857
+
858
+ return h('div', { className: 'dpu-root' }, head, notices, queuePanel, h('div', { className: 'dpu-list' }, rows), empty, foot)
859
+ }
860
+
861
+ function renderRow(row, selection, setSelection, running) {
862
+ const status = statusOf(row)
863
+ const check = row.check
864
+ const versions = check && check.state === 'done' ? check.versions : []
865
+ const outdated = versions.length > 0
866
+ const task = taskOf(row.name)
867
+ const chosen = selection[row.name] || (versions.length ? versions[0].version : '')
868
+
869
+ const tagTone = status.tone === 'warn' ? 'dpu-tag-warn' : status.tone === 'error' ? 'dpu-tag-error' : status.tone === 'success' ? 'dpu-tag-success' : 'dpu-tag-muted'
870
+
871
+ const actions = []
872
+ if (outdated) {
873
+ actions.push(h('select', {
874
+ className: 'dpu-select',
875
+ key: 'version',
876
+ value: chosen,
877
+ title: '选择要升级到的版本',
878
+ onChange: (event) => setSelection(Object.assign({}, selection, { [row.name]: event.target.value })),
879
+ }, versions.map((entry) => h('option', { key: entry.version, value: entry.version },
880
+ entry.version + (entry.prerelease ? ' (预发布)' : '') + (entry.deprecated ? ' (已弃用)' : '') + (entry.incompatible ? ' (不兼容)' : '')))))
881
+ actions.push(h('button', {
882
+ className: 'dpu-btn dpu-btn-primary',
883
+ key: 'update',
884
+ disabled: !!task || !chosen,
885
+ title: task ? '已加入更新队列' : '加入更新队列',
886
+ onClick: () => { enqueueUpdates([{ name: row.name, title: row.title, version: chosen }]) },
887
+ }, task ? (task.status === 'running' ? '更新中…' : '排队中…') : '更新'))
888
+ }
889
+
890
+ let progress = null
891
+ if (task && task.status === 'running') {
892
+ const percent = task.percent || STEP_PERCENT[task.step] || 12
893
+ progress = h('div', { className: 'dpu-progress' },
894
+ h('div', { className: 'dpu-progress-track' },
895
+ h('div', {
896
+ className: 'dpu-progress-bar',
897
+ style: { width: Math.max(2, Math.min(100, percent)) + '%' },
898
+ })),
899
+ h('div', { className: 'dpu-progress-text' },
900
+ h('span', null, (STEP_LABEL[task.step] || '准备中') + ' · ' + elapsedText(task.startedAt))))
901
+ } else if (check && check.state === 'error' && check.error) {
902
+ progress = h('div', { className: 'dpu-error' }, check.error)
903
+ } else if (check && check.state === 'n/a' && check.error) {
904
+ progress = h('div', { className: 'dpu-error' }, check.error)
905
+ }
906
+
907
+ return h('div', { className: 'dpu-row' + (outdated ? ' dpu-row-outdated' : ''), key: row.name },
908
+ h('div', { className: 'dpu-row-head' },
909
+ h('div', { className: 'dpu-row-title' },
910
+ h('span', { className: 'dpu-title' }, row.title),
911
+ h('span', { className: 'dpu-tag ' + tagTone }, status.text),
912
+ !row.enabled ? h('span', { className: 'dpu-tag dpu-tag-muted' }, '已禁用') : null,
913
+ row.official ? h('span', { className: 'dpu-tag dpu-tag-muted' }, '内置') : null,
914
+ row.git ? h('span', { className: 'dpu-tag dpu-tag-muted' }, 'Git') : null),
915
+ h('div', { className: 'dpu-row-actions' }, actions)),
916
+ h('div', { className: 'dpu-name' }, row.name),
917
+ row.description ? h('div', { className: 'dpu-desc' }, row.description) : null,
918
+ h('div', { className: 'dpu-meta' },
919
+ h('span', null, '当前版本 ', h('b', null, row.version || '—')),
920
+ h('span', null, '安装时间 ', h('b', null, formatTime(row.installedAt))),
921
+ outdated ? h('span', null, '最新版本 ', h('b', null, versions[0].version)) : null,
922
+ outdated && check.omitted ? h('span', null, '另有 ' + check.omitted + ' 个版本未列出') : null),
923
+ progress)
924
+ }
925
+
926
+ function apply(ctx) {
927
+ appCtx = ctx
928
+ const slots = ctx.get('slots')
929
+ if (slots === undefined) return
930
+ const style = createOwnedStyle(CSS)
931
+ ctx.effect(() => () => { try { style.remove() } catch (error) { /* ignore */ } })
932
+
933
+ slots.inject('plugins.tab', () => slots.register(
934
+ { name: 'plugins.tab', id: 'updates', order: 10, label: '插件更新' },
935
+ () => h(PluginUpdatesTab, {}),
936
+ ))
937
+
938
+ let attempts = 0
939
+ const start = () => {
940
+ attempts += 1
941
+ if (!remoteService()) {
942
+ if (attempts < 40) setTimeout(start, 400)
943
+ return
944
+ }
945
+ subscribe()
946
+ bootstrap()
947
+ }
948
+ start()
949
+ }
950
+
951
+ const inject = ['slots']
952
+ exports.apply = apply
953
+ exports.inject = inject
954
+ return module.exports
955
+ },
956
+ }
957
+ })())