dsh-pick 0.3.0 → 0.4.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/engine.js CHANGED
@@ -6,15 +6,28 @@
6
6
  // 页面只读 catalog.json,秒开。
7
7
 
8
8
  import { readFile, writeFile, mkdir } from 'node:fs/promises'
9
- import { join, dirname } from 'node:path'
9
+ import { join, dirname, resolve } from 'node:path'
10
+ import { homedir } from 'node:os'
10
11
  import { fileURLToPath } from 'node:url'
11
12
  import { classify } from './classify.js'
12
13
  import { expandWords } from './words.js'
13
14
  import { baselineWithStart, growth, cadence, ageDays, score, sum } from './metrics.js'
14
15
 
15
16
  const PKG_ROOT = fileURLToPath(new URL('..', import.meta.url))
17
+ /** 随包自带的目录(发版时的快照;dsh-pick build 也写这里) */
16
18
  export const CATALOG_PATH = join(PKG_ROOT, 'data', 'catalog.json')
17
19
 
20
+ /** DSH 的数据目录:DSH_HOME 或 ~/.dsh */
21
+ export function dshHome(env = process.env) {
22
+ const fromEnv = String(env.DSH_HOME || '').trim()
23
+ return fromEnv ? resolve(fromEnv) : join(homedir(), '.dsh')
24
+ }
25
+
26
+ /** 每日更新下来的目录(lib/remote.js 写入):放在 DSH 数据目录里,插件升级、重装都不丢 */
27
+ export function cachePath(env = process.env) {
28
+ return join(dshHome(env), 'dsh-pick', 'catalog.json')
29
+ }
30
+
18
31
  const SEARCH_API = 'https://registry.npmjs.org/-/v1/search'
19
32
  const DL_API = 'https://api.npmjs.org/downloads'
20
33
  const REG_API = 'https://registry.npmjs.org'
