dsh-aupdate 0.7.3 → 0.8.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.
@@ -0,0 +1,36 @@
1
+ # 从 dsh-plugin-upgrader 学什么(差距清单)
2
+
3
+ 对照对象:[zuwenyin/dsh-plugin-upgrader](https://github.com/zuwenyin/dsh-plugin-upgrader) 1.10.0(MIT,npm 上有 provenance 证明)。
4
+ 它和 dsh-aupdate 是同类:都在插件页补「一键升级」。区别是它手动触发、把精力放在**版本可见性和安装前后的边界**上,
5
+ aupdate 自动跑、把精力放在**调度和让开**上。
6
+
7
+ 这份清单是 0.8.0 的施工依据:只有能落在 aupdate 现有架构里的项才做,做了的写明代价,没做的写明为什么。
8
+
9
+ ## 可借鉴项
10
+
11
+ | 能力 | 它怎么做 | aupdate 0.8.0 | 代价 / 边界 |
12
+ | --- | --- | --- | --- |
13
+ | **按版本比 DSH 兼容性** | 装之前先查该版本 manifest 的 `engines.dsh`(没有才看 `@deepseek-ai/dsh(-*)` 的 peer),和宿主版本比 | ✅ 已实现(`compatOf`),不满足的版本不进安装队列 | 每个**候选**版本多一次几 KB 的 manifest 请求;只在「已经决定要升」时发生,不是每包每轮 |
14
+ | **DSH 版本从哪来** | 从 `process.argv` 的入口往上找 `@deepseek-ai/dsh-app-boot/package.json` | ✅ 已实现(`dshVersion`) | 读不到就返回 null 并**不拦**:宁可漏拦,也不按猜的版本误拦 |
15
+ | **安装源切换** | 顶部「注册表」对话框:自带源 / pluginManager 源 / 自建源,可测速 | ✅ 已实现(`registryMode` + `registryUrl`),三种预设 + 自定义 | 只用 `npm_config_registry` 传给子进程,**不写** `.npmrc`、不改 pnpm 配置;没选源时一个字节都不动 |
16
+ | **镜像落后单独标出** | 官方源已发布、镜像没同步时单独标一行 | ✅ 已实现(`mirrorLagOf`),写进 `lastRun.lagged`,界面按名字列出 | 只有用镜像时对每个包多一次官方源 dist-tags 请求;用官方源时零额外请求 |
17
+ | **重启指引** | 读宿主 pid 与启动方式,给出能完成重启的那一条命令 | ❌ 没做 | aupdate 的默认路径是热生效(hmr),需要重启时已经有「重启后生效」这句;再做一套 pid 追踪属于另一个功能面 |
18
+ | **插件页「版本」标签** | 顶栏多一个标签,展开插件看全部已发布版本,点一下切过去 | ✅ 已实现「版本管理」标签页(`plugins.tab`),复用同一条安装/预检/历史路径 | 按包按需拉缩略 packument;一次一个包,不进首屏 |
19
+ | **多选卸载** | 走宿主 `removeBundle`,先列清单再确认 | ❌ 没做 | 卸载是不可逆动作,和 aupdate「只负责升」的边界冲突;dsh 自带已安装页已经能卸 |
20
+ | **收紧 pnpm 重试等待** | 往 `pnpm-workspace.yaml` 追加 `fetchTimeout/fetchRetries/...` | ❌ 没做 | 它会改 profile 的共享配置文件,影响该 profile 里**所有** pnpm;这种横切改动该由用户决定,不该由自动更新插件在后台悄悄做 |
21
+ | **「需处理」可归零计数** | 只数用户能自己修的问题 | ⚠️ 部分:`lagged` / `blocked` 单独列 | 完整版的四项里,「构建待批准」aupdate 根本没有这条路径 |
22
+ | **一键复制诊断** | 纯客户端把版本、源、每行问题拼成 markdown | ❌ 没做 | 低价值;`/state` 已经把 `dshVersion`、`registry`、`lagged`、`blocked` 都吐出来了 |
23
+ | **按版本列表回滚** | 展开插件看全部已发布版本 | ❌ 没做 | 要读整份 packument(最大单包 26 MB);aupdate 滚回的是**自己装过**的版本,记录在本地,不需要联网 |
24
+
25
+ ## 刻意不照搬的
26
+
27
+ - **整份 packument 换版本列表**:它为了版本历史和兼容性标记读 packument,aupdate 一直只用 `dist-tags` 那个几百字节的端点(24 个包 2.88 MB → 655 B)。按包按需读单个版本 manifest 是更便宜的等价做法。
28
+ - **in-place 替换(先摘 manifest 再装)**:它靠临时改 profile 的 `package.json` 做到「不卸载换版本」,配了 journal 和写入锁。aupdate 走 `dsh plugin add pkg@version`,这条命令本身就会换版本;再自己动 manifest 等于和 plugin-manager 抢同一份文件,风险大于收益。
29
+ - **自动写 pnpm 配置**:见上表。
30
+
31
+ ## 0.8.0 的验收点
32
+
33
+ 1. 没选安装源时:`/state.registry === ''`,dist-tags 仍走官方源,安装命令环境变量不变。
34
+ 2. 选镜像时:`lastRun.lagged` 能列出「镜像 x.y.z、官方 a.b.c」。
35
+ 3. 目标版本要求 `DSH >=0.3.0` 而宿主是 0.2.x:该版本不进 `updates`,`lastRun.blocked` 有它,日志一行 `compatBlocked`。
36
+ 4. 服务器读不到 DSH 版本:`/state.dshVersion === null`,兼容性预检不拦任何包(回到改造前行为)。
package/index.js CHANGED
@@ -234,6 +234,22 @@ function makeLogTemplates(lang) {
234
234
  ? `清理${kind}:删掉 ${rows} 条超过 ${days} 天的`
235
235
  : `Cleaned ${kind}: removed ${rows} entr${rows === 1 ? 'y' : 'ies'} older than ${days} day(s)`),
236
236
  cleanSkipped: (kind) => (zh ? `${kind}没有需要清理的` : `Nothing to clean in ${kind}`),
237
+ compatBlocked: (name, version, range, dsh) => (zh
238
+ ? `${name}@${version} 跳过:要求 DSH ${range},当前 ${dsh}`
239
+ : `${name}@${version} skipped: needs DSH ${range}, host is ${dsh}`),
240
+ mirrorLag: (name, upstream, mirror) => (zh
241
+ ? `${name} 镜像落后:镜像 ${mirror},官方 ${upstream}`
242
+ : `${name} mirror lag: mirror ${mirror}, upstream ${upstream}`),
243
+ registryPicked: (source) => (zh ? `安装源:${source}` : `Registry: ${source}`),
244
+ switching: (name, from, to) => (zh
245
+ ? '切换版本:' + name + ' ' + from + ' → ' + to
246
+ : 'Switching: ' + name + ' ' + from + ' → ' + to),
247
+ switched: (name, from, to) => (zh
248
+ ? '已切换:' + name + ' ' + from + ' → ' + to
249
+ : 'Switched: ' + name + ' ' + from + ' → ' + to),
250
+ reloaded: (status, reason) => (zh
251
+ ? '就地生效:' + status + (reason ? '(' + reason + ')' : '')
252
+ : 'Apply in place: ' + status + (reason ? ' (' + reason + ')' : '')),
237
253
  ready: (minutes, autoApply, hotReload) => (zh
238
254
  ? `已就绪:每 ${minutes} 分钟检查一次,自动安装=${onOff(autoApply)},就地生效=${onOff(hotReload)}`
239
255
  : `Ready: every ${minutes} min, autoApply=${onOff(autoApply)}, hotReload=${onOff(hotReload)}`),
@@ -269,6 +285,15 @@ function makeReasonTemplates(lang) {
269
285
  noInstalled: () => (zh ? '读不到已装版本' : 'Installed version unreadable'),
270
286
  suppressed: (stamp) => (zh ? `上次安装失败,${stamp} UTC 前不再重试` : `Install failed before; not retried until ${stamp} UTC`),
271
287
  lookupFailed: (msg) => (zh ? `查不到:${msg}` : `Lookup failed: ${msg}`),
288
+ compatBlocked: (version, range, dsh) => (zh
289
+ ? `${version} 要求 DSH ${range},当前宿主是 ${dsh},没装`
290
+ : `${version} needs DSH ${range}; this host is ${dsh}, not installed`),
291
+ incompatible: (range, dsh) => (zh
292
+ ? `已装的版本要求 DSH ${range},当前宿主是 ${dsh}`
293
+ : `The installed version needs DSH ${range}; this host is ${dsh}`),
294
+ mirrorLag: (upstream, mirror) => (zh
295
+ ? `镜像还停在 ${mirror},官方源已经是 ${upstream}`
296
+ : `The mirror still has ${mirror}; upstream is at ${upstream}`),
272
297
  agentsBusy: (n) => (zh ? `${n} 个子任务在跑` : `${n} subagent(s) running`),
273
298
  sessionActive: (age) => (zh ? `会话在 ${ageText(age)} 分钟前还在写入` : `Session was written ${ageText(age)} min ago`),
274
299
  noDeps: () => (zh ? '这个 profile 里没有可检查的依赖' : 'No dependencies to check in this profile'),
@@ -514,6 +539,8 @@ const OVERRIDEABLE = [
514
539
  'enabled', 'autoApply', 'hotReload', 'checkOnStart', 'idleOnly', 'notify',
515
540
  'intervalMinutes', 'firstDelayMinutes', 'exclude',
516
541
  'allowMajor', 'allowPrerelease',
542
+ // 安装源与兼容性预检(0.8.0 借自 dsh-plugin-upgrader)。
543
+ 'registryMode', 'registryUrl', 'compatCheck',
517
544
  // 调度:四种节奏 + 失败抑制时长。这些键不写进 Config schema,
518
545
  // 只活在覆盖层里——Config 的字段类型是宿主校验的,加错一个类型
519
546
  // 会在加载期直接抛错,而覆盖层是我们自己的文件,改坏了只影响这一项。
@@ -706,6 +733,13 @@ function settingsOf(config) {
706
733
  // 发现可更新版本时是否弹出提醒。默认开着:定时更新最容易出的事,是它一直在
707
734
  // 后台装,用户根本不知道装了什么、装到哪一版。
708
735
  notify: booleanSetting(config, 'notify', true),
736
+ // 安装源:默认跟随 pnpm,选别的才动(生效值见 registryOf)。
737
+ registryMode: registryModeOf(config),
738
+ registryUrl: typeof config?.registryUrl === 'string' ? config.registryUrl : '',
739
+ registry: registryOf(config),
740
+ // 兼容性预检:装之前先看目标版本声明的 DSH 范围。默认开——宿主闸门是在
741
+ // bundle 已经卸下之后才拒绝的,等它拒绝就已经晚了。
742
+ compatCheck: booleanSetting(config, 'compatCheck', true),
709
743
  intervalMinutes: numberSetting(config, 'intervalMinutes', 1440, 10, 10080),
710
744
  firstDelayMinutes: numberSetting(config, 'firstDelayMinutes', 5, 0, 1440),
711
745
  exclude: stringList(config?.exclude),
@@ -863,6 +897,13 @@ function readLastRun() {
863
897
  ? raw.reason
864
898
  : (raw.reason !== null && typeof raw.reason === 'object' ? raw.reason : ''),
865
899
  snapshot: typeof raw.snapshot === 'string' ? raw.snapshot : '',
900
+ // 0.7.x 及更早没有这两项;缺了就是空数组,不当成坏数据。
901
+ lagged: Array.isArray(raw.lagged)
902
+ ? raw.lagged.filter((row) => row !== null && typeof row === 'object' && typeof row.name === 'string')
903
+ : [],
904
+ blocked: Array.isArray(raw.blocked)
905
+ ? raw.blocked.filter((row) => row !== null && typeof row === 'object' && typeof row.name === 'string')
906
+ : [],
866
907
  }
867
908
  }
868
909
 
@@ -1090,6 +1131,343 @@ function compareVersions(a, b) {
1090
1131
  function distTagFor(pkgName) {
1091
1132
  return NEXT_TAG_SCOPES.some((prefix) => pkgName.startsWith(prefix)) ? 'next' : 'latest'
1092
1133
  }
1134
+
1135
+ /* ── 安装源 / 兼容性预检 / 镜像落后 ─────────────────────────────────────
1136
+ *
1137
+ * 这三样是从 dsh-plugin-upgrader 学来的(差距清单见 docs/BORROWED-FROM-UPGRADER.md),
1138
+ * 但按 aupdate 自己的量级实现:
1139
+ *
1140
+ * - 安装源:没选就不干预——dist-tags 走官方源、pnpm 用自己配置的源,和改造前
1141
+ * 一个字节都不差;选了才把 dist-tags 和 npm_config_registry 一起换过去。
1142
+ * - 兼容性预检:只在「已经决定要装这个版本」时读一次该版本的 manifest(几 KB),
1143
+ * 不像竞品那样为了版本列表去拉整份 packument(24 个包 2.88 MB)。
1144
+ * - 镜像落后:只有用了镜像才多查一次官方源的 dist-tags,默认零额外请求。
1145
+ */
1146
+ const OFFICIAL_REGISTRY = 'https://registry.npmjs.org'
1147
+ const REGISTRY_MIRROR = 'https://registry.npmmirror.com'
1148
+ const REGISTRY_MODES = ['pnpm', 'npmjs', 'mirror', 'custom']
1149
+
1150
+ function registryModeOf(config) {
1151
+ const mode = typeof config?.registryMode === 'string' ? config.registryMode : ''
1152
+ return REGISTRY_MODES.includes(mode) ? mode : 'pnpm'
1153
+ }
1154
+
1155
+ /**
1156
+ * 生效的源;'' 表示不干预。
1157
+ *
1158
+ * 自定义源只认 http(s) 并去掉尾部斜杠:后头是直接拼 URL 的,不校验的话一个
1159
+ * file: 或者带空格的串会变成更难查的「查不到版本」。
1160
+ */
1161
+ function registryOf(config) {
1162
+ const mode = registryModeOf(config)
1163
+ if (mode === 'pnpm') return ''
1164
+ if (mode === 'npmjs') return OFFICIAL_REGISTRY
1165
+ if (mode === 'mirror') return REGISTRY_MIRROR
1166
+ const raw = typeof config?.registryUrl === 'string' ? config.registryUrl.trim().replace(/\/+$/u, '') : ''
1167
+ return /^https?:\/\/[^\s]+$/iu.test(raw) ? raw : ''
1168
+ }
1169
+
1170
+ /** 查 dist-tags 用的基地址:没选源也走官方源(和改造前一致)。 */
1171
+ function tagsBaseOf(registry) {
1172
+ return registry === '' ? OFFICIAL_REGISTRY : registry
1173
+ }
1174
+
1175
+ /**
1176
+ * 当前宿主真正在跑的 DSH 版本。
1177
+ *
1178
+ * 兼容性闸门比的是 @deepseek-ai/dsh-app-boot 的版本——入口加载的是哪一份,闸门
1179
+ * 就用哪一份。桌面版入口在 app.asar 里,命令行启动看到的是 profile 里那份,两者
1180
+ * 可能不是同一个构建;从入口往上找是两种布局都对读法,读一个写死的路径会在两者
1181
+ * 不一致时骗人。读不到就返回 null:宁可漏拦,也不要按猜的版本误拦。
1182
+ */
1183
+ let dshVersionMemo = null
1184
+ const RUNTIME_PACKAGE = '@deepseek-ai/dsh-app-boot'
1185
+
1186
+ function dshVersion() {
1187
+ if (dshVersionMemo !== null) return dshVersionMemo
1188
+ const versionAt = (file) => {
1189
+ const raw = readJson(file)
1190
+ return raw !== null && typeof raw.version === 'string' && raw.version.trim() !== '' ? raw.version.trim() : null
1191
+ }
1192
+ const beside = (entry) => {
1193
+ let dir = dirname(entry)
1194
+ for (let depth = 0; depth < 10; depth += 1) {
1195
+ const found = versionAt(join(dir, 'node_modules', RUNTIME_PACKAGE, 'package.json'))
1196
+ if (found !== null) return found
1197
+ const up = dirname(dir)
1198
+ if (up === dir) return null
1199
+ dir = up
1200
+ }
1201
+ return null
1202
+ }
1203
+ try {
1204
+ for (const entry of process.argv.slice(1, 7)) {
1205
+ if (typeof entry !== 'string' || !/[.]c?js$/iu.test(entry)) continue
1206
+ const found = beside(entry)
1207
+ if (found !== null) {
1208
+ dshVersionMemo = found
1209
+ return found
1210
+ }
1211
+ }
1212
+ } catch {}
1213
+ return null
1214
+ }
1215
+
1216
+ /**
1217
+ * 一个 range 是否接受这个版本。
1218
+ *
1219
+ * 只实现真正会遇到的那几种写法(比较符组合、^、~、裸版本号、x/星号)。遇到
1220
+ * 看不懂的(||、连字符区间、nested)一律放行:这套逻辑的用途是「提前拦住装不上
1221
+ * 的版本」,漏拦只是回到改造前的行为,误拦却会让一个本来能升的包永远不升。
1222
+ */
1223
+ function satisfiesRange(range, version) {
1224
+ const text = String(range ?? '').trim()
1225
+ if (text === '') return true
1226
+ if (parseVersion(version) === null) return true
1227
+ if (text.includes('||')) return true
1228
+ const parts = text.split(/\s+/u).filter(Boolean)
1229
+ if (parts.length === 0) return true
1230
+ for (const part of parts) if (!satisfiesOne(part, version)) return false
1231
+ return true
1232
+ }
1233
+
1234
+ function satisfiesOne(part, version) {
1235
+ const match = /^(>=|<=|>|<|=|\^|~)?\s*(.+)$/u.exec(part)
1236
+ if (match === null) return true
1237
+ const op = match[1] ?? ''
1238
+ const wantedRaw = match[2].trim()
1239
+ const wanted = parseVersion(wantedRaw)
1240
+ const got = parseVersion(version)
1241
+ if (got === null) return true
1242
+ // 1.x / 1.2.x / * 这类认不出完整版本号的,当通配处理。
1243
+ if (wanted === null) return true
1244
+ const cmp = compareVersions(version, wantedRaw)
1245
+ if (cmp === null) return true
1246
+ const [gotMajor, gotMinor] = got.core
1247
+ const [wantMajor, wantMinor] = wanted.core
1248
+ switch (op) {
1249
+ case '>=': return cmp >= 0
1250
+ case '>': return cmp > 0
1251
+ case '<=': return cmp <= 0
1252
+ case '<': return cmp < 0
1253
+ case '=': return cmp === 0
1254
+ case '^':
1255
+ // ^0.2.1 → >=0.2.1 <0.3.0;^1.2.3 → >=1.2.3 <2.0.0
1256
+ if (cmp < 0) return false
1257
+ if (wantMajor > 0) return gotMajor === wantMajor
1258
+ if (wantMinor > 0) return gotMajor === 0 && gotMinor === wantMinor
1259
+ return gotMajor === 0 && gotMinor === 0 && wanted.core[2] === got.core[2]
1260
+ case '~': return cmp >= 0 && gotMajor === wantMajor && gotMinor === wantMinor
1261
+ default: {
1262
+ const segments = wantedRaw.split('.').length
1263
+ if (segments >= 3) return cmp === 0
1264
+ if (segments === 2) return gotMajor === wantMajor && gotMinor === wantMinor
1265
+ return gotMajor === wantMajor
1266
+ }
1267
+ }
1268
+ }
1269
+
1270
+ /**
1271
+ * 一个已发布版本声明的 DSH 要求。
1272
+ *
1273
+ * 顺序照宿主闸门:有 engines.dsh 就只认它,没有才看 @deepseek-ai/dsh(-*) 的 peer。
1274
+ * 反过来读会把宿主随后会拒绝的版本标成可用,正是这条路径要防的事。
1275
+ */
1276
+ const DSH_PEER = '@deepseek-ai/dsh'
1277
+ const DSH_PEER_PREFIX = '@deepseek-ai/dsh-'
1278
+
1279
+ function dshRequirementOf(manifest) {
1280
+ if (manifest === null || typeof manifest !== 'object') return null
1281
+ const engines = manifest.engines
1282
+ if (engines !== null && typeof engines === 'object' && typeof engines.dsh === 'string' && engines.dsh.trim() !== '') {
1283
+ return { range: engines.dsh.trim().replace(/^workspace:/u, ''), from: 'engines.dsh' }
1284
+ }
1285
+ const peers = manifest.peerDependencies
1286
+ if (peers === null || typeof peers !== 'object') return null
1287
+ const rank = (key) => (key === DSH_PEER ? 0 : key.startsWith(DSH_PEER_PREFIX) ? 1 : 2)
1288
+ const entries = Object.entries(peers)
1289
+ .filter(([key, value]) => rank(key) < 2 && typeof value === 'string' && value !== '' && !value.startsWith('workspace:'))
1290
+ .sort((a, b) => rank(a[0]) - rank(b[0]))
1291
+ if (entries.length === 0) return null
1292
+ return { range: entries[0][1].trim(), from: 'peer ' + entries[0][0] }
1293
+ }
1294
+
1295
+ const manifestCache = new Map()
1296
+
1297
+ /** 单个已发布版本的 manifest(几 KB),带缓存。 */
1298
+ async function versionManifestOf(pkgName, version, registry) {
1299
+ const key = tagsBaseOf(registry) + '|' + pkgName + '|' + version
1300
+ const hit = manifestCache.get(key)
1301
+ if (hit !== undefined && Date.now() - hit.at < TAG_TTL_MS) return hit.value
1302
+ const url = tagsBaseOf(registry) + '/' + pkgName.replace('/', '%2f') + '/' + encodeURIComponent(version)
1303
+ const response = await fetch(url, {
1304
+ headers: { accept: 'application/json' },
1305
+ signal: AbortSignal.timeout(8000),
1306
+ })
1307
+ if (!response.ok) throw new Error('registry ' + response.status)
1308
+ const value = await response.json()
1309
+ manifestCache.set(key, { at: Date.now(), value })
1310
+ if (manifestCache.size > 200) {
1311
+ const oldest = manifestCache.keys().next()
1312
+ if (!oldest.done) manifestCache.delete(oldest.value)
1313
+ }
1314
+ return value
1315
+ }
1316
+
1317
+ /**
1318
+ * 这个版本能不能装在这台宿主上。
1319
+ *
1320
+ * 返回 null 表示「说不了」:DSH 版本读不到、manifest 查不到、这个包根本没声明
1321
+ * 要求——三种情况都不拦,照常装。只有明确不满足时才返回 ok:false。
1322
+ */
1323
+ async function compatOf(pkgName, version, registry) {
1324
+ const dsh = dshVersion()
1325
+ if (dsh === null) return null
1326
+ let manifest
1327
+ try {
1328
+ manifest = await versionManifestOf(pkgName, version, registry)
1329
+ } catch {
1330
+ return null
1331
+ }
1332
+ const need = dshRequirementOf(manifest)
1333
+ if (need === null) return null
1334
+ return { ok: satisfiesRange(need.range, dsh), range: need.range, from: need.from, dsh }
1335
+ }
1336
+
1337
+ /**
1338
+ * 镜像落后:官方源已经有更新的版本,你在用的镜像还没同步。
1339
+ *
1340
+ * 只比 dist-tags 上那一个标签。镜像模式下每个包多一次很小的请求;不选镜像时
1341
+ * 直接返回 null,一个请求都不发。
1342
+ */
1343
+ async function mirrorLagOf(pkgName, registry, mirrorTags) {
1344
+ if (registry === '' || tagsBaseOf(registry) === OFFICIAL_REGISTRY) return null
1345
+ try {
1346
+ const upstream = await registryTags(pkgName, OFFICIAL_REGISTRY)
1347
+ const tag = distTagFor(pkgName)
1348
+ const up = typeof upstream[tag] === 'string' ? upstream[tag] : null
1349
+ const mirror = typeof mirrorTags?.[tag] === 'string' ? mirrorTags[tag] : null
1350
+ if (up === null || mirror === null) return null
1351
+ const cmp = compareVersions(up, mirror)
1352
+ return cmp !== null && cmp > 0 ? { tag, upstream: up, mirror } : null
1353
+ } catch {
1354
+ return null
1355
+ }
1356
+ }
1357
+
1358
+ /* ── 版本管理 ───────────────────────────────────────────────────────────
1359
+ *
1360
+ * 「插件」页多一个标签页,列每个已装插件的全部已发布版本,可以点到某一版。
1361
+ *
1362
+ * 只读缩略 packument(Accept: application/vnd.npm.install-v1+json):它保留
1363
+ * versions 里每个版本的 engines/deprecated,正好是这里要判断的东西,而把
1364
+ * readme、tarball 元数据和 maintainer 全砍掉了。整份 packument 最大单包 26 MB,
1365
+ * 缩略版 10 MB,常见插件只有几 KB —— 这个差别决定了能不能一页列一排包的版本。
1366
+ */
1367
+ const MAX_VERSIONS = 80
1368
+ const versionsCache = new Map()
1369
+ const VERSIONS_TTL_MS = 5 * 60 * 1000
1370
+ const ABBREVIATED_ACCEPT = 'application/vnd.npm.install-v1+json'
1371
+
1372
+ async function publishedVersions(pkgName, registry) {
1373
+ const base = tagsBaseOf(registry)
1374
+ const key = base + '|' + pkgName
1375
+ const hit = versionsCache.get(key)
1376
+ if (hit !== undefined && Date.now() - hit.at < VERSIONS_TTL_MS) return hit.value
1377
+ const url = base + '/' + pkgName.replace('/', '%2f')
1378
+ const response = await fetch(url, {
1379
+ headers: { accept: ABBREVIATED_ACCEPT },
1380
+ // 慢的包(几千个版本那种)在镜像上要几秒;超时就回报失败,不拖住整页。
1381
+ signal: AbortSignal.timeout(15000),
1382
+ })
1383
+ if (!response.ok) throw new Error('registry ' + response.status)
1384
+ const doc = await response.json()
1385
+ const packs = doc?.versions !== null && typeof doc?.versions === 'object' ? doc.versions : {}
1386
+ const tags = doc?.['dist-tags'] !== null && typeof doc?.['dist-tags'] === 'object' ? doc['dist-tags'] : {}
1387
+ const dsh = dshVersion()
1388
+ const rows = []
1389
+ for (const [version, manifest] of Object.entries(packs)) {
1390
+ if (parseVersion(version) === null) continue
1391
+ const need = dshRequirementOf(manifest)
1392
+ rows.push({
1393
+ version,
1394
+ // 宿主闸门读的是同一个字段,这里算出来的结论和它一致。
1395
+ need: need === null ? '' : need.range,
1396
+ ok: need === null || dsh === null ? null : satisfiesRange(need.range, dsh),
1397
+ deprecated: typeof manifest?.deprecated === 'string' && manifest.deprecated !== '',
1398
+ })
1399
+ }
1400
+ rows.sort((a, b) => (compareVersions(b.version, a.version) ?? 0))
1401
+ const tag = distTagFor(pkgName)
1402
+ const value = {
1403
+ name: pkgName,
1404
+ latest: typeof tags.latest === 'string' ? tags.latest : '',
1405
+ tag,
1406
+ tagVersion: typeof tags[tag] === 'string' ? tags[tag] : '',
1407
+ total: rows.length,
1408
+ versions: rows.slice(0, MAX_VERSIONS),
1409
+ }
1410
+ versionsCache.set(key, { at: Date.now(), value })
1411
+ if (versionsCache.size > 60) {
1412
+ const oldest = versionsCache.keys().next()
1413
+ if (!oldest.done) versionsCache.delete(oldest.value)
1414
+ }
1415
+ return value
1416
+ }
1417
+
1418
+ /** 正在切版本时挡住定时轮次,反过来也一样:pnpm 是按 profile 上一把锁的。 */
1419
+ let switching = null
1420
+
1421
+ /**
1422
+ * 把某个插件切到指定版本。
1423
+ *
1424
+ * 和整轮更新走同一条安装路径(installOne → 回读磁盘版本 → 记历史),只是不带
1425
+ * 调度、抑制和单轮上限。兼容性预检在这里同样生效:宿主的闸门要等 bundle 卸下
1426
+ * 之后才拒绝,切到装不上的版本会留下一个半装的样子。
1427
+ */
1428
+ async function switchVersion(ctxRef, pkgName, version) {
1429
+ if (switching !== null || running !== null) return { ok: false, reason: { code: 'runBusy' } }
1430
+ const settings = settingsOf(ctxRef.config)
1431
+ const profileDir = profileDirOf(ctxRef.ctx)
1432
+ const profileName = basename(profileDir)
1433
+ const current = installedVersion(profileDir, pkgName, null)
1434
+ if (current === version) return { ok: true, unchanged: true, from: current, to: version, detail: '' }
1435
+ const compat = await compatOf(pkgName, version, settings.registry)
1436
+ if (compat !== null && !compat.ok) {
1437
+ return { ok: false, from: current, to: version, reason: { code: 'compatBlocked', args: [version, compat.range, compat.dsh] } }
1438
+ }
1439
+ const runner = cliRunner()
1440
+ if (runner === null) return { ok: false, from: current, to: version, reason: { code: 'noCli' } }
1441
+ const lock = takeProfileLock(profileDir, new Date())
1442
+ if (!lock.ok) return { ok: false, from: current, to: version, reason: lock.reason }
1443
+ switching = { name: pkgName, version }
1444
+ try {
1445
+ writeLog('switching', [pkgName, current ?? '?', version])
1446
+ const outcome = await installOne(runner, profileName, profileDir, pkgName, version, settings.registry)
1447
+ if (!outcome.ok) return { ok: false, from: current, to: version, detail: outcome.detail ?? '' }
1448
+ clearFailure(pkgName, version)
1449
+ appendHistory({
1450
+ at: new Date().toISOString(),
1451
+ name: pkgName,
1452
+ from: current ?? '',
1453
+ to: version,
1454
+ tag: '',
1455
+ profile: profileName,
1456
+ rolledBack: false,
1457
+ })
1458
+ writeLog('switched', [pkgName, current ?? '?', version])
1459
+ // 切完就地换代码:和回滚同一条路径(requiredBefore 传空),不重启就能用上。
1460
+ let reload = null
1461
+ if (settings.hotReload) {
1462
+ reload = await hotApply(ctxRef.ctx, [])
1463
+ writeLog('reloaded', [reload?.status ?? 'none', reload?.reason ?? ''])
1464
+ }
1465
+ return { ok: true, from: current, to: version, detail: outcome.detail ?? '', reload: reload?.status ?? 'off' }
1466
+ } finally {
1467
+ switching = null
1468
+ releaseProfileLock(lock)
1469
+ }
1470
+ }
1093
1471
  function profileDirOf(ctx) {
1094
1472
  const base = propOf(serviceOf(ctx, 'hmr'), 'baseDir')
1095
1473
  if (typeof base === 'string' && base !== '') return base
@@ -1195,18 +1573,19 @@ function installedVersion(profileDir, pkgName, spec) {
1195
1573
  const tagCache = new Map()
1196
1574
  const TAG_TTL_MS = 10 * 60 * 1000
1197
1575
 
1198
- function tagCacheGet(pkgName) {
1199
- const hit = tagCache.get(pkgName)
1576
+ /** 缓存键带上源:同一个包在两个源上的答案可以不一样,不能混用。 */
1577
+ function tagCacheGet(key) {
1578
+ const hit = tagCache.get(key)
1200
1579
  if (hit === undefined) return null
1201
1580
  if (Date.now() - hit.at > TAG_TTL_MS) {
1202
- tagCache.delete(pkgName)
1581
+ tagCache.delete(key)
1203
1582
  return null
1204
1583
  }
1205
1584
  return hit.tags
1206
1585
  }
1207
1586
 
1208
- function tagCacheSet(pkgName, tags) {
1209
- tagCache.set(pkgName, { at: Date.now(), tags })
1587
+ function tagCacheSet(key, tags) {
1588
+ tagCache.set(key, { at: Date.now(), tags })
1210
1589
  // 缓存不设上限会随着 profile 换包一直长;几百个包就够用,超出就丢最旧的。
1211
1590
  if (tagCache.size > 400) {
1212
1591
  const oldest = tagCache.keys().next()
@@ -1214,18 +1593,20 @@ function tagCacheSet(pkgName, tags) {
1214
1593
  }
1215
1594
  }
1216
1595
 
1217
- async function registryTags(pkgName) {
1218
- const cached = tagCacheGet(pkgName)
1596
+ async function registryTags(pkgName, base = OFFICIAL_REGISTRY) {
1597
+ const key = base + '|' + pkgName
1598
+ const cached = tagCacheGet(key)
1219
1599
  if (cached !== null) return cached
1220
- const url = 'https://registry.npmjs.org/-/package/' + pkgName.replace('/', '%2f') + '/dist-tags'
1600
+ const url = base + '/-/package/' + pkgName.replace('/', '%2f') + '/dist-tags'
1221
1601
  const response = await fetch(url, {
1222
1602
  headers: { accept: 'application/json' },
1223
- signal: AbortSignal.timeout(10000),
1603
+ // 镜像慢起来很慢,但一个页面不该被它拖住:8 秒拿不到就回报失败。
1604
+ signal: AbortSignal.timeout(base === OFFICIAL_REGISTRY ? 10000 : 8000),
1224
1605
  })
1225
1606
  if (!response.ok) throw new Error('registry ' + response.status)
1226
1607
  const tags = await response.json()
1227
1608
  if (tags === null || typeof tags !== 'object') throw new Error('没有 dist-tags')
1228
- tagCacheSet(pkgName, tags)
1609
+ tagCacheSet(key, tags)
1229
1610
  return tags
1230
1611
  }
1231
1612
  /**
@@ -1304,11 +1685,15 @@ function runOnce(command, args, options) {
1304
1685
  })
1305
1686
  }
1306
1687
 
1307
- async function installOne(runner, profileName, profileDir, pkgName, version) {
1688
+ async function installOne(runner, profileName, profileDir, pkgName, version, registry = '') {
1308
1689
  const args = [...runner.prefix, 'plugin', '--profile', profileName, 'add', pkgName + '@' + version]
1690
+ // 选了安装源就让 pnpm 也走这个源:npm_config_registry 是 pnpm 也认的变量,
1691
+ // 只作用于这个子进程,不动 profile 的 .npmrc,也不动 pnpm 自己的配置。
1692
+ const env = { ...runner.env, CI: '1' }
1693
+ if (registry !== '') env.npm_config_registry = registry
1309
1694
  const result = await runOnce(runner.command, args, {
1310
1695
  cwd: profileDir,
1311
- env: { ...runner.env, CI: '1' },
1696
+ env,
1312
1697
  shell: runner.shell === true,
1313
1698
  timeoutMs: INSTALL_TIMEOUT_MS,
1314
1699
  })
@@ -1745,6 +2130,9 @@ async function runCycle(mode, ctxRef) {
1745
2130
  report.reason = { code: 'noDeps' }
1746
2131
  return report
1747
2132
  }
2133
+ // 镜像落后 / 兼容性拦下的明细:这一轮结束后写进 lastRun,界面按名字展示。
2134
+ const lagged = []
2135
+ const blocked = []
1748
2136
  for (let i = 0; i < deps.length; i += FETCH_CONCURRENCY) {
1749
2137
  // 每批之间让出一次事件循环:同步读 package.json 和结果合批都在主线程上,
1750
2138
  // 一口气跑完 24 个包会让界面掉帧。setImmediate 只让一次,代价可以忽略。
@@ -1753,9 +2141,17 @@ async function runCycle(mode, ctxRef) {
1753
2141
  const answers = await Promise.all(batch.map(async (dep) => {
1754
2142
  const current = installedVersion(profileDir, dep.name, dep.spec)
1755
2143
  try {
1756
- const tags = await registryTags(dep.name)
2144
+ // 换了源就按那个源查:缓存键带 base,两个源的答案不会串。
2145
+ const tags = await registryTags(dep.name, tagsBaseOf(settings.registry))
1757
2146
  const tag = distTagFor(dep.name)
1758
2147
  const target = typeof tags[tag] === 'string' ? tags[tag] : null
2148
+ // 用了镜像时顺手比一次官方源。它不改变这一轮的判断,但「已经是最新」
2149
+ // 这时候可能是假的——镜像没同步,官方源其实已经发了新版本。
2150
+ const lag = await mirrorLagOf(dep.name, settings.registry, tags)
2151
+ if (lag !== null) {
2152
+ lagged.push({ name: dep.name, installed: current, ...lag })
2153
+ writeLog('mirrorLag', [dep.name, lag.upstream, lag.mirror])
2154
+ }
1759
2155
  if (target === null) return { name: dep.name, current, why: { code: 'noTag', args: [tag] } }
1760
2156
  if (current === null) return { name: dep.name, current, why: { code: 'noInstalled' } }
1761
2157
  const verdict = upgradeVerdict(target, current, tag, settings)
@@ -1764,6 +2160,16 @@ async function runCycle(mode, ctxRef) {
1764
2160
  if (verdict.code === 'latest') return null
1765
2161
  return { name: dep.name, current, target, why: verdict.why }
1766
2162
  }
2163
+ // 兼容性预检:宿主闸门要等 bundle 卸下之后才拒绝,那时候快照已经白拍了、
2164
+ // 插件也处于「卸了一半」的样子。这里先问一句,装不了就不进队列。
2165
+ if (settings.compatCheck) {
2166
+ const compat = await compatOf(dep.name, target, settings.registry)
2167
+ if (compat !== null && !compat.ok) {
2168
+ blocked.push({ name: dep.name, target, need: compat.range, dsh: compat.dsh, from: compat.from })
2169
+ writeLog('compatBlocked', [dep.name, target, compat.range, compat.dsh])
2170
+ return { name: dep.name, current, target, why: { code: 'compatBlocked', args: [target, compat.range, compat.dsh] } }
2171
+ }
2172
+ }
1767
2173
  // 这个版本之前装失败过、还在抑制窗口内:这一轮不再试它。
1768
2174
  const until = suppressedUntil(dep.name, target, settings, new Date())
1769
2175
  if (until !== null) {
@@ -1787,6 +2193,8 @@ async function runCycle(mode, ctxRef) {
1787
2193
  else report.skipped.push(answer)
1788
2194
  }
1789
2195
  }
2196
+ report.lagged = lagged
2197
+ report.blocked = blocked
1790
2198
  writeLog('checked', [report.checked, report.updates.length])
1791
2199
  if (report.updates.length === 0) {
1792
2200
  report.reason = { code: 'noUpdates' }
@@ -1852,6 +2260,9 @@ async function runCycle(mode, ctxRef) {
1852
2260
  status: report.status,
1853
2261
  at: report.finishedAt,
1854
2262
  checked: report.checked,
2263
+ // 这一轮「镜像落后」与「兼容性拦下」的明细:界面要能指着名字说清为什么。
2264
+ lagged: Array.isArray(report.lagged) ? report.lagged : [],
2265
+ blocked: Array.isArray(report.blocked) ? report.blocked : [],
1855
2266
  // 结构化存:界面要分开排「包名」和「版本」,句子做不到。
1856
2267
  updates: report.updates.map((item) => ({ name: item.name, from: item.current ?? '', to: item.target })),
1857
2268
  installed: report.installed.map((item) => item.name + '@' + item.version + (item.ok ? '' : ' !failed')),
@@ -1886,7 +2297,7 @@ async function applyUpdates(ctxRef, report, settings, runner, profileDir, profil
1886
2297
  slowTimer.unref?.()
1887
2298
  let outcome
1888
2299
  try {
1889
- outcome = await installOne(runner, profileName, profileDir, update.name, update.target)
2300
+ outcome = await installOne(runner, profileName, profileDir, update.name, update.target, settings.registry)
1890
2301
  } finally {
1891
2302
  clearTimeout(slowTimer)
1892
2303
  }
@@ -1988,7 +2399,7 @@ async function rollbackOne(ctxRef, entryName) {
1988
2399
  if (!lock.ok) return { ok: false, reason: lock.reason }
1989
2400
  let outcome
1990
2401
  try {
1991
- outcome = await installOne(runner, profileName, profileDir, row.name, row.from)
2402
+ outcome = await installOne(runner, profileName, profileDir, row.name, row.from, settings.registry)
1992
2403
  } finally {
1993
2404
  releaseProfileLock(lock)
1994
2405
  }
@@ -2205,6 +2616,10 @@ function settingsSnapshot(config, ctxRef, lang) {
2205
2616
  overrides: readOverrides(),
2206
2617
  // 「关于 aupdate」显示用;随 package.json 自动更新,无需手改前端。
2207
2618
  version: pluginVersion,
2619
+ // 这台宿主真正在跑的 DSH 版本:兼容性预检就是按它比的,界面也要能看见它。
2620
+ dshVersion: dshVersion(),
2621
+ // 生效的安装源('' = 跟随 pnpm)。
2622
+ registry: settings.registry,
2208
2623
  // 运行中的进度:没在跑时为 null,设置页据此决定要不要显示进度条。
2209
2624
  progress: progress === null ? null : { ...progress },
2210
2625
  lastRun: lastRun === null ? null : {
@@ -2214,6 +2629,8 @@ function settingsSnapshot(config, ctxRef, lang) {
2214
2629
  checked: lastRun.checked,
2215
2630
  updates: lastRun.updates,
2216
2631
  installed: lastRun.installed,
2632
+ lagged: Array.isArray(lastRun.lagged) ? lastRun.lagged : [],
2633
+ blocked: Array.isArray(lastRun.blocked) ? lastRun.blocked : [],
2217
2634
  reload: lastRun.reload,
2218
2635
  snapshot: lastRun.snapshot ?? '',
2219
2636
  },
@@ -2296,6 +2713,23 @@ function registerRoutes(scope, ctxRef) {
2296
2713
  sendJson(res, 200, readLogTail(url.searchParams.get('lines'), url.searchParams.get('lang')))
2297
2714
  return
2298
2715
  }
2716
+ if (suffix === '/versions') {
2717
+ // 一次只看一个包的版本列表:整页一次拉一排包,镜像上会很慢。
2718
+ const target = url.searchParams.get('name') ?? ''
2719
+ if (target === '') {
2720
+ sendJson(res, 400, { error: 'missing name' })
2721
+ return
2722
+ }
2723
+ try {
2724
+ const live = settingsOf(ctxRef.config)
2725
+ const listed = await publishedVersions(target, live.registry)
2726
+ const profileDir = profileDirOf(ctxRef.ctx)
2727
+ sendJson(res, 200, { ...listed, installed: installedVersion(profileDir, target, null) })
2728
+ } catch (error) {
2729
+ sendJson(res, 502, { error: oneLine(error?.message ?? error, 200) })
2730
+ }
2731
+ return
2732
+ }
2299
2733
  sendJson(res, 404, { error: 'unknown endpoint' })
2300
2734
  return
2301
2735
  }
@@ -2321,6 +2755,21 @@ function registerRoutes(scope, ctxRef) {
2321
2755
  sendJson(res, 200, settingsSnapshot(ctxRef.config, ctxRef, url.searchParams.get('lang')))
2322
2756
  return
2323
2757
  }
2758
+ if (suffix === '/switch') {
2759
+ const body = await readBody(req)
2760
+ const target = typeof body?.name === 'string' ? body.name : ''
2761
+ const version = typeof body?.version === 'string' ? body.version : ''
2762
+ if (target === '' || version === '') {
2763
+ sendJson(res, 400, { error: 'missing name or version' })
2764
+ return
2765
+ }
2766
+ const outcome = await switchVersion(ctxRef, target, version)
2767
+ sendJson(res, outcome.ok ? 200 : 409, {
2768
+ ...outcome,
2769
+ reason: outcome.reason === undefined ? '' : renderReason(outcome.reason, url.searchParams.get('lang')),
2770
+ })
2771
+ return
2772
+ }
2324
2773
  if (suffix === '/rollback') {
2325
2774
  const body = await readBody(req)
2326
2775
  const target = typeof body?.name === 'string' ? body.name : ''