dsh-plugin 1.6.12 → 2.0.1

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.
Files changed (131) hide show
  1. package/README.en.md +13 -13
  2. package/README.md +13 -13
  3. package/client/client.js +791 -761
  4. package/client/client.js.map +1 -1
  5. package/lib/http/catalog.js +2 -3
  6. package/lib/http/diagnostics.js +6 -7
  7. package/lib/http/install.js +47 -213
  8. package/lib/http/logs.js +1 -2
  9. package/lib/http/npm-release-age.js +42 -0
  10. package/lib/http/routes.js +8 -7
  11. package/lib/http/settings.js +2 -2
  12. package/lib/http/shared.js +2 -2
  13. package/lib/http/task.js +1 -2
  14. package/lib/index.js +5 -6
  15. package/lib/services/install/install-types.js +4 -4
  16. package/lib/services/install/install.js +1 -1
  17. package/lib/services/install/npm-check.js +3 -2
  18. package/lib/services/install/npm-resolve.js +9 -96
  19. package/lib/services/install/operation-log.js +53 -1
  20. package/lib/services/install/package-entry.js +6 -11
  21. package/lib/services/install/registry-check.js +2 -2
  22. package/lib/services/install/release-target.js +8 -9
  23. package/lib/services/install/task-queue.js +44 -48
  24. package/lib/services/npm-release-age.js +119 -0
  25. package/lib/services/probe.js +4 -4
  26. package/lib/services/profile/installed-versions.js +15 -21
  27. package/lib/services/profile/profile.js +16 -44
  28. package/lib/services/profile/progress.js +8 -11
  29. package/lib/services/settings.js +2 -5
  30. package/lib/types/http/catalog.d.ts +1 -1
  31. package/lib/types/http/install.d.ts +2 -2
  32. package/lib/types/http/npm-release-age.d.ts +2 -0
  33. package/lib/types/http/routes.d.ts +10 -12
  34. package/lib/types/http/shared.d.ts +5 -6
  35. package/lib/types/index.d.ts +7 -8
  36. package/lib/types/services/install/install-types.d.ts +12 -13
  37. package/lib/types/services/install/install.d.ts +1 -1
  38. package/lib/types/services/install/npm-resolve.d.ts +4 -16
  39. package/lib/types/services/install/operation-log.d.ts +9 -0
  40. package/lib/types/services/install/package-entry.d.ts +6 -11
  41. package/lib/types/services/install/release-target.d.ts +7 -8
  42. package/lib/types/services/install/task-queue.d.ts +25 -30
  43. package/lib/types/services/npm-release-age.d.ts +15 -0
  44. package/lib/types/services/probe.d.ts +4 -4
  45. package/lib/types/services/profile/installed-versions.d.ts +5 -7
  46. package/lib/types/services/profile/profile.d.ts +14 -18
  47. package/lib/types/services/profile/progress.d.ts +7 -10
  48. package/lib/types/services/settings.d.ts +0 -4
  49. package/package.json +1 -1
  50. package/src/client/components/PluginHubSection.tsx +26 -22
  51. package/src/client/components/catalog/CatalogList.tsx +2 -4
  52. package/src/client/components/catalog/PluginCard.tsx +2 -3
  53. package/src/client/components/layout/CatalogControls.tsx +5 -6
  54. package/src/client/components/layout/CatalogHeader.tsx +1 -2
  55. package/src/client/components/layout/CategoryTabs.tsx +2 -3
  56. package/src/client/components/layout/SectionTabs.tsx +3 -5
  57. package/src/client/components/modals/ConfirmDialog.tsx +4 -6
  58. package/src/client/components/modals/InstalledDetailModal.tsx +3 -6
  59. package/src/client/components/modals/LogsModal.tsx +7 -12
  60. package/src/client/components/modals/NotificationsModal.tsx +74 -24
  61. package/src/client/components/modals/ProgressView.tsx +3 -4
  62. package/src/client/components/modals/modals.tsx +75 -26
  63. package/src/client/components/ui/Dropdown.tsx +4 -6
  64. package/src/client/components/ui/Toggle.tsx +2 -3
  65. package/src/client/components/ui/icons.tsx +1 -2
  66. package/src/client/components/views/CustomInstallView.tsx +20 -178
  67. package/src/client/components/views/DiagnosticsView.tsx +3 -6
  68. package/src/client/components/views/InstalledView.tsx +6 -11
  69. package/src/client/components/views/MarketView.tsx +2 -4
  70. package/src/client/components/views/SettingsView.tsx +9 -32
  71. package/src/client/css-modules.d.ts +1 -1
  72. package/src/client/data/catalog.ts +2 -3
  73. package/src/client/data/host.ts +26 -3
  74. package/src/client/data/hub.ts +2 -3
  75. package/src/client/hooks/useCatalog.ts +79 -24
  76. package/src/client/hooks/useIncrementalList.ts +3 -5
  77. package/src/client/hooks/useLanguage.ts +4 -6
  78. package/src/client/hooks/useSettings.ts +4 -11
  79. package/src/client/hooks/useTaskQueue.ts +36 -42
  80. package/src/client/index.tsx +2 -3
  81. package/src/client/locales.ts +187 -114
  82. package/src/client/logic/constants.ts +1 -2
  83. package/src/client/logic/ensure-plugin-css.ts +8 -12
  84. package/src/client/logic/failures.ts +20 -19
  85. package/src/client/logic/format.ts +1 -1
  86. package/src/client/logic/install-command.ts +14 -35
  87. package/src/client/logic/installed.ts +15 -10
  88. package/src/client/logic/normalize.ts +3 -3
  89. package/src/client/logic/release-age.ts +19 -0
  90. package/src/client/logic/urls.ts +24 -21
  91. package/src/client/styles/CustomInstallView.module.css +3 -30
  92. package/src/client/styles/DiagnosticsView.module.css +3 -5
  93. package/src/client/styles/Dropdown.module.css +2 -4
  94. package/src/client/styles/Header.module.css +6 -7
  95. package/src/client/styles/InstalledView.module.css +4 -7
  96. package/src/client/styles/List.module.css +4 -5
  97. package/src/client/styles/LogsView.module.css +2 -3
  98. package/src/client/styles/Modal.module.css +46 -6
  99. package/src/client/styles/SectionTabs.module.css +2 -4
  100. package/src/client/styles/SettingsView.module.css +3 -5
  101. package/src/client/styles/Toggle.module.css +2 -4
  102. package/src/client/styles/tokens.module.css +14 -18
  103. package/src/client/types.ts +11 -11
  104. package/src/server/http/catalog.ts +2 -3
  105. package/src/server/http/diagnostics.ts +6 -7
  106. package/src/server/http/install.ts +47 -208
  107. package/src/server/http/logs.ts +1 -2
  108. package/src/server/http/npm-release-age.ts +42 -0
  109. package/src/server/http/routes.ts +12 -12
  110. package/src/server/http/settings.ts +2 -2
  111. package/src/server/http/shared.ts +5 -6
  112. package/src/server/http/task.ts +1 -2
  113. package/src/server/index.ts +7 -8
  114. package/src/server/services/install/install-types.ts +12 -13
  115. package/src/server/services/install/install.ts +0 -1
  116. package/src/server/services/install/npm-check.ts +3 -2
  117. package/src/server/services/install/npm-resolve.ts +9 -99
  118. package/src/server/services/install/operation-log.ts +47 -1
  119. package/src/server/services/install/package-entry.ts +6 -11
  120. package/src/server/services/install/registry-check.ts +2 -2
  121. package/src/server/services/install/release-target.ts +8 -9
  122. package/src/server/services/install/task-queue.ts +51 -54
  123. package/src/server/services/npm-release-age.ts +107 -0
  124. package/src/server/services/probe.ts +4 -4
  125. package/src/server/services/profile/installed-versions.ts +16 -22
  126. package/src/server/services/profile/profile.ts +16 -42
  127. package/src/server/services/profile/progress.ts +8 -11
  128. package/src/server/services/settings.ts +2 -9
  129. package/lib/services/install/preflight.js +0 -178
  130. package/lib/types/services/install/preflight.d.ts +0 -23
  131. package/src/server/services/install/preflight.ts +0 -184
