@li-canghai/dsh-paper 0.0.0-stage → 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.
Files changed (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -2
  3. package/cordis.patch.yml +4 -0
  4. package/lib/annotate-tool.js +334 -0
  5. package/lib/arxiv-id.js +74 -0
  6. package/lib/asset-routes.js +210 -0
  7. package/lib/bibliography-formats.js +126 -0
  8. package/lib/bibliography-import.js +105 -0
  9. package/lib/bibliography-service.js +43 -0
  10. package/lib/bibliography.js +42 -0
  11. package/lib/block-authors.js +292 -0
  12. package/lib/block-cache.js +39 -0
  13. package/lib/blocks-markdown.js +157 -0
  14. package/lib/blocks-reconcile.js +218 -0
  15. package/lib/blocks.js +1344 -0
  16. package/lib/citation-metadata.js +260 -0
  17. package/lib/citation-styles.js +120 -0
  18. package/lib/client-parts/01-pure-helpers.js +2607 -0
  19. package/lib/client.js +9569 -0
  20. package/lib/code-source.js +68 -0
  21. package/lib/concurrency-gate.js +91 -0
  22. package/lib/context.js +233 -0
  23. package/lib/csl/SOURCES.md +10 -0
  24. package/lib/csl/gb-t-7714.csl +441 -0
  25. package/lib/csl/ieee.csl +520 -0
  26. package/lib/csl/locales-zh-CN.xml +438 -0
  27. package/lib/csl/nature.csl +190 -0
  28. package/lib/discussion.js +400 -0
  29. package/lib/documents.js +67 -0
  30. package/lib/export.js +848 -0
  31. package/lib/file-lock.js +177 -0
  32. package/lib/gloss.js +181 -0
  33. package/lib/glossary.js +279 -0
  34. package/lib/index.js +3862 -0
  35. package/lib/inline-html.js +53 -0
  36. package/lib/install-dependency.js +120 -0
  37. package/lib/item-ops.js +83 -0
  38. package/lib/job-facade.js +58 -0
  39. package/lib/json-store.js +54 -0
  40. package/lib/library-model.js +132 -0
  41. package/lib/library-service.js +180 -0
  42. package/lib/library-tool.js +982 -0
  43. package/lib/library.js +814 -0
  44. package/lib/markdown-assets.js +138 -0
  45. package/lib/markdown-literals.js +93 -0
  46. package/lib/metadata-enrichment.js +516 -0
  47. package/lib/metadata-fetch.js +146 -0
  48. package/lib/metadata-node.js +158 -0
  49. package/lib/metadata-proxy.ps1 +35 -0
  50. package/lib/mineru-config.js +95 -0
  51. package/lib/mineru-sdk-helper.py +123 -0
  52. package/lib/mineru-sdk.js +182 -0
  53. package/lib/mineru.js +268 -0
  54. package/lib/mirror-export.js +240 -0
  55. package/lib/outline.js +296 -0
  56. package/lib/page-image-helper.py +294 -0
  57. package/lib/page-image.js +454 -0
  58. package/lib/paper-metadata.js +242 -0
  59. package/lib/parse-export.js +631 -0
  60. package/lib/pdf-analysis-tool.js +750 -0
  61. package/lib/pdf-metadata-helper.py +75 -0
  62. package/lib/pdf-metadata.js +141 -0
  63. package/lib/pdf-page.js +183 -0
  64. package/lib/pdf-scan.js +134 -0
  65. package/lib/pdf-text.js +68 -0
  66. package/lib/picker.js +305 -0
  67. package/lib/portable.js +379 -0
  68. package/lib/purge.js +170 -0
  69. package/lib/read-tool.js +660 -0
  70. package/lib/reader-store.js +497 -0
  71. package/lib/reading-order.js +207 -0
  72. package/lib/rename-document.js +480 -0
  73. package/lib/rename.js +372 -0
  74. package/lib/renderer-status.js +161 -0
  75. package/lib/resolver.js +1152 -0
  76. package/lib/result-archive.js +157 -0
  77. package/lib/revisions.js +330 -0
  78. package/lib/search-database.js +62 -0
  79. package/lib/search-index.js +601 -0
  80. package/lib/search-scan.js +185 -0
  81. package/lib/search-source.js +23 -0
  82. package/lib/search-terms.js +539 -0
  83. package/lib/section-audit.js +209 -0
  84. package/lib/selection-message.js +332 -0
  85. package/lib/serial-tail.js +21 -0
  86. package/lib/slicing.js +425 -0
  87. package/lib/source-resolver.js +581 -0
  88. package/lib/stem-repair.js +189 -0
  89. package/lib/storage.js +562 -0
  90. package/lib/store-paths.js +253 -0
  91. package/lib/table-gfm.js +236 -0
  92. package/lib/tasks.js +270 -0
  93. package/lib/tex-align.js +509 -0
  94. package/lib/tex-blocks.js +653 -0
  95. package/lib/tex-fetch.js +455 -0
  96. package/lib/tex-figures.js +140 -0
  97. package/lib/tex-inline.js +166 -0
  98. package/lib/tex-merge.js +279 -0
  99. package/lib/tex-pipeline.js +242 -0
  100. package/lib/tex-prepare.js +746 -0
  101. package/lib/tex-tables.js +210 -0
  102. package/lib/text-similarity.js +85 -0
  103. package/lib/tool-contract.js +86 -0
  104. package/lib/tool-host.js +1058 -0
  105. package/lib/tool-identity.js +214 -0
  106. package/lib/translatable-text.js +48 -0
  107. package/lib/translate-prompts.js +709 -0
  108. package/lib/translate-queue.js +418 -0
  109. package/lib/translate-task.js +158 -0
  110. package/lib/translate.js +909 -0
  111. package/lib/update-check.js +438 -0
  112. package/lib/update-contracts.js +75 -0
  113. package/lib/usage.js +282 -0
  114. package/package.json +55 -4
@@ -0,0 +1,438 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { readFile, realpath } from 'node:fs/promises'
3
+ import { dirname, join } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+
6
+ import {
7
+ UPDATE_INSTALL_SPEC, UPDATE_MANUAL_COMMAND, UPDATE_PACKAGE_NAME, UPDATE_REGISTRY_URL, updateAddCommand,
8
+ } from './update-contracts.js'
9
+
10
+ /**
11
+ * 「检查更新 / 一键升级」(D193)。上游 dsh-subscription 的同名通路,逐条照搬它的判断。
12
+ *
13
+ * 三个守卫决定一键升级可不可能,且都在**按钮出现之前**就答完,所以点下去不会失败:
14
+ *
15
+ * 1. link:/file: 安装是开发者的工作树,装上去会覆盖正在编辑的文件。优先问 pluginManager
16
+ * (它按 profile manifest 给出 pnpm 会接受的 spec,仍带 link:/file: 协议),
17
+ * 问不到就看解析后的路径(开发依赖解析到 node_modules 之外)。
18
+ * 2. 没有 pluginManager 服务就是没有东西能跑 pnpm。
19
+ * 3. registry 不应答就是没有版本可装。
20
+ *
21
+ * POST 要装的 spec 是常量 UPDATE_INSTALL_SPEC,请求体一个字段都不读。
22
+ *
23
+ * HMR 宿主上的一键升级**不能是一次 install**:它的 installBundle 拒绝覆盖 profile 里
24
+ * 已装的包(already-installed)。官方插件管理器的更新动作是「先移除再装」,这里走同一条:
25
+ * 先试直接装,只有撞到这个拒绝才回退到 remove-then-install,且第二次装失败要把原版本装回去。
26
+ * 直接装在前的理由是:宿主若能接受安装,磁盘上的副本一瞬都不会消失。
27
+ */
28
+
29
+ /** manifest 往上找几层。打包副本在 lib/index.js 一层,源码副本也就一两层。 */
30
+ const MANIFEST_WALK_DEPTH = 6
31
+
32
+ /** registry 多久不应答就算失败。 */
33
+ const REGISTRY_TIMEOUT_MS = 8000
34
+
35
+ /**
36
+ * 定位这一份副本自己的 manifest。
37
+ *
38
+ * 起点是本模块自己的 URL,**不是固定相对路径**:打包副本在 lib/index.js、
39
+ * 源码副本在别处,../package.json 指的不是同一个文件。只接受 name 对得上的那份,
40
+ * 这也顺带在 workspace 根停住。
41
+ *
42
+ * @param {string} [fromFile] 起点,默认本模块
43
+ * @returns {Promise<{version: string|null, root: string}|null>}
44
+ */
45
+ export async function readOwnManifest(fromFile = fileURLToPath(import.meta.url)) {
46
+ let directory = dirname(fromFile)
47
+ for (let depth = 0; depth <= MANIFEST_WALK_DEPTH; depth += 1) {
48
+ const manifest = await readJsonObject(join(directory, 'package.json'))
49
+ if (manifest?.name === UPDATE_PACKAGE_NAME) {
50
+ return { version: typeof manifest.version === 'string' ? manifest.version : null, root: directory }
51
+ }
52
+ const parent = dirname(directory)
53
+ if (parent === directory) return null
54
+ directory = parent
55
+ }
56
+ return null
57
+ }
58
+
59
+ /** 读一个 JSON 对象;缺失、读不动、不是对象一律 null。 */
60
+ async function readJsonObject(path) {
61
+ try {
62
+ const parsed = JSON.parse(await readFile(path, 'utf8'))
63
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed : null
64
+ } catch {
65
+ return null
66
+ }
67
+ }
68
+
69
+ /**
70
+ * 路径暗示的安装方式。
71
+ *
72
+ * registry 装的包解析到 node_modules 之下;link:/file: 依赖解析到作者放源码的地方,
73
+ * 不在其中。按**整段**匹配而不是子串,免得 node_modules-backup 冒充正牌。
74
+ *
75
+ * @param {string} root 解析符号链接之后的插件根
76
+ * @returns {'registry'|'link'}
77
+ */
78
+ export function installKindFromPath(root) {
79
+ return root.split(/[\\/]+/).includes('node_modules') ? 'registry' : 'link'
80
+ }
81
+ /** 一条版本:数字三段 + prerelease 尾巴。 */
82
+ const VERSION_PATTERN = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/
83
+
84
+ function parseVersion(value) {
85
+ const match = VERSION_PATTERN.exec(String(value).trim())
86
+ if (match === null) return null
87
+ return { parts: [Number(match[1]), Number(match[2]), Number(match[3])], prerelease: match[4] ?? null }
88
+ }
89
+
90
+ /**
91
+ * 比较两个 semver 字符串(含 prerelease)。
92
+ *
93
+ * 只实现这个功能需要的部分:数字三段,以及「prerelease 排在同样数字的正式版之下」。
94
+ * build metadata 按 semver 要求忽略。
95
+ *
96
+ * @param {string} left
97
+ * @param {string} right
98
+ * @returns {number|null} 负数 left 更旧、0 相等、正数更新;任一侧不是能排序的版本时 null
99
+ */
100
+ export function compareVersions(left, right) {
101
+ const a = parseVersion(left)
102
+ const b = parseVersion(right)
103
+ if (a === null || b === null) return null
104
+ for (let index = 0; index < 3; index += 1) {
105
+ const difference = a.parts[index] - b.parts[index]
106
+ if (difference !== 0) return difference
107
+ }
108
+ if (a.prerelease === b.prerelease) return 0
109
+ if (a.prerelease === null) return 1
110
+ if (b.prerelease === null) return -1
111
+ const leftIds = a.prerelease.split('.')
112
+ const rightIds = b.prerelease.split('.')
113
+ for (let index = 0; index < Math.max(leftIds.length, rightIds.length); index += 1) {
114
+ const one = leftIds[index]
115
+ const other = rightIds[index]
116
+ if (one === undefined) return -1
117
+ if (other === undefined) return 1
118
+ if (one === other) continue
119
+ const oneNumeric = /^\d+$/.test(one)
120
+ const otherNumeric = /^\d+$/.test(other)
121
+ if (oneNumeric && otherNumeric) return Number(one) - Number(other)
122
+ if (oneNumeric) return -1
123
+ if (otherNumeric) return 1
124
+ return one < other ? -1 : 1
125
+ }
126
+ return 0
127
+ }
128
+
129
+ /**
130
+ * 问 registry 最新发布版。
131
+ *
132
+ * 🔴 **404 与"连不上"必须是两个不同的结论。** 最初这里把一切都折成 null,界面统一说
133
+ * 「连不上 npm registry」——而那台机器网络明明是通的,只是这个包**还没发布**(或者被删了)。
134
+ * 用户实测指出来过一次:他自己打开 npmjs.com 一切正常,界面却说连不上。
135
+ * 给错的原因是比不给更糟的:它会让人去查网络,而真正要做的是发布。
136
+ *
137
+ * 三种结果:
138
+ * - `{ kind: 'ok', version }` 拿到版本
139
+ * - `{ kind: 'missing' }` registry 应答了,但没有这个包(404)—— 还没发布
140
+ * - `{ kind: 'unreachable' }` 网络/代理/超时/应答不是 JSON
141
+ *
142
+ * 检查本身只是便利:任何失败都不抛,也不回 500 —— 那会让一台**只是离线**的机器
143
+ * 看起来像「插件坏了」。
144
+ *
145
+ * @param {typeof fetch} fetchFn
146
+ * @returns {Promise<{kind: 'ok', version: string}|{kind: 'missing'}|{kind: 'unreachable'}>}
147
+ */
148
+ async function readLatestPublishedVersion(fetchFn) {
149
+ let response
150
+ try {
151
+ response = await fetchFn(UPDATE_REGISTRY_URL, {
152
+ headers: { accept: 'application/json' },
153
+ signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),
154
+ })
155
+ } catch {
156
+ // 连接被拒、代理不应答、超时、DNS 挂了 —— 这些才是"连不上"。
157
+ return { kind: 'unreachable' }
158
+ }
159
+ // 404 = 这个包在 registry 上不存在(还没发布)。其余非 2xx 归为不可达:
160
+ // 5xx 是 registry 自己的问题,403 可能是镜像站策略 —— 都不是"还没发布"。
161
+ if (response.status === 404) return { kind: 'missing' }
162
+ if (!response.ok) return { kind: 'unreachable' }
163
+ try {
164
+ const body = await response.json()
165
+ const version = body?.version
166
+ return typeof version === 'string' && version !== ''
167
+ ? { kind: 'ok', version }
168
+ // 应答了但文档里没有 version:这是 registry 的数据问题,不是"还没发布"。
169
+ : { kind: 'unreachable' }
170
+ } catch {
171
+ // 拿到了 200 但不是 JSON(代理的拦截页、镜像的 HTML 错误页)。
172
+ return { kind: 'unreachable' }
173
+ }
174
+ }
175
+ /** pluginManager 报出来的安装方式(它说得出时优先信它)。 */
176
+ async function installKindFromManager(manager) {
177
+ if (manager === null || typeof manager.listBundles !== 'function') return null
178
+ let rows
179
+ try {
180
+ rows = await manager.listBundles()
181
+ } catch {
182
+ return null
183
+ }
184
+ const row = Array.isArray(rows) ? rows.find(entry => entry?.name === UPDATE_PACKAGE_NAME) : undefined
185
+ const source = row?.source
186
+ if (typeof source !== 'string' || source === '') return null
187
+ // 装在别的名字下的依赖读作 `<other-name>@link:/abs`。
188
+ const protocol = /^(?:[^:@/]*@)?(link|file):/.exec(source)?.[1]
189
+ if (protocol === 'link' || protocol === 'file') return protocol
190
+ return 'registry'
191
+ }
192
+
193
+ /** 这一份是怎么到磁盘的,优先信 pluginManager 的答案。 */
194
+ async function resolveInstallKind(manifest, manager) {
195
+ const reported = await installKindFromManager(manager)
196
+ if (reported !== null) return reported
197
+ if (manifest === null) return 'unknown'
198
+ // 先解析符号链接:link: 依赖的目录**本身**可能就是指向 node_modules 的链接,
199
+ // 决定的是安装位置。
200
+ const resolved = await realpath(manifest.root).catch(() => manifest.root)
201
+ return installKindFromPath(resolved)
202
+ }
203
+
204
+ /**
205
+ * 一键升级不可用的原因。
206
+ *
207
+ * @param {string|null} latest 已发布版本,registry 没答时 null
208
+ * @param {string} installKind 这一份怎么来的
209
+ * @param {boolean} hasManager 有没有 pluginManager 能装
210
+ * @returns {string|undefined}
211
+ */
212
+ function blockedReasonFor(latest, installKind, hasManager, registryKind = 'unreachable') {
213
+ // 🔴 还没发布是**另一种**情况,不能说成"连不上":这里网络是通的。
214
+ if (registryKind === 'missing') return 'not-published'
215
+ // 检查失败排最前:没有已发布版本就没有可装的东西,另外两条说什么都不重要。
216
+ if (latest === null) return 'registry-unreachable'
217
+ if (installKind === 'link' || installKind === 'file') return 'development-install'
218
+ if (!hasManager) return 'plugin-manager-missing'
219
+ return undefined
220
+ }
221
+
222
+ /** 拒绝里那些光看代码说不明白的,给一句话。 */
223
+ const INSTALL_FAILURE_HINTS = Object.freeze({
224
+ 'already-installed': '这台宿主自己应用插件改动,且不会覆盖已经装过的包:先移除,再从「设置 › 插件」重新安装。',
225
+ 'not-bundle': '已发布的包没有声明 bundle patch,这台宿主不会加载它。',
226
+ 'incompatible-version': '已发布的包不接受当前运行的 DSH 版本。',
227
+ })
228
+
229
+ function messageOf(error) {
230
+ return error instanceof Error ? error.message : String(error)
231
+ }
232
+
233
+ /** 抛出来的 manager 失败带的机器可读码(有的话)。 */
234
+ function thrownCode(error) {
235
+ if (typeof error !== 'object' || error === null) return undefined
236
+ const code = error.code
237
+ return typeof code === 'string' ? code : undefined
238
+ }
239
+
240
+ /** 装一条 spec,把抛出来的调用折成一份结果。 */
241
+ async function installSpec(manager, spec) {
242
+ try {
243
+ return await manager.installBundle(spec, { enabled: true, requestId: randomUUID() })
244
+ } catch (error) {
245
+ return { application: 'failed', error: { code: thrownCode(error) ?? 'operation-error', diagnostic: messageOf(error) } }
246
+ }
247
+ }
248
+
249
+ /** 移除已装的那份。 */
250
+ async function removeInstalledCopy(manager) {
251
+ if (typeof manager.removeBundle !== 'function') {
252
+ return { application: 'failed', error: { code: 'remove-unavailable', diagnostic: '这台宿主没有提供 removeBundle。' } }
253
+ }
254
+ try {
255
+ return await manager.removeBundle(UPDATE_PACKAGE_NAME)
256
+ } catch (error) {
257
+ return { application: 'failed', error: { code: thrownCode(error) ?? 'operation-error', diagnostic: messageOf(error) } }
258
+ }
259
+ }
260
+
261
+ function settled(result) {
262
+ return result.application !== 'failed' && result.application !== 'cancelled'
263
+ }
264
+
265
+ /** 一次成功的 apply;restartRequired 读安装自己的回答,不假设。 */
266
+ function appliedOutcome(result, removedFirst) {
267
+ return {
268
+ ok: true,
269
+ installed: result.version ?? 'unknown',
270
+ // HMR profile 的宿主会就地换代并回 applied;其它情况加载的模块还停在旧版。
271
+ restartRequired: result.application !== 'applied',
272
+ removedFirst,
273
+ }
274
+ }
275
+ /**
276
+ * 官方更新路径需要的移除没成功时,为什么。
277
+ *
278
+ * 此时什么都没装成:工作副本还在磁盘上(或处于这条通路读不懂的状态),
279
+ * 唯一诚实的结果是一个指出出路的拒绝。
280
+ */
281
+ function removalFailureMessage(result) {
282
+ const code = result.error?.code
283
+ if (code === 'stop-profile') {
284
+ return {
285
+ code: 'stop-profile',
286
+ message: '这台宿主不会移除运行中的 profile 已经加载的插件,所以要先把 profile 停掉:停掉宿主,跑 ' + UPDATE_MANUAL_COMMAND + ',再启动。「设置 › 插件」做的是同一次移除。',
287
+ }
288
+ }
289
+ if (code === 'remove-unavailable') {
290
+ return {
291
+ code: 'install-failed',
292
+ message: '这台宿主拒绝在已装的包上再装,又没有提供移除的办法,所以这里没法完成更新。请手动跑 ' + UPDATE_MANUAL_COMMAND + '。',
293
+ }
294
+ }
295
+ if (settled(result) && result.changed === false) {
296
+ return {
297
+ code: 'install-failed',
298
+ message: '宿主报告了移除但 profile 没有变化,所以旧的那份还在、新的一点没装。请手动跑 ' + UPDATE_MANUAL_COMMAND + '。',
299
+ }
300
+ }
301
+ const detail = result.error?.diagnostic ?? result.packageResult?.output?.trim()
302
+ const reason = ['移除已装的副本失败,所以新版本没有装上。', detail]
303
+ .filter(part => part !== undefined && part !== '')
304
+ .join(' ')
305
+ return { code: 'install-failed', message: reason + ' 请手动跑 ' + UPDATE_MANUAL_COMMAND + '。' }
306
+ }
307
+
308
+ /**
309
+ * 装失败之后把原来那个版本装回去。
310
+ *
311
+ * 走到这里时移除已经发生,磁盘上没有工作副本了,别的东西不会把它补回来。
312
+ * 回滚用的版本来自**本进程自己读的 manifest**,从不来自请求;版本读不到就跳过回滚而不是瞎猜。
313
+ */
314
+ async function rollBackAfterFailedUpdate(manager, currentVersion, failed) {
315
+ const reason = installFailureMessage(failed)
316
+ if (currentVersion === null) {
317
+ return {
318
+ ok: false,
319
+ code: 'install-failed',
320
+ rollback: 'skipped',
321
+ message: reason + ' 已装的副本已经被移除,而本进程读不到自己的版本,所以没有装回去。请跑 ' + UPDATE_MANUAL_COMMAND + ' 重新安装。',
322
+ }
323
+ }
324
+ const spec = UPDATE_PACKAGE_NAME + '@' + currentVersion
325
+ const restored = await installSpec(manager, spec)
326
+ if (settled(restored)) {
327
+ const version = restored.version ?? currentVersion
328
+ return {
329
+ ok: false,
330
+ code: 'install-failed',
331
+ rollback: 'restored',
332
+ restoredVersion: version,
333
+ message: reason + ' 已经重新装回 ' + version + ',插件和之前一样继续运行。',
334
+ }
335
+ }
336
+ return {
337
+ ok: false,
338
+ code: 'install-failed',
339
+ rollback: 'failed',
340
+ message: reason + ' 把 ' + currentVersion + ' 装回去也失败了(' + installFailureMessage(restored) + '),插件很可能已经不在。请手动 ' + updateAddCommand(spec) + ' 并重启宿主。',
341
+ }
342
+ }
343
+
344
+ /**
345
+ * 装已发布版;宿主拒绝覆盖已装包时走官方更新路径。
346
+ *
347
+ * 顺序是刻意的:直接装先跑,所以没有 HMR 的宿主、以及任何接受这次安装的宿主,
348
+ * 工作副本一瞬都不会消失。只有已装包引起的那个拒绝才落到 remove-then-install,
349
+ * 也只有那条路径会报回滚。
350
+ */
351
+ async function applyPublishedUpdate(manager, currentVersion) {
352
+ const direct = await installSpec(manager, UPDATE_INSTALL_SPEC)
353
+ if (settled(direct)) return appliedOutcome(direct, false)
354
+ if (direct.error?.code !== 'already-installed') {
355
+ // 这次失败与磁盘上已有的副本无关,移除它等于把「升级失败」变成「插件没了」。
356
+ return { ok: false, code: 'install-failed', message: installFailureMessage(direct) }
357
+ }
358
+ const removed = await removeInstalledCopy(manager)
359
+ if (!settled(removed) || removed.changed === false) return { ok: false, ...removalFailureMessage(removed) }
360
+ const replaced = await installSpec(manager, UPDATE_INSTALL_SPEC)
361
+ if (settled(replaced)) return appliedOutcome(replaced, true)
362
+ return await rollBackAfterFailedUpdate(manager, currentVersion, replaced)
363
+ }
364
+
365
+ /** 安装没发生的原因,用调用方该读的话说。 */
366
+ function installFailureMessage(result) {
367
+ const code = result.error?.code
368
+ const hint = code === undefined ? undefined : INSTALL_FAILURE_HINTS[code]
369
+ const detail = result.error?.diagnostic ?? result.packageResult?.output?.trim()
370
+ const parts = [hint, detail].filter(part => part !== undefined && part !== '')
371
+ return parts.length === 0 ? '安装没有完成。' : parts.join(' ')
372
+ }
373
+ /**
374
+ * 检查更新与一键升级的核心:两条通路都是纯逻辑,不碰 HTTP。
375
+ *
376
+ * @param {{fetchFn?: typeof fetch, readManifest?: Function, manager?: Function}} [options]
377
+ */
378
+ export function createUpdateService(options = {}) {
379
+ const fetchFn = typeof options.fetchFn === 'function' ? options.fetchFn : fetch
380
+ const readManifest = typeof options.readManifest === 'function' ? options.readManifest : () => readOwnManifest()
381
+ const resolveManager = typeof options.manager === 'function' ? options.manager : () => null
382
+
383
+ return {
384
+ /** 一次版本检查。只读:不改任何东西。 */
385
+ async check() {
386
+ const checkedAt = Date.now()
387
+ const manifest = await readManifest()
388
+ const manager = resolveManager()
389
+ const current = manifest?.version ?? null
390
+ const [registry, installKind] = await Promise.all([readLatestPublishedVersion(fetchFn), resolveInstallKind(manifest, manager)])
391
+ const latest = registry.kind === 'ok' ? registry.version : null
392
+ const comparison = current === null || latest === null ? null : compareVersions(latest, current)
393
+ const updateAvailable = comparison !== null && comparison > 0
394
+ const reason = blockedReasonFor(latest, installKind, manager !== null, registry.kind)
395
+ return {
396
+ current,
397
+ latest,
398
+ updateAvailable,
399
+ installKind,
400
+ // 只有「有东西可装」且每个守卫都同意时才提供安装;读不懂的安装方式不是
401
+ // 可以拿来做一键替换的基础。
402
+ canApply: updateAvailable && reason === undefined && installKind === 'registry',
403
+ ...(reason === undefined ? {} : { reason }),
404
+ // 🔴 把 registry 的三种结论原样带给界面:404(还没发布)与连不上是两种修法,
405
+ // 合并成一句话会让人去查网络,而真正要做的是发布。
406
+ registry: registry.kind,
407
+ command: UPDATE_MANUAL_COMMAND,
408
+ checkedAt,
409
+ }
410
+ },
411
+
412
+ /** 装已发布的那一版。会改变插件本身 —— 这是本插件里唯一这样的动作。 */
413
+ async apply() {
414
+ const manifest = await readManifest()
415
+ const manager = resolveManager()
416
+ const installKind = await resolveInstallKind(manifest, manager)
417
+ // 顺序与卡片守卫的顺序一致,所以宿主答 check 一个样、答 apply 另一个样的情况不会发生。
418
+ if (installKind === 'link' || installKind === 'file') {
419
+ return { ok: false, status: 409, code: 'development-install', message: '这一份是从本地路径装的,替换它会覆盖被链接的那棵工作树。要装已发布的包请跑 ' + UPDATE_MANUAL_COMMAND + '。' }
420
+ }
421
+ if (manager === null) {
422
+ return { ok: false, status: 409, code: 'plugin-manager-missing', message: '这台宿主没有提供插件管理器,所以更新不能在这里跑。请改用 ' + UPDATE_MANUAL_COMMAND + '。' }
423
+ }
424
+ const outcome = await applyPublishedUpdate(manager, manifest?.version ?? null)
425
+ if (!outcome.ok) {
426
+ return {
427
+ ok: false,
428
+ status: outcome.code === 'stop-profile' ? 409 : 502,
429
+ code: outcome.code,
430
+ message: outcome.message,
431
+ ...(outcome.rollback === undefined ? {} : { rollback: outcome.rollback }),
432
+ ...(outcome.restoredVersion === undefined ? {} : { restoredVersion: outcome.restoredVersion }),
433
+ }
434
+ }
435
+ return { ok: true, installed: outcome.installed, restartRequired: outcome.restartRequired, removedFirst: outcome.removedFirst }
436
+ },
437
+ }
438
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * 检查更新 / 一键升级的线格式(D193)。
3
+ *
4
+ * 两条通路:GET 回答「registry 上是什么版本、这一份是怎么到磁盘的、这台宿主能不能装」,
5
+ * POST 执行那次安装。字段全是设置卡可以渲染的非机密事实。
6
+ *
7
+ * 🔴 要装的 spec **写死在服务端**(见 UPDATE_INSTALL_SPEC),**不从请求体读** ——
8
+ * 否则任何能发同源 POST 的东西都能往 profile 里装任意包。这与 install-dependency 的
9
+ * 白名单是同一条原则:会改变机器状态的入口,输入面只能是「选一个预置动作」。
10
+ */
11
+
12
+ /** 这份构建的包名。两条通路都只作用于这一个名字。 */
13
+ export const UPDATE_PACKAGE_NAME = '@li-canghai/dsh-paper'
14
+
15
+ /**
16
+ * 一键升级要装的那条 spec。
17
+ *
18
+ * 写在这里而不是从请求体收:一条从调用方读包名的通路,等于让任何同源 POST
19
+ * 都能往 profile 里装任意包。
20
+ */
21
+ export const UPDATE_INSTALL_SPEC = UPDATE_PACKAGE_NAME + '@latest'
22
+
23
+ /** 版本检查读的 registry 文档(scoped 包要 URL 编码斜杠,所以用 name/latest 而不是 name%2Flatest)。 */
24
+ export const UPDATE_REGISTRY_URL = 'https://registry.npmjs.org/' + UPDATE_PACKAGE_NAME.replace('/', '%2F') + '/latest'
25
+
26
+ /**
27
+ * 一条可粘贴的手动命令。
28
+ *
29
+ * 一键升级被拒时(本地 link 安装、宿主没有 pluginManager),这是唯一的出路,
30
+ * 所以每个结果都带上它。
31
+ *
32
+ * @param spec 要装的 spec,默认 {@link UPDATE_INSTALL_SPEC}
33
+ * @returns 能粘进终端的命令行
34
+ */
35
+ export function updateAddCommand(spec = UPDATE_INSTALL_SPEC) {
36
+ return 'dsh plugin add ' + spec
37
+ }
38
+
39
+ /** 卡片装不了时用户自己跑的命令。 */
40
+ export const UPDATE_MANUAL_COMMAND = updateAddCommand()
41
+
42
+ /** 这一份副本是怎么到磁盘上的。 */
43
+ export const INSTALL_KINDS = Object.freeze(['registry', 'link', 'file', 'unknown'])
44
+
45
+ /**
46
+ * 一键升级不可用的原因。
47
+ *
48
+ * - `development-install`:正在跑的是 `link:`/`file:` 依赖,装上去会覆盖开发者正在编辑的工作树;
49
+ * - `plugin-manager-missing`:这台宿主没有 pluginManager 服务,没有任何东西能跑 pnpm;
50
+ * - `registry-unreachable`:版本检查本身失败,还不知道有什么可装。
51
+ */
52
+ export const UPDATE_BLOCKED_REASONS = Object.freeze(['development-install', 'plugin-manager-missing', 'registry-unreachable'])
53
+
54
+ /**
55
+ * 一次版本检查的结论。
56
+ *
57
+ * 卡片渲染的四种结果完全由这些字段推出:
58
+ *
59
+ * | 结果 | 字段 |
60
+ * | --- | --- |
61
+ * | 已是最新 | `latest` 有值、`updateAvailable: false`、无 `reason` |
62
+ * | 有新版本,可一键 | `updateAvailable: true`、`canApply: true` |
63
+ * | 有新版本,只能手装 | `updateAvailable: true`、`canApply: false`、有 `reason` |
64
+ * | 检查失败 | `latest: null`、`reason: 'registry-unreachable'` |
65
+ *
66
+ * @typedef {object} UpdateCheckDto
67
+ * @property {string|null} current 这一进程跑的版本;定位不到 manifest 时为 null(卡片说「未知」而不是编一个)
68
+ * @property {string|null} latest registry 上的最新版;registry 没应答时 null
69
+ * @property {boolean} updateAvailable latest 严格新于 current
70
+ * @property {'registry'|'link'|'file'|'unknown'} installKind 这一份是怎么到磁盘的
71
+ * @property {boolean} canApply POST 能不能在这台机器上装
72
+ * @property {string} [reason] 恰好在 canApply 为假且原因值得说时出现
73
+ * @property {string} command 手动命令,永远存在——每种结果都有逃生口
74
+ * @property {number} checkedAt 问 registry 的时刻(Unix 毫秒)
75
+ */