dsh-pick 0.4.1 → 0.4.2

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/bin/dsh-pick.js CHANGED
@@ -11,7 +11,7 @@ import { createServer } from 'node:http'
11
11
  import { readFile } from 'node:fs/promises'
12
12
  import { join, extname } from 'node:path'
13
13
  import { fileURLToPath } from 'node:url'
14
- import { buildCatalog, loadCatalog, searchByNeed, rank, stats, normalize } from '../lib/engine.js'
14
+ import { buildCatalog, loadCatalog, searchByNeed, rank, stats, liveStats, normalize } from '../lib/engine.js'
15
15
 
16
16
  const PKG_ROOT = fileURLToPath(new URL('..', import.meta.url))
17
17
  const [, , cmd = 'help', ...rest] = process.argv
@@ -117,6 +117,14 @@ async function main() {
117
117
  try {
118
118
  let p = decodeURIComponent(new URL(req.url, 'http://x').pathname)
119
119
  if (p === '/') p = '/web/panel.html'
120
+ // 「我的监控」的刷新:实时查 npm(和插件里的 /api-dsh-pick/live 一样)
121
+ if (p === '/live') {
122
+ const names = [...new Set((new URL(req.url, 'http://x').searchParams.get('names') || '').split(',')
123
+ .map(s => s.trim()).filter(s => /^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i.test(s)))].slice(0, 30)
124
+ res.writeHead(names.length ? 200 : 400, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
125
+ res.end(JSON.stringify(names.length ? await liveStats(names) : { error: '没有合法的包名' }))
126
+ return
127
+ }
120
128
  const prefix = Object.keys(ROOTS).find(k => p.startsWith(k))
121
129
  if (!prefix) { res.writeHead(403).end('forbidden'); return }
122
130
  let buf
package/lib/engine.js CHANGED
@@ -387,15 +387,43 @@ export async function stats(catalog, names) {
387
387
  out.push({ source: 'catalog', ...serialize(rec) })
388
388
  continue
389
389
  }
390
- const live = await fetchLive(name)
391
- out.push(live ? { source: 'live', ...live } : { source: 'not-found', name })
390
+ const [live, dl] = await Promise.all([fetchLive(name), searchDownloads(name)])
391
+ // 周 / 月下载和目录同一口径(见 liveStats)
392
+ out.push(live ? { source: 'live', ...live, ...(dl ? { weekly: dl.weekly, monthly: dl.monthly } : {}) } : { source: 'not-found', name })
392
393
  }
393
394
  return out
394
395
  }
395
396
 
396
- async function fetchLive(name) {
397
- const today = new Date().toISOString().slice(0, 10)
397
+ /**
398
+ * 实时查几个包(「我的监控」的刷新):统计截止日只探测一次,下载量接口低并发(稍高就 429)。
399
+ * 不带 30 天日序列(太长,界面用不上)
400
+ * @returns {Promise<{at: string, anchor: string, rows: object[]}>}
401
+ */
402
+ export async function liveStats(names) {
398
403
  const anchor = await resolveAnchor()
404
+ const rows = await pool(names, 2, async name => {
405
+ const [r, dl] = await Promise.all([fetchLive(name, anchor), searchDownloads(name)])
406
+ if (!r && !dl) return { name, found: false }
407
+ const { daily, keywords, ...rest } = r || { name, deep: null }
408
+ // 周下载 / 月下载用搜索接口的:和目录同一口径(目录就是从它抓的),而且比下载统计接口新——
409
+ // 下载统计接口常常只到几天前,拿它和目录比会凭空「跌」一截
410
+ return dl
411
+ ? { found: true, ...rest, weekly: dl.weekly, monthly: dl.monthly, latest: rest.latest || dl.version }
412
+ : { found: true, ...rest }
413
+ })
414
+ return { at: new Date().toISOString(), anchor, rows }
415
+ }
416
+
417
+ /** npm 搜索接口里这个包的周 / 月下载(按包名精确匹配;查不到返回 null) */
418
+ async function searchDownloads(name) {
419
+ const d = await jget(`${SEARCH_API}?text=${encodeURIComponent(name)}&size=5`, 2)
420
+ const o = d && Array.isArray(d.objects) && d.objects.find(x => x.package && x.package.name === name)
421
+ return o && o.downloads ? { weekly: o.downloads.weekly || 0, monthly: o.downloads.monthly || 0, version: o.package.version } : null
422
+ }
423
+
424
+ async function fetchLive(name, knownAnchor) {
425
+ const today = new Date().toISOString().slice(0, 10)
426
+ const anchor = knownAnchor || await resolveAnchor()
399
427
  const start = shiftDate(anchor, -29)
400
428
  const [range, total, meta] = await Promise.all([
401
429
  jget(`${DL_API}/range/${start}:${anchor}/${enc(name)}`),
@@ -466,4 +494,4 @@ function serialize(rec) {
466
494
  }
467
495
 
468
496
 
469
- export default { buildCatalog, loadCatalog, reloadCatalog, searchByNeed, rank, stats, CATALOG_PATH, resolveAnchor }
497
+ export default { buildCatalog, loadCatalog, reloadCatalog, searchByNeed, rank, stats, liveStats, CATALOG_PATH, resolveAnchor }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-pick",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "description": "帮你在 DSH 生态里选对插件:说需求 → 找候选 → 多维比较 → 出结论。下载量是证据,AI 是推理。",
5
5
  "type": "module",
6
6
  "main": "./plugin/index.js",
package/plugin/index.js CHANGED
@@ -14,6 +14,7 @@
14
14
  // POST /api-dsh-pick/update 更新到 npm 最新版(交给 DSH 的插件管理器)
15
15
  // POST /api-dsh-pick/uninstall 从 DSH 卸载本插件
16
16
  // GET /api-dsh-pick/installed DSH 里已装的插件名(面板的「已安装」标记)
17
+ // GET /api-dsh-pick/live?names=a,b 实时查 npm(「我的监控」的刷新,最多 30 个)
17
18
  // POST /api-dsh-pick/install 安装目录里的某个插件 { name }
18
19
  //
19
20
  // 另外注册 4 个 AI 工具(plugin/tools.js):对话里的 AI 能自己查目录、比较插件。
@@ -24,7 +25,7 @@ import { readFile } from 'node:fs/promises'
24
25
  import { fileURLToPath } from 'node:url'
25
26
  import { join } from 'node:path'
26
27
  import { registerTools } from './tools.js'
27
- import { loadCatalog } from '../lib/engine.js'
28
+ import { loadCatalog, liveStats } from '../lib/engine.js'
28
29
  import { refreshCatalog, remoteState, CHECK_EVERY_MS } from '../lib/remote.js'
29
30
 
30
31
  /** 本包根目录:插件就是完整的 dsh-pick 包 */
@@ -148,6 +149,12 @@ function installedNames(pluginManager) {
148
149
 
149
150
  const NAME_RE = /^(@[a-z0-9._-]+\/)?[a-z0-9._-]+$/i
150
151
 
152
+ /** ?names=a,b,c → 合法、去重的包名,最多 30 个(监控列表本身也最多 30 个) */
153
+ export function parseNames(url) {
154
+ const raw = new URL(url || '/', 'http://x').searchParams.get('names') || ''
155
+ return [...new Set(raw.split(',').map(s => s.trim()).filter(s => NAME_RE.test(s)))].slice(0, 30)
156
+ }
157
+
151
158
  function sendJson(res, status, body) {
152
159
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
153
160
  res.end(JSON.stringify(body))
@@ -340,6 +347,21 @@ export function apply(ctx) {
340
347
  },
341
348
  }))
342
349
 
350
+ // 实时数据:「我的监控」点刷新时,直接去 npm 查这几个包(只读公开数据)
351
+ track(ws.register({
352
+ kind: 'exact',
353
+ path: '/api-dsh-pick/live',
354
+ handler: async (req, res) => {
355
+ const names = parseNames(req.url)
356
+ if (!names.length) return sendJson(res, 400, { error: '没有合法的包名' })
357
+ try {
358
+ sendJson(res, 200, await liveStats(names))
359
+ } catch (e) {
360
+ sendJson(res, 502, { error: `查 npm 失败:${e.message}` })
361
+ }
362
+ },
363
+ }))
364
+
343
365
  // 已装的插件(面板卡片上的「已安装」)
344
366
  track(ws.register({
345
367
  kind: 'exact',
package/web/panel.html CHANGED
@@ -107,6 +107,13 @@ h1{margin:0;font-size:19px;font-weight:650;letter-spacing:-.2px}
107
107
  .ai:hover{border-color:color-mix(in srgb,var(--ai) 62%,transparent);
108
108
  background:linear-gradient(135deg,color-mix(in srgb,var(--accent) 22%,transparent),color-mix(in srgb,var(--ai) 28%,transparent))}
109
109
  .section h2 .ai{margin-left:auto;font-weight:650}
110
+ .section h2 .h2-acts{margin-left:auto;display:inline-flex;gap:8px;align-items:center}
111
+ .section h2 .h2-acts .ai{margin-left:0}
112
+ .btn.sm{font-size:11.5px;padding:0 10px;height:24px;border-radius:7px}
113
+ .mon .live{font-size:10px;color:var(--ok-text);background:var(--ok-bg);border-radius:5px;padding:1px 5px;white-space:nowrap}
114
+ .mon .delta{font-size:10.5px;margin-left:3px}
115
+ .mon .delta.up{color:var(--ok)}.mon .delta.down{color:var(--bad)}
116
+ #watchAsOf b{color:var(--t2);font-weight:600}
110
117
  .inst{appearance:none;font-family:inherit;font-size:10.5px;font-weight:600;border-radius:6px;padding:2px 9px;cursor:pointer;
111
118
  border:1px solid var(--accent);background:var(--panel);color:var(--accent);white-space:nowrap}
112
119
  .inst:hover{background:var(--accent-bg)}
@@ -340,6 +347,10 @@ td.down{color:var(--bad);font-weight:600}
340
347
  </div>
341
348
  </div>
342
349
 
350
+ </div>
351
+
352
+ <!-- ============ Tab 2:排行榜 ============ -->
353
+ <div id="tab-rank" class="hidden">
343
354
  <div class="section">
344
355
  <h2>排行榜</h2>
345
356
  <p class="cap">换一种方式发现:按去噪后的指标看整个生态。</p>
@@ -363,11 +374,11 @@ td.down{color:var(--bad);font-weight:600}
363
374
  </div>
364
375
  </div>
365
376
 
366
- <!-- ============ Tab 2:监控 ============ -->
377
+ <!-- ============ Tab 3:监控 ============ -->
367
378
  <div id="tab-watch" class="hidden">
368
379
  <div class="section">
369
- <h2>我的监控<button class="ai hidden" id="aiWatch" title="把监控列表发到对话里,让 AI 看看谁在涨、谁停更了">+AI 看看近况</button></h2>
370
- <p class="cap">存在浏览器本地(localStorage),不上传。数据取自目录,目录每天重建一次。</p>
380
+ <h2>我的监控<span class="h2-acts"><button class="btn ghost sm" id="btnWatchRefresh" title="去 npm 实时查这些插件的最新数据">↻ 刷新</button><button class="ai hidden" id="aiWatch" title="把监控列表发到对话里,让 AI 看看谁在涨、谁停更了">+AI 看看近况</button></span></h2>
381
+ <p class="cap"><span id="watchAsOf"></span>监控列表存在浏览器本地,不上传。点「刷新」去 npm 查最新:版本号、发版时间是即时的;下载量 npm 大约一天更新一次,日常基线和环比按 npm 下载统计算(滞后约 5 天)。</p>
371
382
  <div id="watchList"></div>
372
383
  </div>
373
384
  <div class="section">
package/web/panel.js CHANGED
@@ -7,6 +7,7 @@ const IS_PLUGIN = location.pathname.indexOf('/api-dsh-pick') === 0
7
7
  const P = {
8
8
  words: IS_PLUGIN ? '/api-dsh-pick/words.js' : '/lib/words.js',
9
9
  catalog: IS_PLUGIN ? '/api-dsh-pick/catalog.json' : '/data/catalog.json',
10
+ live: IS_PLUGIN ? '/api-dsh-pick/live' : '/live',
10
11
  }
11
12
 
12
13
  // 嵌在 DSH 里(同源 iframe)才有「+AI」和「安装」:消息交给外层(plugin/client.js)写进当前对话;
@@ -110,9 +111,10 @@ function askVerdict() {
110
111
  }
111
112
 
112
113
  function askWatch() {
113
- const rows = watch().map(n => CAT.packages[n]).filter(Boolean)
114
+ const rows = watch().map(watchRec).filter(Boolean)
115
+ const live = LIVE.at ? `(npm 实时数据,${new Date(LIVE.at).toLocaleString()} 刷新;下载量含 CI / 镜像流量,不等于用户数)` : dataAsOf()
114
116
  return [
115
- `帮我看看我关注的这些 DSH 插件最近怎么样${dataAsOf()}:`,
117
+ `帮我看看我关注的这些 DSH 插件最近怎么样${live}:`,
116
118
  ...rows.map(r => `- ${r.n}(${r.cat}):${factLine(r)}`),
117
119
  '',
118
120
  `谁在涨、谁停更了、有没有该换掉的?${TAIL}`,
@@ -360,8 +362,8 @@ function bindEvents() {
360
362
  b.addEventListener('click', () => {
361
363
  document.querySelectorAll('#tabs button').forEach(x => x.classList.toggle('on', x === b))
362
364
  const t = b.dataset.tab
363
- $('#tab-pick').classList.toggle('hidden', t !== 'pick')
364
- $('#tab-watch').classList.toggle('hidden', t !== 'watch')
365
+ // 每个标签一块内容:tab-pick / tab-rank / tab-watch
366
+ document.querySelectorAll('#tabs button').forEach(x => $('#tab-' + x.dataset.tab).classList.toggle('hidden', x.dataset.tab !== t))
365
367
  })
366
368
  })
367
369
 
@@ -376,6 +378,7 @@ function bindEvents() {
376
378
  $('#aiCands').addEventListener('click', () => cands.length && askAI(askCands()))
377
379
  $('#aiVerdict').addEventListener('click', () => picked.length >= 2 && askAI(askVerdict()))
378
380
  $('#aiWatch').addEventListener('click', () => watch().length && askAI(askWatch()))
381
+ $('#btnWatchRefresh').addEventListener('click', refreshWatch)
379
382
 
380
383
  $('#btnExport').addEventListener('click', exportHtml)
381
384
  $('#btnWatch').addEventListener('click', addPickedToWatch)
@@ -611,9 +614,62 @@ function addPickedToWatch() {
611
614
  alert('已加入我的监控(' + picked.join('、') + ')')
612
615
  }
613
616
 
617
+ /* 刷新:去 npm 实时查监控列表里的包。结果存本地,下次打开还看得到上次刷新的数 */
618
+ const LIVE_KEY = 'dsh-pick-watch-live-v1'
619
+ let LIVE = (() => {
620
+ try { return JSON.parse(localStorage.getItem(LIVE_KEY)) || { at: null, rows: {} } } catch { return { at: null, rows: {} } }
621
+ })()
622
+
623
+ /**
624
+ * 监控卡片用的数据:有实时数据就用实时的(字段换成目录的短名,后面的代码不用分两套),
625
+ * 否则用目录里的。目录里没有、也没刷新过的返回 null
626
+ */
627
+ function watchRec(n) {
628
+ const base = CAT.packages[n]
629
+ const live = LIVE.rows[n]
630
+ if (!live || !live.found) return base || null
631
+ const d = live.deep
632
+ return {
633
+ ...(base || { n, cat: '(目录外)' }),
634
+ n,
635
+ v: live.latest || (base && base.v),
636
+ w: live.weekly,
637
+ m: live.monthly,
638
+ deep: d ? { base: d.baseline, growth: d.growth, cadence: d.cadence, age: d.ageDays, lastRelease: d.lastRelease, versions: d.versions, s: d.score } : null,
639
+ live: true,
640
+ catalogW: base ? base.w : null,
641
+ }
642
+ }
643
+
644
+ async function refreshWatch() {
645
+ const list = watch()
646
+ if (!list.length) return
647
+ const btn = $('#btnWatchRefresh')
648
+ btn.disabled = true
649
+ btn.textContent = '刷新中…'
650
+ try {
651
+ const r = await fetch(`${P.live}?names=${encodeURIComponent(list.join(','))}`, { cache: 'no-store' })
652
+ const j = await r.json()
653
+ if (!r.ok) throw new Error(j.error || 'HTTP ' + r.status)
654
+ LIVE = { at: j.at, anchor: j.anchor, rows: Object.fromEntries(j.rows.map(x => [x.name, x])) }
655
+ try { localStorage.setItem(LIVE_KEY, JSON.stringify(LIVE)) } catch { /* 存不下就只这次有效 */ }
656
+ const miss = j.rows.filter(x => !x.found).map(x => x.name)
657
+ toast(miss.length ? `已刷新;npm 上查不到:${miss.join('、')}` : `已刷新 ${j.rows.length} 个插件`)
658
+ } catch (e) {
659
+ toast('刷新失败:' + e.message + '(检查网络后再试)')
660
+ }
661
+ btn.disabled = false
662
+ btn.textContent = '↻ 刷新'
663
+ renderWatch()
664
+ }
665
+
614
666
  function renderWatch() {
615
667
  const list = watch()
616
668
  $('#watchCount').textContent = list.length ? ` (${list.length})` : ''
669
+ $('#btnWatchRefresh').classList.toggle('hidden', !list.length)
670
+ $('#watchAsOf').innerHTML = !list.length ? ''
671
+ : LIVE.at ? `<b>实时数据</b>,${esc(new Date(LIVE.at).toLocaleString())} 刷新(npm 统计截止 ${esc(LIVE.anchor || '—')})。`
672
+ : `现在显示的是目录数据(截止 <b>${esc(CAT.anchor)}</b>)。`
617
673
  const host = $('#watchList')
618
674
  if (!list.length) {
619
675
  host.innerHTML = '<div class="empty">还没有监控的插件。在「选插件」里挑几个,点「加入我的监控」。</div>'
@@ -622,16 +678,24 @@ function renderWatch() {
622
678
  }
623
679
 
624
680
  host.innerHTML = list.map(n => {
625
- const r = CAT.packages[n]
626
- if (!r) return `<div class="mon"><span class="nm">${esc(n)}</span><span style="color:var(--t3);font-size:11.5px">不在目录中</span><button class="x" data-rm="${esc(n)}">×</button></div>`
681
+ const r = watchRec(n)
682
+ if (!r) return `<div class="mon"><span class="nm">${esc(n)}</span><span style="color:var(--t3);font-size:11.5px">不在目录中,点「刷新」去 npm 查</span><button class="x" data-rm="${esc(n)}">×</button></div>`
627
683
  const d = r.deep
684
+ // 和目录数据比,周下载涨了还是跌了(只在刷新过、差得明显时标)
685
+ let delta = ''
686
+ if (r.live && r.catalogW) {
687
+ const ch = (r.w - r.catalogW) / Math.max(r.catalogW, 1)
688
+ if (Math.abs(ch) >= 0.05) delta = `<span class="delta ${ch > 0 ? 'up' : 'down'}" title="和目录数据(截止 ${esc(CAT.anchor)})相比">${ch > 0 ? '↑' : '↓'}${Math.round(Math.abs(ch) * 100)}%</span>`
689
+ }
628
690
  return `<div class="mon">` +
629
- `<span class="nm">${esc(n)}</span>` +
691
+ `<span class="nm">${esc(n)}${r.v ? ` <span style="color:var(--t3);font-weight:400;font-size:11px">v${esc(r.v)}</span>` : ''}</span>` +
692
+ (r.live ? '<span class="live" title="刚从 npm 查的">实时</span>' : '') +
630
693
  `<span class="mrank">${rankText(r)}</span>` +
631
694
  `<span style="font-size:11.5px;color:var(--t3)">${esc(r.cat)}</span>` +
632
- `<span style="font-size:12px"><b>${num(r.w)}</b>/周</span>` +
695
+ `<span style="font-size:12px"><b>${num(r.w)}</b>/周${delta}</span>` +
633
696
  `<span style="font-size:12px;color:var(--t2)">基线 ${d ? num(d.base) : '—'}</span>` +
634
- `<span class="mlinks">${linkBtns(r)}</span>` +
697
+ `<span style="font-size:12px;color:var(--t2)">${d ? ageText(d.age) + '发版' : ''}</span>` +
698
+ `<span class="mlinks">${linkBtns(r, { icon: true })}</span>` +
635
699
  `<button class="x" data-rm="${esc(n)}">×</button></div>`
636
700
  }).join('')
637
701
 
@@ -639,12 +703,12 @@ function renderWatch() {
639
703
  b.addEventListener('click', () => saveWatch(watch().filter(x => x !== b.dataset.rm)) || renderWatch()))
640
704
 
641
705
  // 对数刻度横条图
642
- const rows = list.map(n => CAT.packages[n]).filter(Boolean)
706
+ const rows = list.map(watchRec).filter(Boolean)
643
707
  const max = Math.max(...rows.map(r => r.w), 1)
644
708
  $('#watchChart').innerHTML = rows.map((r, i) => {
645
709
  const w = Math.max(Math.log10(r.w + 1) / Math.log10(max + 1) * 100, 1.5)
646
- return `<div class="hrow" style="display:grid;grid-template-columns:210px 1fr 78px;align-items:center;gap:12px;padding:6px 0">` +
647
- `<div style="font-size:12px;color:var(--t2);text-align:right;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><i style="display:inline-block;width:8px;height:8px;border-radius:2px;background:${colorOf(i)};margin-right:6px"></i>${esc(r.n)} <span style="color:var(--t3);font-size:10px">#${num(r.rank)}</span></div>` +
710
+ return `<div class="hrow" style="display:grid;grid-template-columns:minmax(80px,38%) 1fr auto;align-items:center;gap:10px;padding:6px 0">` +
711
+ `<div style="font-size:12px;color:var(--t2);text-align:right;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><i style="display:inline-block;width:8px;height:8px;border-radius:2px;background:${colorOf(i)};margin-right:6px"></i>${esc(r.n)}${r.rank ? ` <span style="color:var(--t3);font-size:10px">#${num(r.rank)}</span>` : ''}</div>` +
648
712
  `<div style="height:14px;background:var(--soft);border-radius:4px"><div style="height:100%;width:${w}%;background:${colorOf(i)};border-radius:4px"></div></div>` +
649
713
  `<div style="font-size:12px;font-weight:650;text-align:right">${num(r.w)}</div></div>`
650
714
  }).join('')