@@ -5,8 +5,9 @@
5
5
  *
6
6
  * 本机 npm 环境检测:判断一次安装失败是否源于「本机 npm 版本过低」。
7
7
  *
8
- * 背景:pnpm 在 git 源插件的 prepare 阶段会调 npm 装依赖,npm arborist 在解 peer 依赖时有
9
- * 已知内部崩溃 —— `Cannot read properties of null (reading 'edgesOut')`。这是 npm 自身缺陷,
8
+ * 背景:pnpm 在带 `prepare` 构建脚本的依赖上会调 npm 装依赖(npm 包同样可能带原生
9
+ * 依赖或 git 依赖),npm arborist 在解 peer 依赖时有已知内部崩溃 ——
10
+ * `Cannot read properties of null (reading 'edgesOut')`。这是 npm 自身缺陷,
10
11
  * 该报错会被 pnpm 包进 ERR_PNPM_PREPARE_PACKAGE 输出,不能按插件打包问题引导用户提 Issue。
11
12
  *
12
13
  * 这里的 `npmTooLowMarker` 是纯函数(输出文本 + 环境 → 标记行或 null),不触碰任务/队列,
@@ -3,57 +3,18 @@
3
3
  * Website: https://dsh-plugin.org
4
4
  * GitHub: https://github.com/dshplugin/dsh-plugin-hub
5
5
  *
6
- * npm 包反查:git 分发不完整(缺构建产物/子模块)导致安装失败时,用 npm
7
- * registry 的搜索接口按 repository 地址反查该仓库对应的官方 npm 包。
6
+ * npm 包校验:确认某个 npm 包确实属于该 GitHub 仓库、且声明为 DSH 插件
7
+ * (包元数据里的 repository 指向该仓库,并带 `dsh-plugin` 关键词或 `dsh` manifest)。
8
8
  *
9
9
  * 这是通用机制,不针对任何具体插件:只要作者发布了 repository 指向该
10
- * GitHub 仓库的 npm 包(scope 名与 GitHub 用户名是否一致无所谓),就能命中,
11
- * 从而把 git 分发不完整的插件切换到 npm 通道安装。命中结果带内存缓存,
12
- * 避免同一会话内重复查询 registry。
10
+ * GitHub 仓库的 npm 包(scope 名与 GitHub 用户名是否一致无所谓),就能命中。
13
11
  */
14
12
  import { get } from 'node:https';
15
13
  import { githubRepoOf } from '../profile/profile.js';
16
14
  import { finalUrl } from '../probe.js';
17
- /** 反查缓存:repo 小写 → npm 包名(null 表示已确认无对应 npm 包;网络异常不缓存)。 */
18
- const cache = new Map();
19
- /** 单次 registry 查询超时(ms):慢网络下失败返回 null,不阻塞安装流程。 */
15
+ /** 单次 registry 查询超时(ms):慢网络下失败返回 false,不阻塞安装流程。 */
20
16
  const REQUEST_TIMEOUT_MS = 8000;