@@ -186,6 +199,15 @@ export async function buildCatalog({ deep = 200, max = 2250, pages = 9, deepOnly
186
199
  pending = pending.filter((_, i) => !ranges[i])
187
200
  }
188
201
 
202
+ // 安装相关的硬信息(全部包都要):npm 上 latest 版本的 manifest 里
203
+ // dsh.bundle 有没有声明(没有的话 dsh plugin add 直接拒绝安装)、
204
+ // 客户端平台(web / tui)、声明的 DSH 版本要求(engines.dsh 与 @deepseek-ai/dsh* 的 peer)
205
+ // registry 的单版本 manifest 很宽松,可以并发
206
+ const needFacts = [...records.values()].filter(r => !(deepOnly && r.inst))
207
+ onProgress(`安装信息 ${needFacts.length} 个…`)
208
+ const manifests = await pool(needFacts, 8, rec => jget(`${REG_API}/${enc(rec.n)}/latest`, 2))
209
+ needFacts.forEach((rec, i) => { if (manifests[i]) rec.inst = installFacts(manifests[i]) })
210
+
189
211
  const catalog = {
190
212
  tool: 'dsh-pick',
191
213
  asOf: today,
@@ -202,22 +224,60 @@ export async function buildCatalog({ deep = 200, max = 2250, pages = 9, deepOnly
202
224
  return catalog
203
225
  }
204
226
 
227
+ /**
228
+ * 从 npm manifest 里摘出安装相关的三件事(字段名短:2,250 个包都要存)
229
+ * b 有没有 dsh.bundle 声明 · p 客户端平台 · r 声明的 DSH 版本要求(可能为 null)
230
+ * 版本要求的读法照 dshmarket:engines.dsh 与 dsh.engines.dsh 都认,peer 只看 @deepseek-ai/dsh*
231
+ * (cordis、schemastery 不跟 DSH 版本走)
232
+ */
233
+ export function installFacts(manifest = {}) {
234
+ const dsh = (manifest && manifest.dsh) || {}
235
+ const reqs = []
236
+ const engine = (manifest.engines && manifest.engines.dsh) || (dsh.engines && dsh.engines.dsh)
237
+ if (typeof engine === 'string' && engine.trim()) reqs.push(engine.trim())
238
+ for (const [name, range] of Object.entries(manifest.peerDependencies || {})) {
239
+ if (/^@deepseek-ai\/dsh(-|$)/.test(name) && typeof range === 'string' && range.trim()) reqs.push(range.trim())
240
+ }
241
+ const platform = dsh.client && typeof dsh.client.platform === 'string' ? dsh.client.platform : null
242
+ return { b: Boolean(dsh.bundle), p: platform, r: reqs.length ? [...new Set(reqs)].join(' ∩ ') : null }
243
+ }
244
+
205
245
  /* ---------------------------------------------------------------- 查询 */
206
246
 
207
247
  let cache = null
208
248
 
209
- export async function loadCatalog() {
210
- if (cache) return cache
249
+ async function readJson(file) {
211
250
  try {
212
- cache = normalize(JSON.parse(await readFile(CATALOG_PATH, 'utf8')))
251
+ return JSON.parse(await readFile(file, 'utf8'))
213
252
  } catch {
214
- cache = { asOf: null, anchor: null, packages: {}, total: 0 }
253
+ return null
215
254
  }
255
+ }
256
+
257
+ /** a 比 b 新:先比统计截止日,再比构建日 */
258
+ export function newerCatalog(a, b) {
259
+ if (!a || !a.packages) return false
260
+ if (!b || !b.packages) return true
261
+ const ka = `${a.anchor || ''}|${a.asOf || ''}`
262
+ const kb = `${b.anchor || ''}|${b.asOf || ''}`
263
+ return ka > kb
264
+ }
265
+
266
+ /**
267
+ * 目录:随包自带的和每日更新的,用新的那份。
268
+ * source 标出用的是哪份('remote' 每日更新 / 'bundled' 随包自带),设置页显示用
269
+ */
270
+ export async function loadCatalog({ env = process.env } = {}) {
271
+ if (cache) return cache
272
+ const [bundled, cached] = await Promise.all([readJson(CATALOG_PATH), readJson(cachePath(env))])
273
+ const pick = newerCatalog(cached, bundled) ? { ...cached, source: 'remote' } : bundled ? { ...bundled, source: 'bundled' } : null
274
+ cache = pick ? normalize(pick) : { asOf: null, anchor: null, packages: {}, total: 0, source: 'none' }
216
275
  return cache
217
276
  }
218
277
 
278
+ /** 换上新目录(每日更新下载完、或测试时) */
219
279
  export function reloadCatalog(cat) {
220
- cache = normalize(cat)
280
+ cache = cat ? normalize(cat) : null
221
281
  }
222
282
 
223
283
  /**
package/lib/remote.js ADDED
@@ -0,0 +1,93 @@
1
+ // lib/remote.js — 每日更新的目录
2
+ //
3
+ // GitHub Actions 每天跑一次 dsh-pick build,把 catalog.json 和一个很小的 meta.json 推到本仓库的
4
+ // catalog 分支(.github/workflows/catalog.yml)。插件在 DSH 里启动时、之后每 6 小时问一次:
5
+ // 先取 meta.json 比新旧,真有更新才下载完整目录(约 1.5 MB),校验后原子写进 ~/.dsh/dsh-pick/,
6
+ // 再换上新目录。取不到(没网、被墙)就继续用手上的,什么都不报——随包自带的那份永远兜底。
7
+ //
8
+ // 镜像按顺序试:jsDelivr 国内一般能直连;raw.githubusercontent.com 兜底。
9
+
10
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
11
+ import { dirname, join } from 'node:path'
12
+ import { cachePath, dshHome, loadCatalog, newerCatalog, reloadCatalog } from './engine.js'
13
+
14
+ export const REPO = 'AIcivilization/dsh-pick'
15
+ export const BRANCH = 'catalog'
16
+ export const MIRRORS = [
17
+ `https://cdn.jsdelivr.net/gh/${REPO}@${BRANCH}/`,
18
+ `https://raw.githubusercontent.com/${REPO}/${BRANCH}/`,
19
+ ]
20
+ export const CHECK_EVERY_MS = 6 * 60 * 60 * 1000
21
+ const TIMEOUT_MS = { meta: 8000, catalog: 60000 }
22
+
23
+ const statePath = env => join(dshHome(env), 'dsh-pick', 'remote.json')
24
+
25
+ async function readState(env) {
26
+ try {
27
+ return JSON.parse(await readFile(statePath(env), 'utf8'))
28
+ } catch {
29
+ return {}
30
+ }
31
+ }
32
+
33
+ async function writeAtomic(file, text) {
34
+ await mkdir(dirname(file), { recursive: true })
35
+ const tmp = `${file}.${process.pid}.tmp`
36
+ await writeFile(tmp, text, 'utf8')
37
+ await rename(tmp, file)
38
+ }
39
+
40
+ async function getJson(fetchImpl, url, timeoutMs) {
41
+ const r = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs), headers: { accept: 'application/json' } })
42
+ if (!r.ok) throw new Error(`HTTP ${r.status}`)
43
+ return r.json()
44
+ }
45
+
46
+ /** 下载来的目录像不像样:包够多、字段齐。防止镜像返回半截文件或错误页 */
47
+ export function validCatalog(cat) {
48
+ if (!cat || typeof cat !== 'object' || !cat.packages || typeof cat.packages !== 'object') return false
49
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(String(cat.anchor || ''))) return false
50
+ const list = Object.values(cat.packages)
51
+ return list.length >= 500 && list.slice(0, 50).every(r => r && typeof r.n === 'string' && typeof r.w === 'number')
52
+ }
53
+
54
+ /**
55
+ * 检查并下载更新的目录。
56
+ * @param {object} [opt]
57
+ * @param {boolean} [opt.force] 不管 6 小时内查过没有,马上查
58
+ * @returns {Promise<{checked: boolean, updated: boolean, anchor?: string, mirror?: string, error?: string}>}
59
+ */
60
+ export async function refreshCatalog({ fetchImpl = globalThis.fetch, env = process.env, force = false, now = Date.now } = {}) {
61
+ const state = await readState(env)
62
+ if (!force && state.checkedAt && now() - Date.parse(state.checkedAt) < CHECK_EVERY_MS) {
63
+ return { checked: false, updated: false }
64
+ }
65
+ const current = await loadCatalog({ env })
66
+ let lastError = ''
67
+ for (const base of MIRRORS) {
68
+ try {
69
+ const meta = await getJson(fetchImpl, base + 'meta.json', TIMEOUT_MS.meta)
70
+ const done = async (result) => {
71
+ await writeAtomic(statePath(env), JSON.stringify({ checkedAt: new Date(now()).toISOString(), anchor: meta.anchor || null, mirror: base }))
72
+ return result
73
+ }
74
+ // meta 不比手上的新:不下载
75
+ if (!newerCatalog({ ...meta, packages: {} }, current)) return done({ checked: true, updated: false, anchor: current.anchor, mirror: base })
76
+ const cat = await getJson(fetchImpl, base + 'catalog.json', TIMEOUT_MS.catalog)
77
+ if (!validCatalog(cat)) throw new Error('目录文件不完整')
78
+ if (!newerCatalog(cat, current)) return done({ checked: true, updated: false, anchor: current.anchor, mirror: base })
79
+ await writeAtomic(cachePath(env), JSON.stringify(cat))
80
+ reloadCatalog({ ...cat, source: 'remote' })
81
+ return done({ checked: true, updated: true, anchor: cat.anchor, mirror: base })
82
+ } catch (e) {
83
+ lastError = e && e.message ? e.message : String(e)
84
+ }
85
+ }
86
+ // 都连不上:不记 checkedAt,下一轮再试
87
+ return { checked: true, updated: false, error: lastError }
88
+ }
89
+
90
+ /** 最近一次检查的记录(设置页显示用) */
91
+ export function remoteState(env = process.env) {
92
+ return readState(env)
93
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-pick",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "帮你在 DSH 生态里选对插件:说需求 → 找候选 → 多维比较 → 出结论。下载量是证据,AI 是推理。",
5
5
  "type": "module",
6
6
  "main": "./plugin/index.js",
@@ -12,6 +12,10 @@
12
12
  "bin": {
13
13
  "dsh-pick": "bin/dsh-pick.js"
14
14
  },
15
+ "scripts": {
16
+ "test": "node --test \"test/*.test.js\"",
17
+ "release": "node scripts/release.mjs"
18
+ },
15
19
  "dsh": {
16
20
  "bundle": {
17
21
  "patch": "./plugin/cordis.patch.yml"
package/plugin/client.js CHANGED
@@ -59,6 +59,36 @@ window.__ModuleLoader__.load({
59
59
  }, children)
60
60
  }
61
61
 
62
+ /** 一条给用户自己在终端执行的命令:等宽显示,旁边一个「复制」 */
63
+ function CommandLine({ command }) {
64
+ const [copied, setCopied] = useState(false)
65
+ const copy = async () => {
66
+ try {
67
+ await navigator.clipboard.writeText(command)
68
+ } catch {
69
+ // 剪贴板不让用(非安全上下文等):退回到选中后 execCommand
70
+ const ta = document.createElement('textarea')
71
+ ta.value = command
72
+ ta.style.position = 'fixed'
73
+ ta.style.opacity = '0'
74
+ document.body.appendChild(ta)
75
+ ta.select()
76
+ try { document.execCommand('copy') } catch { /* 实在不行用户还能手动选 */ }
77
+ ta.remove()
78
+ }
79
+ setCopied(true)
80
+ setTimeout(() => setCopied(false), 2000)
81
+ }
82
+ return h('div', { style: { display: 'flex', alignItems: 'center', gap: 6, marginTop: 6, flexWrap: 'wrap' } },
83
+ h('code', {
84
+ style: {
85
+ flex: '1 1 auto', minWidth: 0, padding: '4px 8px', borderRadius: 6, fontSize: 12, color: C.text,
86
+ border: '1px solid ' + C.border, userSelect: 'all', overflowWrap: 'anywhere',
87
+ },
88
+ }, command),
89
+ h(Btn, { onClick: copy }, copied ? L('已复制', 'Copied') : L('复制', 'Copy')))
90
+ }
91
+
62
92
  /** 标题行:dsh-pick · 版本号 · 更新 ……(最右)卸载 */
63
93
  function HeaderBar() {
64
94
  const [info, setInfo] = useState(null)
@@ -132,7 +162,7 @@ window.__ModuleLoader__.load({
132
162
  ),
133
163
  msg ? h('div', { style: { fontSize: 12, color: C.danger, marginTop: 6, lineHeight: 1.6 } },
134
164
  msg.text,
135
- msg.command ? h('code', { style: { display: 'block', marginTop: 4, color: C.text, userSelect: 'all' } }, msg.command) : null,
165
+ msg.command ? h(CommandLine, { command: msg.command }) : null,
136
166
  ) : null,
137
167
  )
138
168
  }
@@ -277,6 +307,11 @@ window.__ModuleLoader__.load({
277
307
 
278
308
  h(Section, { title: L('数据口径', 'About the data') },
279
309
  h('div', null, catalog),
310
+ meta && meta.total ? h('div', { style: { marginTop: 4 } }, meta.source === 'remote'
311
+ ? L('数据每天自动更新' + (meta.checkedAt ? `,最近一次检查 ${new Date(meta.checkedAt).toLocaleString()}` : '') + '。',
312
+ 'Data updates daily' + (meta.checkedAt ? `; last checked ${new Date(meta.checkedAt).toLocaleString()}` : '') + '.')
313
+ : L('现在用的是随插件自带的数据:每日更新还没取到(网络不通时会这样),取到后自动换上。',
314
+ 'Using the data bundled with the plugin; the daily update has not arrived yet and will be used once it does.')) : null,
280
315
  h('div', { style: { marginTop: 4 } }, DATA_NOTE()),
281
316
  ),
282
317
  )
package/plugin/index.js CHANGED
@@ -1,14 +1,15 @@
1
1
  // plugin/index.js — dsh-pick 的 DSH 插件(宿主端)
2
2
  //
3
3
  // 只做一件事:把「选插件」面板挂到 dsh 自己的 webServer 上,让 dsh 设置页里能看,
4
- // 顺便给面板提供数据接口。数据全部来自本包 data/catalog.json,不外传。
4
+ // 顺便给面板提供数据接口。数据来自随包自带的 data/catalog.json,或每天自动更新下来的那份
5
+ // (~/.dsh/dsh-pick/catalog.json,见 lib/remote.js),用新的那份;只读公开的 npm 数据,不外传任何东西。
5
6
  //
6
7
  // 路由(都走 dsh 的登录校验,所以先过 dsh 自己的鉴权):
7
8
  // GET /api-dsh-pick/panel 面板 HTML
8
9
  // GET /api-dsh-pick/panel.js 面板逻辑
9
10
  // GET /api-dsh-pick/words.js 搜索词典
10
11
  // GET /api-dsh-pick/catalog.json 目录(含排名、链接、去噪指标)
11
- // GET /api-dsh-pick/meta 目录概要(更新时间、包数)
12
+ // GET /api-dsh-pick/meta 目录概要(更新时间、包数、来源)
12
13
  // GET /api-dsh-pick/update 本插件版本 + npm 上的最新版本
13
14
  // POST /api-dsh-pick/update 更新到 npm 最新版(交给 DSH 的插件管理器)
14
15
  // POST /api-dsh-pick/uninstall 从 DSH 卸载本插件
@@ -23,6 +24,8 @@ import { readFile } from 'node:fs/promises'
23
24
  import { fileURLToPath } from 'node:url'
24
25
  import { join } from 'node:path'
25
26
  import { registerTools } from './tools.js'
27
+ import { loadCatalog } from '../lib/engine.js'
28
+ import { refreshCatalog, remoteState, CHECK_EVERY_MS } from '../lib/remote.js'
26
29
 
27
30
  /** 本包根目录:插件就是完整的 dsh-pick 包 */
28
31
  const PKG_ROOT = fileURLToPath(new URL('..', import.meta.url))
@@ -38,7 +41,6 @@ const FILES = {
38
41
  '/panel': 'web/panel.html',
39
42
  '/panel.js': 'web/panel.js',
40
43
  '/words.js': 'lib/words.js',
41
- '/catalog.json': 'data/catalog.json',
42
44
  }
43
45
 
44
46
  async function readPkgJson() {
@@ -95,6 +97,20 @@ function pluginCommand(args, profile) {
95
97
  }
96
98
 
97
99
  /** 插件管理器的失败结果 → 一行人话(取诊断输出的最后几行) */
100
+ /** 插件管理器失败结果里的错误码(没失败返回空串) */
101
+ function managerCode(result) {
102
+ if (!(result && (result.application === 'failed' || result.application === 'cancelled' || result.error))) return ''
103
+ return (result.error && result.error.code) || result.application || 'failed'
104
+ }
105
+
106
+ /**
107
+ * 官方桌面版(0.2.1-rc.2 实测)的插件管理器不能在运行中升级已装的插件:installBundle 一律答
108
+ * already-installed(插件市场的「更新」也栽在这里)。只能退出 DSH、在终端用 dsh plugin 装
109
+ */
110
+ const ALREADY_INSTALLED_HINT =
111
+ '这个版本的 DSH 不能在运行中升级已装的插件。请完全退出 DSH(Mac 上按 Cmd+Q,不是关窗口),' +
112
+ '在终端执行下面的命令,再重新打开 DSH。如果提示版本太新(发布不满 1 天),过一天再执行。'
113
+
98
114
  function managerError(result) {
99
115
  if (!(result && (result.application === 'failed' || result.application === 'cancelled' || result.error))) return ''
100
116
  const code = (result.error && result.error.code) || result.application || 'failed'
@@ -153,22 +169,29 @@ function isSafePost(req) {
153
169
  }
154
170
  }
155
171
 
156
- /** 目录概要:给面板顶部显示「更新时间 / 包数」用 */
172
+ /** 目录概要:给面板顶部、设置页显示「更新时间 / 包数 / 来源」用 */
157
173
  async function catalogMeta() {
158
- try {
159
- const cat = JSON.parse(await readFile(join(PKG_ROOT, 'data', 'catalog.json'), 'utf8'))
160
- const packages = cat.packages || {}
161
- return {
162
- asOf: cat.asOf || null,
163
- anchor: cat.anchor || null,
164
- total: cat.total || Object.keys(packages).length,
165
- deepCount: Object.values(packages).filter(p => p && p.deep).length,
166
- }
167
- } catch {
168
- return { asOf: null, anchor: null, total: 0, deepCount: 0 }
174
+ const cat = await loadCatalog()
175
+ const packages = cat.packages || {}
176
+ const state = await remoteState()
177
+ return {
178
+ asOf: cat.asOf || null,
179
+ anchor: cat.anchor || null,
180
+ total: cat.total || Object.keys(packages).length,
181
+ deepCount: Object.values(packages).filter(p => p && p.deep).length,
182
+ source: cat.source || 'bundled',
183
+ checkedAt: state.checkedAt || null,
169
184
  }
170
185
  }
171
186
 
187
+ /** 归一化后的目录(带排名、npm / GitHub 链接)序列化一次就够:目录对象换了才重算 */
188
+ let catalogText = { of: null, text: '' }
189
+ async function catalogJson() {
190
+ const cat = await loadCatalog()
191
+ if (catalogText.of !== cat) catalogText = { of: cat, text: JSON.stringify(cat) }
192
+ return catalogText.text
193
+ }
194
+
172
195
  export const name = 'dsh-pick'
173
196
  export const inject = []
174
197
 
@@ -188,6 +211,16 @@ export function apply(ctx) {
188
211
  profile = ctx.get && ctx.get('profileContext') && ctx.get('profileContext').name
189
212
  } catch { profile = undefined }
190
213
 
214
+ // 每日更新的目录:启动时查一次,之后每 6 小时查一次(查不到就继续用手上的)
215
+ const refresh = () => refreshCatalog().catch(() => {})
216
+ const startTimer = setTimeout(refresh, 5000) // 别和 DSH 启动抢网络
217
+ const timer = setInterval(refresh, CHECK_EVERY_MS)
218
+ if (timer.unref) timer.unref()
219
+ if (startTimer.unref) startTimer.unref()
220
+ const stop = () => { clearTimeout(startTimer); clearInterval(timer) }
221
+ if (typeof ctx.effect === 'function') ctx.effect(() => stop)
222
+ else if (typeof ctx.on === 'function') ctx.on('dispose', stop)
223
+
191
224
  // AI 工具:DSH 有 tools 服务才注册(可选依赖,没有也不影响面板)
192
225
  ctx.inject(['tools'], (toolsCtx) => {
193
226
  const tools = toolsCtx.tools || (toolsCtx.get && toolsCtx.get('tools'))
@@ -226,6 +259,16 @@ export function apply(ctx) {
226
259
  }))
227
260
  }
228
261
 
262
+ // 目录(归一化后的:带排名与链接;用新的那份)
263
+ track(ws.register({
264
+ kind: 'exact',
265
+ path: '/api-dsh-pick/catalog.json',
266
+ handler: async (req, res) => {
267
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
268
+ res.end(await catalogJson())
269
+ },
270
+ }))
271
+
229
272
  // 目录概要
230
273
  track(ws.register({
231
274
  kind: 'exact',
@@ -265,10 +308,12 @@ export function apply(ctx) {
265
308
  }
266
309
  try {
267
310
  const result = await pluginManager.installBundle(`${PACKAGE}@${latest}`, { enabled: true })
311
+ if (managerCode(result) === 'already-installed') return sendJson(res, 200, { ok: false, message: ALREADY_INSTALLED_HINT, command })
268
312
  const err = managerError(result)
269
313
  if (err) return sendJson(res, 200, { ok: false, message: `更新失败(${err})`, command })
270
314
  return sendJson(res, 200, { ok: true, version: latest })
271
315
  } catch (e) {
316
+ if (e && e.code === 'already-installed') return sendJson(res, 200, { ok: false, message: ALREADY_INSTALLED_HINT, command })
272
317
  return sendJson(res, 200, { ok: false, message: `更新失败:${e.message}`, command })
273
318
  }
274
319
  },
@@ -317,12 +362,12 @@ export function apply(ctx) {
317
362
  if (!isSafePost(req)) return sendJson(res, 403, { ok: false, message: '只接受本页面发出的请求' })
318
363
  const { name } = await readJsonBody(req)
319
364
  if (typeof name !== 'string' || !NAME_RE.test(name)) return sendJson(res, 400, { ok: false, message: '包名不对' })
320
- let inCatalog = false
321
- try {
322
- const cat = JSON.parse(await readFile(join(PKG_ROOT, 'data', 'catalog.json'), 'utf8'))
323
- inCatalog = Boolean(cat.packages && cat.packages[name])
324
- } catch { /* 目录读不到就当不在 */ }
325
- if (!inCatalog) return sendJson(res, 400, { ok: false, message: `${name} 不在 DSH 插件目录里,这里不装` })
365
+ const rec = (await loadCatalog()).packages[name]
366
+ if (!rec) return sendJson(res, 400, { ok: false, message: `${name} 不在 DSH 插件目录里,这里不装` })
367
+ // 没声明 dsh.bundle 的包,DSH 一定拒绝安装:不白跑一趟 pnpm
368
+ if (rec.inst && rec.inst.b === false) {
369
+ return sendJson(res, 400, { ok: false, message: `${name} 没有声明 dsh.bundle,DSH 不能把它当插件安装` })
370
+ }
326
371
  const command = pluginCommand(`add ${name}`, profile)
327
372
  if (!pluginManager || typeof pluginManager.installBundle !== 'function') {
328
373
  return sendJson(res, 200, { ok: false, message: '这个版本的 DSH 不能在这里装插件,请在终端执行命令', command })
package/plugin/tools.js CHANGED
@@ -25,18 +25,19 @@ const plain = v => JSON.parse(JSON.stringify(v == null ? null : v))
25
25
  const NOTE =
26
26
  '口径:周下载/月下载含 CI、镜像、爬虫流量,不等于用户数;日常基线 = 扣掉发布日与次日后的每日中位数,最接近真实使用量;' +
27
27
  '环比 = 近 7 日比前 7 日;健康度 0~100 = 基线 40% + 增速 25% + 新鲜度 20% + 版本节奏 15%。' +
28
- '只有周下载 Top 约 330 的包有去噪指标,其余为「—」。回答里的数字只能引用这些结果,不要自己推算。'
28
+ '只有周下载 Top 约 330 的包有去噪指标,其余为「—」。回答里的数字只能引用这些结果,不要自己推算。' +
29
+ '推荐前留意每个包下面的 ⚠ 提醒(装不了、终端版、和已装插件重叠),装不了的不要推荐用户装。'
29
30
 
30
31
  const num = n => (n == null ? '—' : Number(n).toLocaleString('en-US'))
31
32
  const pct = n => (n == null ? '—' : (n >= 0 ? '+' : '') + Math.round(n * 100) + '%')
32
33
 
33
- /** 一个包的一行摘要(给模型看) */
34
- function line(r, installed) {
34
+ /** 一个包的一行摘要(给模型看);r.installed / r.notes 由 annotate() 补上 */
35
+ function line(r) {
35
36
  const d = r.deep
36
37
  const parts = [
37
38
  `${r.name}${r.version ? ' v' + r.version : ''}`,
38
39
  r.category ? `[${r.category}]` : '',
39
- installed && installed.has(r.name) ? '(已安装)' : '',
40
+ r.installed ? '(已安装)' : '',
40
41
  ].filter(Boolean).join(' ')
41
42
  const nums = [
42
43
  `周下载 ${num(r.weekly)}`,
@@ -48,7 +49,33 @@ function line(r, installed) {
48
49
  r.relevance != null ? `相关度 ${r.relevance}%` : '',
49
50
  ].filter(Boolean).join(' · ')
50
51
  const desc = r.description ? `\n ${String(r.description).slice(0, 160)}` : ''
51
- return `- ${parts}\n ${nums}${desc}`
52
+ const notes = r.notes && r.notes.length ? `\n ⚠ ${r.notes.join(';')}` : ''
53
+ return `- ${parts}\n ${nums}${desc}${notes}`
54
+ }
55
+
56
+ /**
57
+ * 给每一行补上「已安装」和安装相关的提醒:
58
+ * 能不能装(dsh.bundle)、是不是终端版插件、声明的 DSH 版本要求、和已装的同类插件重叠
59
+ */
60
+ export function annotate(rows, cat, have) {
61
+ const installedByCat = new Map()
62
+ for (const n of have) {
63
+ const rec = cat.packages && cat.packages[n]
64
+ if (!rec || !rec.cat || rec.cat === '其他' || n === 'dsh-pick') continue
65
+ if (!installedByCat.has(rec.cat)) installedByCat.set(rec.cat, [])
66
+ installedByCat.get(rec.cat).push(n)
67
+ }
68
+ return rows.map(r => {
69
+ const rec = (cat.packages && cat.packages[r.name]) || {}
70
+ const inst = rec.inst
71
+ const notes = []
72
+ if (inst && !inst.b) notes.push('没声明 dsh.bundle,DSH 不能把它当插件安装')
73
+ if (inst && inst.p && inst.p !== 'web') notes.push(`这是 ${inst.p} 客户端插件,装进桌面版 / 网页版可能让 DSH 起不来`)
74
+ if (inst && inst.r) notes.push(`声明需要 DSH ${inst.r}`)
75
+ const same = (installedByCat.get(rec.cat || r.category) || []).filter(n => n !== r.name)
76
+ if (same.length && !have.has(r.name)) notes.push(`你已装了同类插件:${same.join('、')},功能可能重叠`)
77
+ return { ...r, installed: have.has(r.name), notes }
78
+ })
52
79
  }
53
80
 
54
81
  /** 排行榜返回的是目录原始记录(字段名短),转成和搜索一样的形状 */
@@ -118,7 +145,7 @@ export async function buildToolDefinitions(deps = {}) {
118
145
  render: (_a, v) => [{
119
146
  type: 'text',
120
147
  text: v.candidates.length
121
- ? `${v.header}\n需求「${v.need}」的候选(按相关度与下载量综合排序):\n${v.candidates.map(r => line(r, new Set(v.installed))).join('\n')}\n\n${NOTE}`
148
+ ? `${v.header}\n需求「${v.need}」的候选(按相关度与下载量综合排序):\n${v.candidates.map(r => line(r)).join('\n')}\n\n${NOTE}`
122
149
  : `${v.header}\n没找到和「${v.need}」相关的插件。可以换个说法,或用 pick_rank 看某一类的排行。`,
123
150
  }],
124
151
  },
@@ -129,8 +156,7 @@ export async function buildToolDefinitions(deps = {}) {
129
156
  limit: clampInt(args.limit, 1, 20, 8),
130
157
  category: CATS.includes(args.category) ? args.category : null,
131
158
  })
132
- const have = installed()
133
- return plain({ header: header(cat), need, candidates, installed: candidates.map(c => c.name).filter(n => have.has(n)) })
159
+ return plain({ header: header(cat), need, candidates: annotate(candidates, cat, installed()) })
134
160
  },
135
161
  }),
136
162
 
@@ -147,7 +173,7 @@ export async function buildToolDefinitions(deps = {}) {
147
173
  type: 'text',
148
174
  text: `${v.header}\n${v.rows.map(r => r.source === 'not-found'
149
175
  ? `- ${r.name}:npm 上找不到,或没有下载数据`
150
- : line(r, new Set(v.installed)) + (r.source === 'live' ? '\n (去噪指标是刚从 npm 实时算的)' : '') + (r.npmUrl ? `\n ${r.npmUrl}` : '')).join('\n')}\n\n${NOTE}`,
176
+ : line(r) + (r.source === 'live' ? '\n (去噪指标是刚从 npm 实时算的)' : '') + (r.npmUrl ? `\n ${r.npmUrl}` : '')).join('\n')}\n\n${NOTE}`,
151
177
  }],
152
178
  },
153
179
  async execute(args) {
@@ -155,8 +181,7 @@ export async function buildToolDefinitions(deps = {}) {
155
181
  const names = cleanNames(args.names, 8)
156
182
  if (!names.length) throw new Error('names 里没有合法的 npm 包名')
157
183
  const rows = (await stats(cat, names)).map(withCatalogFields(cat))
158
- const have = installed()
159
- return plain({ header: header(cat), rows, installed: names.filter(n => have.has(n)) })
184
+ return plain({ header: header(cat), rows: annotate(rows, cat, installed()) })
160
185
  },
161
186
  }),
162
187
 
@@ -177,7 +202,7 @@ export async function buildToolDefinitions(deps = {}) {
177
202
  ...v.best.map(b => `- ${b.label}:${b.winner ? `${b.winner}(${b.value})` : '都没有数据'}`),
178
203
  '',
179
204
  '按健康度排序(没有去噪指标的排在最后):',
180
- ...v.rows.map(r => line(r, new Set(v.installed))),
205
+ ...v.rows.map(r => line(r)),
181
206
  ...(v.missing.length ? ['', `查不到:${v.missing.join('、')}`] : []),
182
207
  '',
183
208
  NOTE,
@@ -206,8 +231,7 @@ export async function buildToolDefinitions(deps = {}) {
206
231
  return { label: m.label, winner: vals[0][0], value: m.fmt(vals[0][1]) }
207
232
  })
208
233
  rows.sort((a, b) => ((b.deep && b.deep.score) ?? -1) - ((a.deep && a.deep.score) ?? -1))
209
- const have = installed()
210
- return plain({ header: header(cat), best, rows, missing, installed: names.filter(n => have.has(n)) })
234
+ return plain({ header: header(cat), best, rows: annotate(rows, cat, installed()), missing })
211
235
  },
212
236
  }),
213
237
 
@@ -224,7 +248,7 @@ export async function buildToolDefinitions(deps = {}) {
224
248
  schema: ANY_JSON,
225
249
  render: (_a, v) => [{
226
250
  type: 'text',
227
- text: `${v.header}\n排行:${v.category || '全部'} · 按${v.metricLabel}\n${v.rows.map((r, i) => `${i + 1}.${line(r, new Set(v.installed)).slice(1)}`).join('\n')}\n\n${NOTE}`,
251
+ text: `${v.header}\n排行:${v.category || '全部'} · 按${v.metricLabel}\n${v.rows.map((r, i) => `${i + 1}.${line(r).slice(1)}`).join('\n')}\n\n${NOTE}`,
228
252
  }],
229
253
  },
230
254
  async execute(args) {
@@ -233,8 +257,7 @@ export async function buildToolDefinitions(deps = {}) {
233
257
  const metric = LABELS[args.metric] ? args.metric : 'baseline'
234
258
  const category = CATS.includes(args.category) ? args.category : null
235
259
  const rows = rank(cat, { metric, category, limit: clampInt(args.limit, 1, 30, 10) }).map(fromRec)
236
- const have = installed()
237
- return plain({ header: header(cat), metric, metricLabel: LABELS[metric], category, rows, installed: rows.map(r => r.name).filter(n => have.has(n)) })
260
+ return plain({ header: header(cat), metric, metricLabel: LABELS[metric], category, rows: annotate(rows, cat, installed()) })
238
261
  },
239
262
  }),
240
263
  ]
package/web/panel.html CHANGED
@@ -113,6 +113,11 @@ h1{margin:0;font-size:19px;font-weight:650;letter-spacing:-.2px}
113
113
  .inst.confirm{background:var(--accent);color:#fff}
114
114
  .inst:disabled{opacity:.6;cursor:default}
115
115
  .badge-in{font-size:10.5px;color:var(--ok-text);background:var(--ok-bg);border-radius:6px;padding:2px 8px;white-space:nowrap}
116
+ .badge-no{font-size:10.5px;color:var(--t3);background:var(--soft);border-radius:6px;padding:2px 8px;white-space:nowrap}
117
+ /* 能不能装:兼容 / 装不了的原因 / 已装同类 */
118
+ .cand .chk{display:flex;flex-wrap:wrap;gap:4px 10px;margin-top:7px;font-size:10.5px;line-height:1.5}
119
+ .cand .chk .good{color:var(--ok-text)}
120
+ .cand .chk .warn{color:var(--warn-text)}
116
121
  .toast{position:fixed;left:50%;bottom:18px;transform:translateX(-50%);z-index:90;max-width:calc(100% - 24px);
117
122
  background:var(--text);color:var(--bg);font-size:12px;line-height:1.6;padding:8px 14px;border-radius:9px;
118
123
  box-shadow:0 4px 16px var(--shadow);opacity:0;pointer-events:none;transition:opacity .2s}