@li-canghai/dsh-paper 0.0.0-stage → 0.8.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 (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -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 +2762 -0
  19. package/lib/client-parts/02-author-year.js +95 -0
  20. package/lib/client.js +10381 -0
  21. package/lib/code-source.js +68 -0
  22. package/lib/concurrency-gate.js +91 -0
  23. package/lib/context.js +233 -0
  24. package/lib/csl/SOURCES.md +10 -0
  25. package/lib/csl/gb-t-7714.csl +441 -0
  26. package/lib/csl/ieee.csl +520 -0
  27. package/lib/csl/locales-zh-CN.xml +438 -0
  28. package/lib/csl/nature.csl +190 -0
  29. package/lib/discussion.js +400 -0
  30. package/lib/documents.js +67 -0
  31. package/lib/export.js +848 -0
  32. package/lib/file-lock.js +177 -0
  33. package/lib/gloss.js +181 -0
  34. package/lib/glossary.js +279 -0
  35. package/lib/index.js +3862 -0
  36. package/lib/inline-html.js +53 -0
  37. package/lib/install-dependency.js +120 -0
  38. package/lib/item-ops.js +83 -0
  39. package/lib/job-facade.js +58 -0
  40. package/lib/json-store.js +54 -0
  41. package/lib/library-model.js +132 -0
  42. package/lib/library-service.js +180 -0
  43. package/lib/library-tool.js +982 -0
  44. package/lib/library.js +814 -0
  45. package/lib/markdown-assets.js +138 -0
  46. package/lib/markdown-literals.js +93 -0
  47. package/lib/metadata-enrichment.js +516 -0
  48. package/lib/metadata-fetch.js +146 -0
  49. package/lib/metadata-node.js +158 -0
  50. package/lib/metadata-proxy.ps1 +35 -0
  51. package/lib/mineru-config.js +95 -0
  52. package/lib/mineru-sdk-helper.py +123 -0
  53. package/lib/mineru-sdk.js +182 -0
  54. package/lib/mineru.js +268 -0
  55. package/lib/mirror-export.js +240 -0
  56. package/lib/outline.js +296 -0
  57. package/lib/page-image-helper.py +308 -0
  58. package/lib/page-image.js +454 -0
  59. package/lib/paper-metadata.js +242 -0
  60. package/lib/parse-export.js +631 -0
  61. package/lib/pdf-analysis-tool.js +750 -0
  62. package/lib/pdf-metadata-helper.py +75 -0
  63. package/lib/pdf-metadata.js +141 -0
  64. package/lib/pdf-page.js +261 -0
  65. package/lib/pdf-scan.js +134 -0
  66. package/lib/pdf-text.js +68 -0
  67. package/lib/picker.js +305 -0
  68. package/lib/portable.js +379 -0
  69. package/lib/purge.js +170 -0
  70. package/lib/read-tool.js +660 -0
  71. package/lib/reader-store.js +497 -0
  72. package/lib/reading-order.js +207 -0
  73. package/lib/rename-document.js +480 -0
  74. package/lib/rename.js +372 -0
  75. package/lib/renderer-status.js +161 -0
  76. package/lib/resolver.js +1152 -0
  77. package/lib/result-archive.js +157 -0
  78. package/lib/revisions.js +330 -0
  79. package/lib/search-database.js +62 -0
  80. package/lib/search-index.js +601 -0
  81. package/lib/search-scan.js +185 -0
  82. package/lib/search-source.js +23 -0
  83. package/lib/search-terms.js +539 -0
  84. package/lib/section-audit.js +209 -0
  85. package/lib/selection-message.js +332 -0
  86. package/lib/serial-tail.js +21 -0
  87. package/lib/slicing.js +425 -0
  88. package/lib/source-resolver.js +581 -0
  89. package/lib/stem-repair.js +189 -0
  90. package/lib/storage.js +562 -0
  91. package/lib/store-paths.js +253 -0
  92. package/lib/table-gfm.js +236 -0
  93. package/lib/tasks.js +270 -0
  94. package/lib/tex-align.js +509 -0
  95. package/lib/tex-blocks.js +653 -0
  96. package/lib/tex-fetch.js +455 -0
  97. package/lib/tex-figures.js +140 -0
  98. package/lib/tex-inline.js +166 -0
  99. package/lib/tex-merge.js +279 -0
  100. package/lib/tex-pipeline.js +242 -0
  101. package/lib/tex-prepare.js +746 -0
  102. package/lib/tex-tables.js +210 -0
  103. package/lib/text-similarity.js +85 -0
  104. package/lib/tool-contract.js +86 -0
  105. package/lib/tool-host.js +1058 -0
  106. package/lib/tool-identity.js +214 -0
  107. package/lib/translatable-text.js +48 -0
  108. package/lib/translate-prompts.js +709 -0
  109. package/lib/translate-queue.js +418 -0
  110. package/lib/translate-task.js +158 -0
  111. package/lib/translate.js +909 -0
  112. package/lib/update-check.js +438 -0
  113. package/lib/update-contracts.js +75 -0
  114. package/lib/usage.js +282 -0
  115. package/package.json +55 -4
@@ -0,0 +1,189 @@
1
+ /**
2
+ * 论文资产被劈成两套主名时的对账与修复(D178)。
3
+ *
4
+ * 🔴 **为什么会劈开**:`pdfName` 同时是一篇论文 9 个资产的主名(见 store-paths.js)。`add()`
5
+ * 早先跟着**源文件名**走,而用户目录里的文件名可能已经和记录里冻结的那个不同(D156 改过名、
6
+ * 或用户自己改过)—— 于是同一个 `library/<documentId>/` 目录里落下两套主名的资产:
7
+ * 记录指向的那套缺块列表/译文/划线,另一套有。
8
+ *
9
+ * 症状不是"文件多了几个":缺 `.content.json` 意味着块列表读不出来,`planTranslation` 直接报
10
+ * 「这篇论文没有块列表(旧产物或 MinerU 降级),无法按块翻译」—— 一键翻译整批里就有两篇卡在这。
11
+ *
12
+ * 🔴 **目录即论文**:`library/<documentId>/` 里的所有文件都属于同一篇(documentId 是 PDF 内容的
13
+ * sha256)。所以同目录里另一个主名的文件不是"别人的东西",就是这篇论文自己的另一半。判据仍然
14
+ * 收紧到「**恰好一个**别的候选主名」:多份就只报告不猜(同一条口径 —— 错误的线比没有线更坏)。
15
+ *
16
+ * 🔴 **覆盖正文前必须逐字核对**:把另一套的 `.md` 搬过来是为了拿回 `<!-- b:id -->` 块标记,
17
+ * 不是为了让两份正文互相覆盖。去掉标记后不是逐字相同就一个字节都不动 —— 宁可继续没有标记,
18
+ * 也不能把用户正在读的正文换成另一份内容。
19
+ */
20
+ import { copyFile, readdir, readFile, writeFile } from 'node:fs/promises'
21
+ import { join } from 'node:path'
22
+ import { hydrateDocument } from './portable.js'
23
+ import { stemOf, storePathsOf } from './store-paths.js'
24
+
25
+ /** 主名派生出来的资产后缀。**最长优先**:`.outline.md` 必须先于 `.md` 试,否则主名会被截成 `X.outline`。 */
26
+ const ASSET_SUFFIXES = ['.outline.md', '.content.json', '.dsh-paper.json', '.translation.json', '.reader.json', '.discussion.json', '.item.json', '.pdf', '.md']
27
+
28
+ /** 记录这套里缺了就去另一套拿的资产。正文与目录另走 adoptMarked(要逐字核对,不能直接搬)。 */
29
+ const ADOPTED_SUFFIXES = ['.content.json', '.translation.json', '.reader.json', '.discussion.json', '.item.json']
30
+
31
+ const BLOCK_MARKER = /^<!-- b:[\w.-]+ -->\r?\n?/gm
32
+ const OUTLINE_RANGE = / \[b:[^\]]*\]/g
33
+
34
+ function errorText(error) {
35
+ return String(error?.message ?? error).slice(0, 500)
36
+ }
37
+
38
+ /** 去掉块标记。用来把"有没有标记"与"内容对不对"分开看。 */
39
+ export function withoutBlockMarkers(text) {
40
+ return String(text ?? '').replace(BLOCK_MARKER, '')
41
+ }
42
+
43
+ /** 去掉目录里的 `[b:… .. b:…]` 区间,只留标题与缩进。 */
44
+ export function withoutOutlineRanges(text) {
45
+ return String(text ?? '').replace(OUTLINE_RANGE, '')
46
+ }
47
+
48
+ /** 比较正文时忽略行尾差异:同一份内容在 Windows 与 LF 两种写法下都算相同。 */
49
+ function sameText(left, right) {
50
+ return String(left ?? '').replace(/\r\n/g, '\n') === String(right ?? '').replace(/\r\n/g, '\n')
51
+ }
52
+
53
+ /**
54
+ * 同目录里"另一套"的主名。**恰好一个**才返回,0 个或 2 个以上都返回空串。
55
+ *
56
+ * @param {string[]} names 目录下的文件名(不含子目录)。
57
+ * @param {string} stem 记录当前用的主名。
58
+ * @returns {string} 唯一候选主名,或空串。
59
+ */
60
+ export function donorStemOf(names, stem) {
61
+ const others = new Set()
62
+ for (const name of names) {
63
+ const suffix = ASSET_SUFFIXES.find(candidate => name.endsWith(candidate))
64
+ if (suffix === undefined) continue
65
+ const owner = name.slice(0, name.length - suffix.length)
66
+ if (owner === '' || owner === stem) continue
67
+ others.add(owner)
68
+ }
69
+ return others.size === 1 ? [...others][0] : ''
70
+ }
71
+
72
+ async function readText(path) {
73
+ try { return await readFile(path, 'utf8') } catch { return undefined }
74
+ }
75
+
76
+ /**
77
+ * 把另一套的正文/目录搬过来 —— **只在两边去掉标记后逐字相同**时动手。
78
+ *
79
+ * 记录那份整个不在时直接拿另一套的补上(它自己就是这篇论文的资产,没有"换成别的内容"的风险);
80
+ * 两份都在就要求逐字核对,不同就原样不动,让记录这份继续保持没有标记的状态。
81
+ *
82
+ * @returns {Promise<boolean>} 是否动过盘。
83
+ */
84
+ async function adoptMarked(targetPath, donorPath, strip) {
85
+ const donor = await readText(donorPath)
86
+ if (donor === undefined) return false
87
+ const target = await readText(targetPath)
88
+ if (target === undefined) {
89
+ await copyFile(donorPath, targetPath)
90
+ return true
91
+ }
92
+ if (sameText(donor, target)) return false
93
+ if (!sameText(strip(donor), strip(target))) return false
94
+ await writeFile(targetPath, donor, 'utf8')
95
+ return true
96
+ }
97
+
98
+ /**
99
+ * 修一篇论文。返回 `{changed, reason, files, swapped, contentPath}`,**不碰记录**(落记录由调用方统一做)。
100
+ *
101
+ * @param {{runtimeRoot: string, document: object}} input
102
+ */
103
+ export async function repairDocumentStem({ runtimeRoot, document }) {
104
+ const empty = { changed: false, files: [], swapped: [], contentPath: '' }
105
+ const paths = storePathsOf(runtimeRoot, document)
106
+ if (!paths) return { ...empty, reason: 'no-id' }
107
+ const stem = stemOf(document.pdfName)
108
+ let names
109
+ try { names = await readdir(paths.dir) } catch (error) {
110
+ if (error?.code === 'ENOENT') return { ...empty, reason: 'no-dir' }
111
+ throw error
112
+ }
113
+ const donor = donorStemOf(names, stem)
114
+ if (donor === '') return { ...empty, reason: 'no-donor' }
115
+ const files = []
116
+ for (const suffix of ADOPTED_SUFFIXES) {
117
+ if (!names.includes(donor + suffix) || names.includes(stem + suffix)) continue
118
+ await copyFile(join(paths.dir, donor + suffix), join(paths.dir, stem + suffix))
119
+ files.push(suffix)
120
+ }
121
+ const swapped = []
122
+ if (await adoptMarked(join(paths.dir, stem + '.md'), join(paths.dir, donor + '.md'), withoutBlockMarkers)) swapped.push('.md')
123
+ if (await adoptMarked(join(paths.dir, stem + '.outline.md'), join(paths.dir, donor + '.outline.md'), withoutOutlineRanges)) swapped.push('.outline.md')
124
+ const contentName = stem + '.content.json'
125
+ const contentPath = names.includes(contentName) || files.includes('.content.json') ? contentName : ''
126
+ return { changed: files.length > 0 || swapped.length > 0, reason: 'ok', files, swapped, contentPath }
127
+ }
128
+
129
+ /**
130
+ * 对账全部 sidecar 记录,把劈开的资产搬回记录主名,并补上 `artifact.contentPath`。
131
+ *
132
+ * 🔴 **一次 `update` 落所有记录**:逐条 `updateDocument` 会把整份 state.json 重写 N 遍
133
+ * (每次还要抢一次跨进程状态锁),与 compact 的既有口径一致。
134
+ *
135
+ * @param {{root: string, snapshot: Function, rawArchivedDocuments: Function, update: Function, writeArchivedDocument: Function}} repository
136
+ * @param {{info?: Function, warn?: Function}} [logger]
137
+ * @returns {Promise<{repaired: Array<object>, failures: Array<{id: string, error: string}>}>}
138
+ */
139
+ export async function repairSplitStems(repository, logger) {
140
+ const state = await repository.snapshot()
141
+ const hot = new Map(Object.entries(state.documents ?? {}))
142
+ const cold = new Map((await repository.rawArchivedDocuments()).map(document => [document.id, document]))
143
+ const ids = new Set([...hot.keys(), ...cold.keys()])
144
+ const patches = new Map()
145
+ const failures = []
146
+ for (const id of ids) {
147
+ const base = hot.get(id) ?? cold.get(id)
148
+ if (base?.artifact?.kind !== 'sidecar') continue
149
+ // 🔴 记录上没有主名就不动。sidecar 冷记录在 archive/ 里只留 `{ id, pdfPath, artifact }`
150
+ // (writeArchivedRecord 显式剔掉 pdfName),于是 stemOf(undefined) 落到兜底名 'document',
151
+ // 而目录里那套**真实主名**的资产会被 donorStemOf 当成「劈开的两套」,正文被复制成
152
+ // `document.md` —— 冷记录每被驱逐一次就白占一份全文,而且对账会永远认为它「劈开了」。
153
+ // 「搬回记录主名」在没有主名时本来就没有目标;按本模块自己的口径(多份候选只报告不猜)跳过。
154
+ if (typeof base.pdfName !== 'string' || base.pdfName === '') continue
155
+ try {
156
+ const result = await repairDocumentStem({ runtimeRoot: repository.root, document: base })
157
+ const missingContent = result.contentPath !== '' && (typeof base.artifact.contentPath !== 'string' || base.artifact.contentPath === '')
158
+ if (!result.changed && !missingContent) continue
159
+ patches.set(id, { document: base, contentPath: missingContent ? result.contentPath : '', files: result.files, swapped: result.swapped })
160
+ } catch (error) {
161
+ failures.push({ id, error: errorText(error) })
162
+ }
163
+ }
164
+ const repaired = []
165
+ if (patches.size > 0) {
166
+ await repository.update(async current => {
167
+ for (const [id, patch] of patches) {
168
+ const record = current.documents?.[id]
169
+ const target = record ?? patch.document
170
+ if (patch.contentPath !== '' && target?.artifact?.kind === 'sidecar') target.artifact.contentPath = patch.contentPath
171
+ try {
172
+ await repository.writeArchivedDocument(hydrateDocument(target))
173
+ } catch (error) {
174
+ failures.push({ id, error: errorText(error) })
175
+ continue
176
+ }
177
+ if (record) current.documents[id] = target
178
+ repaired.push({ id, files: patch.files, swapped: patch.swapped })
179
+ }
180
+ })
181
+ }
182
+ for (const item of repaired) {
183
+ logger?.info?.(`dsh-paper stem repair: 论文 ${item.id} 的资产从另一套主名搬回 ${item.files.length + item.swapped.length} 个文件`)
184
+ }
185
+ for (const failure of failures) {
186
+ logger?.warn?.(`dsh-paper stem repair: 论文 ${failure.id} 修复失败:${failure.error}`)
187
+ }
188
+ return { repaired, failures }
189
+ }