21
- /** npm search 是相关性搜索而非 repository 精确索引;拉满单页结果后再本地做严格 repo 过滤。 */
22
- const SEARCH_RESULT_LIMIT = 250;
23
- /**
24
- * 反查 repo(`owner/repo`)对应的官方 npm 包名;未命中、网络异常或超时返回 null。
25
- * 返回 null 不代表仓库一定没有 npm 包,只代表本次未能确认 —— 调用方应保留
26
- * 原有错误路径,反查只是额外的一次尝试。只有「已确认」的结果(包名,或 200
27
- * 响应下确认无匹配)会进缓存;网络异常/超时/解析失败不缓存,同一会话内下次
28
- * 安装仍会重试反查,避免一次瞬时故障把整个会话锁死在 git 通道。
29
- * registry 参数:npm 镜像源地址,空串 = 官方源;与安装通道吃同一 registry,
30
- * 保证「配置了镜像」时反查和安装走同一个源(镜像节点同步完整时结果一致)。
31
- * proxy 参数:GitHub 改名跳转探测走的代理(与安装/诊断同一口径)。
32
- * 慢网络下失败不阻塞安装。
33
- */
34
- export async function resolveNpmPackage(repo, registry = '', proxy = '') {
35
- const key = repo.toLowerCase();
36
- if (cache.has(key))
37
- return cache.get(key) ?? null;
38
- let found = await searchRepo(repo, registry);
39
- // 仓库改名后 npm 包的 repository 已指向新名,按旧名反查不到:跟随一次 GitHub 的
40
- // 改名跳转拿到规范名再查一遍(旧地址本身仍可用,只是仓库名变了)。
41
- if (found === null) {
42
- const canonical = await canonicalRepo(repo, proxy);
43
- if (canonical !== '' && canonical.toLowerCase() !== key)
44
- found = await searchRepo(canonical, registry);
45
- }
46
- if (found !== undefined)
47
- cache.set(key, found);
48
- return found ?? null;
49
- }
50
- /**
51
- * Pick the installable npm package for one GitHub repository. npm search is a
52
- * relevance-ranked text search, not an exact repository index, so first filter
53
- * by repository URL. If a monorepo publishes both a CLI/helper package and a
54
- * DSH plugin, prefer the package that explicitly advertises the `dsh-plugin`
55
- * keyword instead of whichever result npm happened to rank first.
56
- */
17
+ /** 从包元数据取 repository 地址:字符串或 `{ url }` 对象,缺省回退 search 结果的 links.repository。 */
57
18
  function repositoryUrlOf(pkg) {
58
19
  if (typeof pkg.repository === 'string')
59
20
  return pkg.repository;
@@ -72,6 +33,10 @@ export function isDshPackageMetadataForRepo(pkg, repo) {
72
33
  const manifestMarked = pkg.dsh !== null && typeof pkg.dsh === 'object';
73
34
  return keywordMarked || manifestMarked;
74
35
  }
36
+ /**
37
+ * 校验包名对应的 npm 包确实属于该仓库且声明为 DSH 插件:取 registry 上的 `latest`
38
+ * 元数据比对 repository 与插件标记。网络异常、超时、非 200 一律返回 false,不阻塞调用方。
39
+ */
75
40
  export function isDshNpmPackageForRepo(packageName, repo, registry = '', proxy = '') {
76
41
  if (packageName === '' || repo === '')
77
42
  return Promise.resolve(false);
@@ -121,55 +86,3 @@ async function canonicalRepo(repo, proxy) {
121
86
  const canonical = final === null ? null : githubRepoOf(final);
122
87
  return canonical !== null && canonical.toLowerCase() !== key ? canonical : '';
123
88
  }
124
- function matchingPackagesForRepo(objects, repo) {
125
- const matches = [];
126
- for (const obj of objects) {
127
- const pkg = obj.package;
128
- if (typeof pkg?.name !== 'string' || pkg.name === '')
129
- continue;
130
- const repoUrl = repositoryUrlOf(pkg);
131
- if (githubRepoOf(repoUrl)?.toLowerCase() !== repo.toLowerCase())
132
- continue;
133
- const keywords = Array.isArray(pkg.keywords) ? pkg.keywords : [];
134
- matches.push({
135
- name: pkg.name,
136
- isDshPlugin: keywords.some((keyword) => typeof keyword === 'string' && keyword.toLowerCase() === 'dsh-plugin'),
137
- });
138
- }
139
- return matches;
140
- }
141
- export function selectNpmPackageForRepo(objects, repo) {
142
- const matches = matchingPackagesForRepo(objects, repo);
143
- return matches.find((candidate) => candidate.isDshPlugin)?.name ?? matches[0]?.name ?? null;
144
- }
145
- /** 用 npm search 接口按 repository 地址反查,并做铁证校验(包元数据必须指向该仓库)。
146
- * 返回:包名 = 命中;null = 200 响应下确认无匹配;undefined = 本次未能确认(网络/超时/解析失败)。 */
147
- function searchRepo(repo, registry) {
148
- const [owner, name] = repo.split('/');
149
- if (owner === undefined || name === undefined || name === '')
150
- return Promise.resolve(null);
151
- const base = registry === '' ? 'https://registry.npmjs.org' : registry.replace(/\/+$/, '');
152
- const url = `${base}/-/v1/search?text=${encodeURIComponent(`repository:${owner}/${name}`)}&size=${SEARCH_RESULT_LIMIT}`;
153
- return new Promise((resolve) => {
154
- const req = get(url, { timeout: REQUEST_TIMEOUT_MS }, (res) => {
155
- if (res.statusCode !== 200) {
156
- res.resume();
157
- resolve(undefined);
158
- return;
159
- }
160
- let body = '';
161
- res.on('data', (chunk) => { body += chunk.toString(); });
162
- res.on('end', () => {
163
- try {
164
- const data = JSON.parse(body);
165
- resolve(selectNpmPackageForRepo(data.objects ?? [], `${owner}/${name}`));
166
- }
167
- catch {
168
- resolve(undefined);
169
- }
170
- });
171
- });
172
- req.on('timeout', () => req.destroy());
173
- req.on('error', () => resolve(undefined));
174
- });
175
- }
@@ -10,7 +10,8 @@
10
10
  * 防止插件把任意路径打印进日志造成越权读取;任何异常都静默降级(返回 null),
11
11
  * 不改变原有失败处理。
12
12
  */
13
- import { readFileSync } from 'node:fs';
13
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
14
+ import { join } from 'node:path';
14
15
  import { CAPTURE_LIMIT_BYTES } from './install-types.js';
15
16
  /**
16
17
  * 从 DSH 输出里解析 operation 日志路径(`diagnostics: <path>`)。
@@ -47,3 +48,54 @@ export function backfillOperationLog(output) {
47
48
  return null;
48
49
  }
49
50
  }
51
+ /**
52
+ * 运行期抓取:宿主的 operation 日志只在命令运行期间存在,结束后可能被清理,
53
+ * 退出后再按路径读往往已经拿不到。这里在安装过程中轮询 profile 下最新的
54
+ * `.plugin-manager/logs/<operation>/pnpm.log`,用抓到的内容兜底。
55
+ * 只认本次运行产生的新文件(mtime 晚于启动基线),避免复述上一次安装的日志。
56
+ */
57
+ export function createOperationLogTap(profileDir) {
58
+ const logsDir = join(profileDir, '.plugin-manager', 'logs');
59
+ const newestLog = () => {
60
+ let newest = null;
61
+ for (const entry of readdirSync(logsDir, { withFileTypes: true })) {
62
+ if (!entry.isDirectory())
63
+ continue;
64
+ const file = join(logsDir, entry.name, 'pnpm.log');
65
+ try {
66
+ const mtimeMs = statSync(file).mtimeMs;
67
+ if (newest === null || mtimeMs > newest.mtimeMs)
68
+ newest = { file, mtimeMs };
69
+ }
70
+ catch { /* 该 operation 还没有 pnpm.log */ }
71
+ }
72
+ return newest;
73
+ };
74
+ let baselineMs = 0;
75
+ try {
76
+ baselineMs = newestLog()?.mtimeMs ?? 0;
77
+ }
78
+ catch { /* logs 目录还不存在 */ }
79
+ let captured = '';
80
+ const tick = () => {
81
+ try {
82
+ const newest = newestLog();
83
+ if (newest === null || newest.mtimeMs <= baselineMs)
84
+ return;
85
+ const text = readFileSync(newest.file, 'utf8');
86
+ if (text.length > captured.length)
87
+ captured = text;
88
+ }
89
+ catch { /* 读不到就放弃这一轮 */ }
90
+ };
91
+ const timer = setInterval(tick, 700);
92
+ timer.unref();
93
+ tick();
94
+ return {
95
+ stop: () => {
96
+ clearInterval(timer);
97
+ tick();
98
+ return captured.length > CAPTURE_LIMIT_BYTES ? captured.slice(-CAPTURE_LIMIT_BYTES) : captured;
99
+ },
100
+ };
101
+ }
@@ -4,17 +4,12 @@
4
4
  * GitHub: https://github.com/dshplugin/dsh-plugin-hub
5
5
  *
6
6
  * 分发文件解析:从 package.json 推出装完后必须真实存在的文件 —— 作者声明的入口
7
- * (exports["."] / main)与 bundle 声明的补丁(dsh.bundle.patch)。git 通道(tar 预检)
8
- * 与 npm 通道(装后 statSync 校验)共用,保证两条通道对同一个包判定一致。
7
+ * (exports["."] / main)与 bundle 声明的补丁(dsh.bundle.patch),供装后校验使用。
9
8
  *
10
- * 这里不替作者补一个 index.js:宿主加载一个 bundle 读的是它的 package.json 和它声明的
11
- * 补丁文件(官方 bundleManifest 的注释即「Read bundle metadata without loading its
12
- * JavaScript」),从不 import 包本身。凭空要求一个作者没声明的入口,只会把完整的
13
- * 技能包判成分发残缺,并把一条假缺陷推到作者仓库(见 QingYunA/answer-me-with-html#209)。
14
- *
15
- * 例外是补丁自己 mount 了本包:dsh 的《打包与安装插件》里组合包的常规写法就是
16
- * `- insert: - name: <本包名>`,宿主随后按包名 import 本包,入口那时必须存在。
17
- * 所以只有补丁真的写了自己的包名,才把这个入口算进分发要求。
9
+ * 只在包自己声明了入口时才要求它存在:宿主加载 bundle 读的是它的 package.json 与声明的补丁,
10
+ * 从不 import 包本身。硬要一个作者没声明过的 index.js,会把完整的包判成分发残缺、把一条假缺陷
11
+ * 推到作者仓库。例外是补丁自己 mount 了本包(组合包的常规写法)—— 那时宿主按包名 import 本包,
12
+ * 入口必须存在,所以只有补丁真的写了自己的包名才把这个入口算进分发要求。
18
13
  */
19
14
  /** exports 条件对象里按优先级尝试的键;Node 语义下 default 最宽,import/require 次之。 */
20
15
  const EXPORT_CONDITION_KEYS = ['default', 'import', 'require'];
@@ -42,7 +37,7 @@ export function resolvePackageEntry(meta) {
42
37
  /**
43
38
  * 解析 `dsh.bundle.patch` 声明的补丁文件(相对包根,不带 `./` 前缀)。
44
39
  * 形状不合规范(既不是字符串也不是字符串数组)在这里不判定:那是 dsh 启动时
45
- * bundlePatchFiles 的报错职责,预检只负责「声明了就要在包里存在」。
40
+ * bundlePatchFiles 的报错职责,装后校验只负责「声明了就要在包里存在」。
46
41
  */
47
42
  export function resolveBundlePatchFiles(meta) {
48
43
  const patch = meta.dsh?.bundle?.patch;
@@ -63,8 +63,8 @@ export async function registryMissingMarker(output, opts) {
63
63
  const name = missingPackageOf(output);
64
64
  if (name === null)
65
65
  return null;
66
- // ① profile 自己声明的残留依赖(#73):用户环境问题,交给既有的 pnpmMissingDep 提示(该提示就是
67
- // 教用户删 profile 里那条依赖),这里不再产出标记、不改归属
66
+ // 该包是 profile 自己声明的依赖(用户环境里留下的条目)→ 用户环境问题,交给既有的 pnpmMissingDep
67
+ // 提示处理(那条提示就是教用户删掉它),不产出标记、不改归属
68
68
  if (profileDependencyNames(opts.profileDir).some((dep) => dep.toLowerCase() === name.toLowerCase()))
69
69
  return null;
70
70
  const exists = await existsOnOfficialRegistry(name, opts.fetchImpl ?? fetch, opts.timeoutMs ?? 8000);
@@ -3,23 +3,22 @@
3
3
  * Website: https://dsh-plugin.org
4
4
  * GitHub: https://github.com/dshplugin/dsh-plugin-hub
5
5
  *
6
- * 预构建 GitHub release 安装目标(目录权威命令 → 可安装直链)。
7
- * 部分插件(如 loopx)把构建产物发布成 GitHub release 的 .tgz,仓库 HEAD 反而是
8
- * monorepo 根、走 git 直装会因缺入口文件失败;目录下发的权威安装命令直接指向该
9
- * release 包。这里把「目录命令」解析成安全的 release 目标,供客户端选路与服务端
10
- * 校验共用(单一事实来源,避免两端口径漂移)。
6
+ * 预构建 release 直链的仓库身份解析。部分插件(如 loopx)当初以 GitHub release 的 .tgz
7
+ * 安装过,仓库 HEAD 反而是 monorepo 根、走 git 直装会因缺入口文件失败;老安装记录里留的
8
+ * 就是这种 release 直链。这里把「历史安装目标」还原成所属仓库身份,供已装态读回、队列
9
+ * 去重与展示复用(单一事实来源,避免两端口径漂移)。
11
10
  *
12
11
  * 只接受固定形态的 HTTPS `github.com/<owner>/<repo>/releases/download/<tag>/<asset>.tgz`:
13
- * 目录命令是展示数据、绝非 shell 代码,绝不执行命令文本;跨仓跳转、外部主机、凭据、
12
+ * 输入是记录/展示数据、绝非 shell 代码,绝不执行其文本;跨仓跳转、外部主机、凭据、
14
13
  * 移动的 latest 链接、query/fragment、多余 CLI 参数与 shell 片段一律拒绝。
15
14
  */
16
- /** 目录权威命令:`dsh plugin --profile <p> add|update <target>`(与 profile.ts installTargetOf 同口径)。 */
15
+ /** 完整命令前缀:`dsh plugin --profile <p> add|update <target>`(与 profile.ts installTargetOf 同口径)。 */
17
16
  const DSH_PLUGIN_CMD_RE = /^dsh[ \t]+plugin[ \t]+--profile(?:[ \t]+|=)[A-Za-z0-9_-]+[ \t]+(?:add|update)[ \t]+(.+)$/i;
18
17
  /** 固定形态的 release .tgz 直链:主机、路径段与扩展名全部锁死。 */
19
18
  const RELEASE_URL_RE = /^https:\/\/github\.com\/([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)\/releases\/download\/([A-Za-z0-9._+-]+)\/([A-Za-z0-9._+-]+\.tgz)$/;
20
19
  /**
21
- * 解析一个 release 安装目标。
22
- * @param value - 目录命令(`dsh plugin --profile web add <url>`)或裸直链。
20
+ * 解析一个历史安装目标里的 release 直链。
21
+ * @param value - 完整命令(`dsh plugin --profile web add <url>`)或裸直链。
23
22
  * @returns 命中返回 `{ target, repo }`,否则 null。
24
23
  */
25
24
  export function githubReleaseTarget(value) {
@@ -14,31 +14,31 @@ import { dirname, join, resolve } from 'node:path';
14
14
  import { CAPTURE_LIMIT_BYTES, MAX_TASKS, MAX_TASK_LINES } from './install-types.js';
15
15
  import { npmTooLowMarker } from './npm-check.js';
16
16
  import { registryMissingMarker } from './registry-check.js';
17
- import { backfillOperationLog } from './operation-log.js';
17
+ import { backfillOperationLog, createOperationLogTap, operationLogPathOf } from './operation-log.js';
18
18
  import { cleanLine, estimateProgress } from '../profile/progress.js';
19
19
  import { hasClientUi, isDshPlugin, mountLoadedEntry, removeLoadedEntry } from '../loader.js';
20
20
  import { addPendingRestart, clearPendingRestart } from '../profile/pending-restart.js';
21
21
  import { addAllowBuildsKey, githubRepoOf, parseAllowBuildsKey, profileDirectory } from '../profile/profile.js';
22
22
  import { appendLog } from '../log.js';
23
- /** In-memory task registry, keyed by task id. */
23
+ /** 内存任务注册表,按任务 id 索引。 */
24
24
  const tasks = new Map();
25
25
  let nextTaskId = 1;
26
- /** Pending tasks awaiting their turn (FIFO). The queue worker runs at most one mutation at a time. */
26
+ /** 等待轮到的排队任务(FIFO)。队列 worker 同一时刻最多跑一个变更。 */
27
27
  const queue = [];
28
- /** Child processes of currently running tasks (for cancel). */
28
+ /** 当前运行任务的子进程(用于取消)。 */
29
29
  const runningChildren = new Map();
30
- /** Snapshot of a task (keeps the live object untouched by consumers). */
30
+ /** 任务快照(避免消费方改动实时对象)。 */
31
31
  export function getTask(id) {
32
32
  const task = tasks.get(id);
33
33
  if (!task)
34
34
  return undefined;
35
35
  return { ...task, lines: task.lines.slice(0, MAX_TASK_LINES) };
36
36
  }
37
- /** All non-terminal tasks in queue order (running first, then pending). Lets the client resume a queue after a page reload. */
37
+ /** 全部未终态任务,按队列顺序(running 在前、pending 在后)。供客户端刷新页面后恢复队列。 */
38
38
  export function activeTask() {
39
39
  const found = [];
40
- // 展示目标用 displayTarget(owner/repo):安装 target 可能被服务端切成 npm 包名
41
- // (npm 反查命中),队列恢复/待重启展示对用户保持仓库名无感知
40
+ // 展示目标用 displayTarget(owner/repo):安装 target 是 npm 包名,
41
+ // 队列恢复/待重启展示对用户保持仓库名无感知
42
42
  const show = (task) => task.displayTarget ?? task.target;
43
43
  for (const item of queue) {
44
44
  const task = item.task;
@@ -72,24 +72,22 @@ export function activeTask() {
72
72
  return found;
73
73
  }
74
74
  /**
75
- * True while a mutation child process is still alive. The concurrent slot is
76
- * keyed off the live child set rather than task.status: cancelling a running
77
- * task flips its status immediately, but the child may still be shutting down
78
- * (the close event lands later) — the slot must stay held until then, otherwise
79
- * a new task would start while the old pnpm still runs in the same profile dir.
75
+ * 变更子进程仍存活时为 true。并发占位以存活子进程集合为准,而非 task.status:
76
+ * 取消运行中任务会立即翻转其状态,但子进程可能仍在退出中(close 事件稍后才到)——
77
+ * 占位必须维持到那时,否则旧 pnpm 还在同一 profile 目录跑,新任务就开始了。
80
78
  */
81
79
  export function hasRunningTask() {
82
80
  return runningChildren.size > 0;
83
81
  }
84
- /** Whether the target already has a non-terminal task in the queue (install/uninstall dedupe). */
82
+ /** 目标在队列里是否已有未终态任务(安装/卸载去重)。 */
85
83
  export function hasQueuedTarget(target) {
86
84
  return queue.some((it) => it.task.target === target && (it.task.status === 'pending' || it.task.status === 'running'));
87
85
  }
88
86
  /**
89
- * Cancel a queued or running task.
90
- * - pending: removed from the queue immediately (never spawned).
91
- * - running: kills the child process; the queue worker then picks the next one.
92
- * Returns false when the task is unknown or already finished.
87
+ * 取消排队中或运行中的任务。
88
+ * - pending:立即移出队列(从未 spawn)。
89
+ * - running:杀掉子进程;队列 worker 随后取下一个。
90
+ * 任务不存在或已结束时返回 false。
93
91
  */
94
92
  export function cancelTask(id) {
95
93
  const task = tasks.get(id);
@@ -241,18 +239,13 @@ function mutationVerb(action) {
241
239
  /** 系统日志入口渠道后缀:自定义安装(带渠道)在日志里体现「从哪张卡片发起」,
242
240
  * 目录插件安装(无渠道)返回空串。日志中文语境,渠道名用中文口语。 */
243
241
  function channelLabel(channel) {
244
- if (channel === 'git')
245
- return '(GitHub 源码入口)';
246
- if (channel === 'dsh')
247
- return '(DSH 命令入口)';
248
242
  if (channel === 'npm')
249
243
  return '(NPM 包入口)';
250
244
  return '';
251
245
  }
252
246
  /**
253
- * Enqueue a plugin mutation and return its task. Tasks run strictly serially:
254
- * the queue worker starts the next one only after the previous finishes.
255
- * Progress is visible through `getTask(id)` / `activeTask()` until done.
247
+ * 插件变更入队并返回其任务。任务严格串行:队列 worker 只在上一个结束后才启动下一个。
248
+ * 完成前可通过 `getTask(id)` / `activeTask()` 查看进度。
256
249
  */
257
250
  export function startPluginMutation(options) {
258
251
  // 卸载入队时先快照「该包是否带客户端 UI」:卸载完成后包已从磁盘删除,读不到 package.json,
@@ -302,7 +295,7 @@ export function startPluginMutation(options) {
302
295
  pumpQueue();
303
296
  return task;
304
297
  }
305
- /** Queue worker: at most one mutation runs at a time; pick the next pending task when the slot frees up. */
298
+ /** 队列 worker:同一时刻最多跑一个变更;占位空出时取下一个 pending 任务。 */
306
299
  function pumpQueue() {
307
300
  if (hasRunningTask())
308
301
  return;
@@ -364,9 +357,8 @@ function pumpQueue() {
364
357
  });
365
358
  }
366
359
  /**
367
- * Run one `dsh plugin --profile <profile> <action> <target>` spawn, stream
368
- * its output onto the tracked task and resolve with the captured result.
369
- * Never rejects; failures surface through the result / task state.
360
+ * 执行一次 `dsh plugin --profile <profile> <action> <target>` spawn,把输出流式写到
361
+ * 跟踪的任务上,并以捕获结果 resolve。绝不 reject;失败通过结果/任务状态体现。
370
362
  */
371
363
  function spawnMutation(options) {
372
364
  const { action, profile, target, timeoutMs = 5 * 60 * 1000, env, task, displayTarget, loader, globalNpm, updateNpm } = options;
@@ -388,8 +380,7 @@ function spawnMutation(options) {
388
380
  const args = isGlobalNpm
389
381
  ? ['install', '-g', ...(globalNpm ?? [])]
390
382
  : [...invocation.prefixArgs, 'plugin', '--profile', profile, cliAction, npmUpdateTarget];
391
- // 记录实际执行的命令(npm 通道显示包名,git 通道显示 HTTPS 源),
392
- // 失败提 Issue 时作为「已尝试的安装方式」随附
383
+ // 记录实际执行的命令(显示包名),失败提 Issue 时作为「已尝试的安装方式」随附
393
384
  const executed = isGlobalNpm
394
385
  ? `npm install -g ${(globalNpm ?? []).join(' ')}`
395
386
  : `dsh plugin --profile ${profile} ${cliAction} ${npmUpdateTarget}`;
@@ -623,7 +614,7 @@ function spawnMutation(options) {
623
614
  }
624
615
  /**
625
616
  * 安装后校验已装包里 package.json 声明的文件(main / exports["."].default 与
626
- * dsh.bundle.patch)是否真实存在。git: 分发常不提交构建产物(lib/ 等),pnpm 装完没有
617
+ * dsh.bundle.patch)是否真实存在。npm 包也可能漏发构建产物(lib/ 等),pnpm 装完没有
627
618
  * 报错,但宿主重启加载插件树时会 ERR_MODULE_NOT_FOUND 直接崩溃、网页打不开 —— 这里在
628
619
  * 登记「待重启」前就把这类残缺包拦下。没有声明过的文件不在这里追究:没声明入口的
629
620
  * bundle 包(只挂技能)本来就不需要入口,宿主读的是它的 package.json 与声明的补丁。
@@ -724,15 +715,15 @@ export function hostSpawnMarker(invocation, error) {
724
715
  return `[host-spawn] the DSH host could not be launched (${invocation.file}: ENOENT)`;
725
716
  }
726
717
  /**
727
- * Run a plugin mutation with one recovery path: when `add` fails because
728
- * pnpm's allowBuilds gate blocks a build script — either the git-hosted
729
- * package's own `prepare` (`ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`, key from
730
- * the printed key@url hint) or a dependency's native build
731
- * (`ERR_PNPM_IGNORED_BUILDS`, key = the listed name@version) — write the
732
- * exact keys into the profile's pnpm-workspace.yaml and retry once.
733
- * Other failures fall through to the single-spawn result.
718
+ * 执行插件变更,带一条恢复路径:当 `add` 因 pnpm 的 allowBuilds 门禁拦下构建脚本而失败 ——
719
+ * 或是 git 源包自己的 `prepare`(`ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`,key 取自打印的
720
+ * key@url 提示),或是某依赖的原生构建(`ERR_PNPM_IGNORED_BUILDS`,key = 列出的 name@version)——
721
+ * 就把确切的 key 写进 profile 的 pnpm-workspace.yaml 并重试一次。
722
+ * 其它失败一律落到单次 spawn 的结果。
734
723
  */
735
724
  export async function runPluginMutation(options) {
725
+ // operation 日志只在运行期存在(宿主结束后可能清掉),先开抓取,退出后按路径读作兜底
726
+ const logTap = createOperationLogTap(profileDirectory(options.profile));
736
727
  let result = await spawnMutation(options);
737
728
  // allowBuilds 放行 / 装后入口校验都是 profile 专属(pnpm 装进 profile 的场景);
738
729
  // 全局 npm 安装直接走 npm,无 pnpm allowBuilds 拦截、也不进 profile,跳过这两类恢复
@@ -744,8 +735,7 @@ export async function runPluginMutation(options) {
744
735
  const key = parseAllowBuildsKey(output);
745
736
  if (key !== null) {
746
737
  if (options.task) {
747
- // First attempt already marked the task failed; reset it so the
748
- // retry streams progress as a running task again.
738
+ // 首次尝试已把任务标为失败;重置它,让重试重新以 running 任务形式流式输出进度。
749
739
  options.task.status = 'running';
750
740
  options.task.exitCode = null;
751
741
  pushLine(options.task, `[allow build] ${key}`);
@@ -774,14 +764,16 @@ export async function runPluginMutation(options) {
774
764
  }
775
765
  }
776
766
  }
777
- // pnpm 安装本身成功,但目标包声明分发的文件缺失(git 分发缺构建产物 / 缺声明的补丁)→ 判为失败:
767
+ // 重试会产生新的 operation 日志,运行期抓取到此为止
768
+ const tappedLog = logTap.stop();
769
+ // pnpm 安装本身成功,但目标包声明分发的文件缺失(分发物缺构建产物 / 缺声明的补丁)→ 判为失败:
778
770
  // 撤销刚登记的待重启,避免用户重启时宿主加载残缺包直接崩溃。
779
771
  // 全局 npm 安装不进 profile(profile deps 里没有这些包),跳过入口校验
780
772
  if (options.action !== 'remove' && result.exitCode === 0 && !result.timedOut && (options.globalNpm ?? []).length === 0) {
781
773
  const verified = verifyInstalledEntry(options.profile, options.target);
782
774
  if (verified.name !== null && verified.missing !== null) {
783
775
  clearPendingRestart(options.displayTarget ?? options.target);
784
- const detail = `[packaging] ${verified.name}: declared file missing: ${verified.missing} (git distribution lacks build output — install the npm version or report to the author)`;
776
+ const detail = `[packaging] ${verified.name}: declared file missing: ${verified.missing} (the published package is missing this file — report it to the author)`;
785
777
  if (options.task && options.task.status !== 'cancelled') {
786
778
  options.task.status = 'failed';
787
779
  options.task.exitCode = null;
@@ -791,12 +783,12 @@ export async function runPluginMutation(options) {
791
783
  return { exitCode: 1, timedOut: false, error: `declared file missing: ${verified.missing}`, stdout: result.stdout, stderr: `${result.stderr}\n${detail}` };
792
784
  }
793
785
  }
794
- // DSH 只把一行摘要(`dsh: plugin command failed; diagnostics: <path>`)回显到控制台时,
795
- // 控制台里没有任何错误特征,前端只能把失败归为「未知」(issue #192)。这里按该路径回捞
796
- // operation 日志尾部补进失败信息:用户直接看到真实报错,自动归类也有据可依。
797
- // 只在本就不含任何错误码时回捞 —— pnpm 已把报错回显出来时无需多读一次文件。
786
+ // 宿主只把一行摘要(`dsh: plugin command failed; diagnostics: <path>`)回显到控制台、真正的报错
787
+ // 写进该日志文件时,前端拿不到任何错误特征、只能归为「未知」。按该路径回捞日志尾部补进失败信息。
788
+ // 只在输出本就不含错误码时回捞 —— pnpm 已回显报错时无需多读一次文件。
798
789
  if (result.exitCode !== 0 && !result.timedOut && !/\bERR_[A-Z0-9_]+\b/.test(`${result.stderr}\n${result.stdout}`)) {
799
- const backfilled = backfillOperationLog(`${result.stderr}\n${result.stdout}`);
790
+ const output = `${result.stderr}\n${result.stdout}`;
791
+ const backfilled = tappedLog !== '' ? tappedLog : backfillOperationLog(output);
800
792
  if (backfilled !== null) {
801
793
  if (options.task && options.task.status !== 'cancelled') {
802
794
  pushLine(options.task, '[pnpm log] DSH did not echo pnpm output — recovered the operation log from disk');
@@ -806,6 +798,10 @@ export async function runPluginMutation(options) {
806
798
  }
807
799
  result = { ...result, stderr: `${result.stderr}\n${backfilled}` };
808
800
  }
801
+ else if (options.task && options.task.status !== 'cancelled' && operationLogPathOf(output) !== null) {
802
+ // 诊断路径在、日志却取不到:留一行证据,否则下一次同类上报又只剩宿主那句摘要、看不出根因
803
+ pushLine(options.task, '[pnpm log] the host-reported diagnostics log could not be read from disk (missing, empty, or unreadable)');
804
+ }
809
805
  }
810
806
  // 包在 registry 不存在(404)→ 官方源复查,区分「作者的依赖缺失/包被删」与「本机镜像源滞后」
811
807
  result = await annotateRegistryMissing(result, options);
@@ -0,0 +1,119 @@
1
+ /**
2
+ * DSH Plugin Hub — the community plugin marketplace for DeepSeek Harness.
3
+ * Website: https://dsh-plugin.org
4
+ * GitHub: https://github.com/dshplugin/dsh-plugin-hub
5
+ *
6
+ * npm 包最新版本的发布时间查询:为「已安装插件是否有更新」提供供应链门禁依据。
7
+ * pnpm 对发布不满 24h(dsh profile minimumReleaseAge=1440)的版本会静默回退到旧版本,
8
+ * 因此发布未满门槛的版本不该提示更新(否则用户点了也装不上)。
9
+ * 结果按包名内存缓存,同一次会话内不重复请求;失败/超时/响应过大一律返回 null,绝不抛错、绝不阻塞。
10
+ */
11
+ import { get as httpsGet } from 'node:https';
12
+ import { validPackageName } from './profile/profile.js';
13
+ import { fetchViaCurl } from './probe.js';
14
+ /** 请求体包名数量上限:只为已安装插件按需查询,几十个足矣,封顶防滥用。 */
15
+ export const MAX_RELEASE_AGE_PACKAGES = 50;
16
+ /** 单包查询超时(ms):慢网络下失败即返回 null,不拖住整个响应。 */
17
+ export const RELEASE_AGE_TIMEOUT_MS = 8000;
18
+ /** 响应体上限:完整 packument 可能达数 MB,超限直接放弃,避免异常大包拖垮服务。 */
19
+ const MAX_PACKUMENT_BYTES = 10 * 1024 * 1024;
20
+ export const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
21
+ /** 会话内缓存(包名 → 版本与发布时间):只存成功结果,一次网络抖动不会把判断永久粘住。 */
22
+ const releaseCache = new Map();
23
+ /** 从完整 packument 取 dist-tags.latest 对应版本及其发布时间;缺任一字段返回 null。 */
24
+ export function latestReleaseOf(packument) {
25
+ if (packument === null || typeof packument !== 'object')
26
+ return null;
27
+ const doc = packument;
28
+ const tags = doc['dist-tags'];
29
+ const version = tags !== null && typeof tags === 'object' ? tags.latest : undefined;
30
+ if (typeof version !== 'string' || version === '')
31
+ return null;
32
+ const time = doc.time;
33
+ const publishedAt = time !== null && typeof time === 'object' ? time[version] : undefined;
34
+ if (typeof publishedAt !== 'string' || publishedAt === '')
35
+ return null;
36
+ return { version, publishedAt };
37
+ }
38
+ /** 请求体 → 去重后的合法包名列表;非数组 / 超量 / 含非法包名一律 null(拒绝非法输入)。 */
39
+ export function parseReleaseAgeRequest(body) {
40
+ if (body === null || typeof body !== 'object')
41
+ return null;
42
+ const raw = body.packages;
43
+ if (!Array.isArray(raw) || raw.length > MAX_RELEASE_AGE_PACKAGES)
44
+ return null;
45
+ const names = new Set();
46
+ for (const item of raw) {
47
+ if (typeof item !== 'string' || item === '' || item.startsWith('-') || !validPackageName(item))
48
+ return null;
49
+ names.add(item);
50
+ }
51
+ return [...names];
52
+ }
53
+ /** node:https 直连 GET,仅接受 200;超时/超限/网络失败返回 null。 */
54
+ function getJson(url, timeoutMs) {
55
+ return new Promise((resolve) => {
56
+ let done = false;
57
+ const finish = (value) => { if (!done) {
58
+ done = true;
59
+ resolve(value);
60
+ } };
61
+ const req = httpsGet(url, { timeout: timeoutMs, headers: { accept: 'application/json' } }, (res) => {
62
+ if (res.statusCode !== 200) {
63
+ res.resume();
64
+ finish(null);
65
+ return;
66
+ }
67
+ const declared = Number(res.headers['content-length']);
68
+ if (Number.isFinite(declared) && declared > MAX_PACKUMENT_BYTES) {
69
+ res.destroy();
70
+ finish(null);
71
+ return;
72
+ }
73
+ let body = '';
74
+ let bytes = 0;
75
+ res.on('data', (chunk) => {
76
+ bytes += chunk.length;
77
+ if (bytes > MAX_PACKUMENT_BYTES) {
78
+ res.destroy();
79
+ finish(null);
80
+ return;
81
+ }
82
+ body += chunk.toString();
83
+ });
84
+ res.on('end', () => finish(body));
85
+ res.on('error', () => finish(null));
86
+ });
87
+ req.on('timeout', () => req.destroy());
88
+ req.on('error', () => finish(null));
89
+ });
90
+ }
91
+ /** 拉取一个包的完整 packument 正文;配了代理时复用与安装/目录同一套代理口径(curl 子进程注入 proxy env)。 */
92
+ async function fetchPackument(url, proxy, timeoutMs) {
93
+ if (proxy !== '') {
94
+ const r = await fetchViaCurl(url, proxy, timeoutMs);
95
+ return r.ok && r.body !== '' && Buffer.byteLength(r.body) <= MAX_PACKUMENT_BYTES ? r.body : null;
96
+ }
97
+ return getJson(url, timeoutMs);
98
+ }
99
+ /** 查询一个包的最新版本与发布时间(成功结果缓存,同会话内同包不重复请求);registry 为空回退官方源,失败返回 null。 */
100
+ export async function lookupReleaseAge(packageName, registry, proxy, timeoutMs = RELEASE_AGE_TIMEOUT_MS) {
101
+ const cached = releaseCache.get(packageName);
102
+ if (cached !== undefined)
103
+ return cached;
104
+ const base = registry.replace(/\/+$/, '') || DEFAULT_NPM_REGISTRY;
105
+ const body = await fetchPackument(`${base}/${encodeURIComponent(packageName)}`, proxy, timeoutMs);
106
+ if (body === null)
107
+ return null;
108
+ let parsed;
109
+ try {
110
+ parsed = JSON.parse(body);
111
+ }
112
+ catch {
113
+ return null;
114
+ }
115
+ const release = latestReleaseOf(parsed);
116
+ if (release !== null)
117
+ releaseCache.set(packageName, release);
118
+ return release;
119
+ }