@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.
- package/LICENSE +21 -0
- package/README.md +150 -2
- package/cordis.patch.yml +4 -0
- package/lib/annotate-tool.js +334 -0
- package/lib/arxiv-id.js +74 -0
- package/lib/asset-routes.js +210 -0
- package/lib/bibliography-formats.js +126 -0
- package/lib/bibliography-import.js +105 -0
- package/lib/bibliography-service.js +43 -0
- package/lib/bibliography.js +42 -0
- package/lib/block-authors.js +292 -0
- package/lib/block-cache.js +39 -0
- package/lib/blocks-markdown.js +157 -0
- package/lib/blocks-reconcile.js +218 -0
- package/lib/blocks.js +1344 -0
- package/lib/citation-metadata.js +260 -0
- package/lib/citation-styles.js +120 -0
- package/lib/client-parts/01-pure-helpers.js +2762 -0
- package/lib/client-parts/02-author-year.js +95 -0
- package/lib/client.js +10381 -0
- package/lib/code-source.js +68 -0
- package/lib/concurrency-gate.js +91 -0
- package/lib/context.js +233 -0
- package/lib/csl/SOURCES.md +10 -0
- package/lib/csl/gb-t-7714.csl +441 -0
- package/lib/csl/ieee.csl +520 -0
- package/lib/csl/locales-zh-CN.xml +438 -0
- package/lib/csl/nature.csl +190 -0
- package/lib/discussion.js +400 -0
- package/lib/documents.js +67 -0
- package/lib/export.js +848 -0
- package/lib/file-lock.js +177 -0
- package/lib/gloss.js +181 -0
- package/lib/glossary.js +279 -0
- package/lib/index.js +3862 -0
- package/lib/inline-html.js +53 -0
- package/lib/install-dependency.js +120 -0
- package/lib/item-ops.js +83 -0
- package/lib/job-facade.js +58 -0
- package/lib/json-store.js +54 -0
- package/lib/library-model.js +132 -0
- package/lib/library-service.js +180 -0
- package/lib/library-tool.js +982 -0
- package/lib/library.js +814 -0
- package/lib/markdown-assets.js +138 -0
- package/lib/markdown-literals.js +93 -0
- package/lib/metadata-enrichment.js +516 -0
- package/lib/metadata-fetch.js +146 -0
- package/lib/metadata-node.js +158 -0
- package/lib/metadata-proxy.ps1 +35 -0
- package/lib/mineru-config.js +95 -0
- package/lib/mineru-sdk-helper.py +123 -0
- package/lib/mineru-sdk.js +182 -0
- package/lib/mineru.js +268 -0
- package/lib/mirror-export.js +240 -0
- package/lib/outline.js +296 -0
- package/lib/page-image-helper.py +308 -0
- package/lib/page-image.js +454 -0
- package/lib/paper-metadata.js +242 -0
- package/lib/parse-export.js +631 -0
- package/lib/pdf-analysis-tool.js +750 -0
- package/lib/pdf-metadata-helper.py +75 -0
- package/lib/pdf-metadata.js +141 -0
- package/lib/pdf-page.js +261 -0
- package/lib/pdf-scan.js +134 -0
- package/lib/pdf-text.js +68 -0
- package/lib/picker.js +305 -0
- package/lib/portable.js +379 -0
- package/lib/purge.js +170 -0
- package/lib/read-tool.js +660 -0
- package/lib/reader-store.js +497 -0
- package/lib/reading-order.js +207 -0
- package/lib/rename-document.js +480 -0
- package/lib/rename.js +372 -0
- package/lib/renderer-status.js +161 -0
- package/lib/resolver.js +1152 -0
- package/lib/result-archive.js +157 -0
- package/lib/revisions.js +330 -0
- package/lib/search-database.js +62 -0
- package/lib/search-index.js +601 -0
- package/lib/search-scan.js +185 -0
- package/lib/search-source.js +23 -0
- package/lib/search-terms.js +539 -0
- package/lib/section-audit.js +209 -0
- package/lib/selection-message.js +332 -0
- package/lib/serial-tail.js +21 -0
- package/lib/slicing.js +425 -0
- package/lib/source-resolver.js +581 -0
- package/lib/stem-repair.js +189 -0
- package/lib/storage.js +562 -0
- package/lib/store-paths.js +253 -0
- package/lib/table-gfm.js +236 -0
- package/lib/tasks.js +270 -0
- package/lib/tex-align.js +509 -0
- package/lib/tex-blocks.js +653 -0
- package/lib/tex-fetch.js +455 -0
- package/lib/tex-figures.js +140 -0
- package/lib/tex-inline.js +166 -0
- package/lib/tex-merge.js +279 -0
- package/lib/tex-pipeline.js +242 -0
- package/lib/tex-prepare.js +746 -0
- package/lib/tex-tables.js +210 -0
- package/lib/text-similarity.js +85 -0
- package/lib/tool-contract.js +86 -0
- package/lib/tool-host.js +1058 -0
- package/lib/tool-identity.js +214 -0
- package/lib/translatable-text.js +48 -0
- package/lib/translate-prompts.js +709 -0
- package/lib/translate-queue.js +418 -0
- package/lib/translate-task.js +158 -0
- package/lib/translate.js +909 -0
- package/lib/update-check.js +438 -0
- package/lib/update-contracts.js +75 -0
- package/lib/usage.js +282 -0
- package/package.json +55 -4
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
// lib/reader-store.js —— 划线与笔记的存储层:读写在 analysis/<主名>.reader.json。
|
|
2
|
+
//
|
|
3
|
+
// 只做两件事:把用户划的线与写的笔记原子地落到论文目录旁,以及把它们与**当前**块列表对起来。
|
|
4
|
+
// **不碰 UI、不碰 state.json、不碰 manifest** —— 用户内容一旦进宿主状态,"把论文目录拷走"
|
|
5
|
+
// 就会丢掉全部笔记(D21)。
|
|
6
|
+
//
|
|
7
|
+
// 🔴 锚点是 blockId(定段)+ quote/prefix/suffix(定块内位置),**不是字符下标**:重译只换译文,
|
|
8
|
+
// 块 id 由 blocks.js 的稳定规则给出,所以重译后划线照旧挂在同一段上。
|
|
9
|
+
|
|
10
|
+
import { randomUUID } from 'node:crypto'
|
|
11
|
+
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
|
|
12
|
+
import { dirname } from 'node:path'
|
|
13
|
+
import { plainInlineText } from './inline-html.js'
|
|
14
|
+
import { assertReplaceableFile, isPlainObject } from './json-store.js'
|
|
15
|
+
import { documentPaths, hydrateDocument } from './portable.js'
|
|
16
|
+
import { replaceStateFile } from './storage.js'
|
|
17
|
+
|
|
18
|
+
/** 划线与笔记文件后缀:与正文同目录、同主名(布局的唯一所有者是 store-paths.js)。 */
|
|
19
|
+
export const READER_SUFFIX = '.reader.json'
|
|
20
|
+
|
|
21
|
+
/** 划线文件的 schemaVersion(dsh-paper 自有的持久 JSON 都带,见 D39/D48)。 */
|
|
22
|
+
export const READER_SCHEMA_VERSION = 1
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 四种划线颜色。**取值就是落盘的值**,改一个会让旧文件里的该色落到兜底色上;
|
|
26
|
+
* 真加第五色不会让旧版本读不出来 —— {@link colorOf} 的兜底分支接得住。
|
|
27
|
+
*/
|
|
28
|
+
export const READER_COLORS = Object.freeze(['yellow', 'green', 'blue', 'pink'])
|
|
29
|
+
|
|
30
|
+
/** 颜色缺失或不认识时的兜底色。 */
|
|
31
|
+
export const DEFAULT_READER_COLOR = 'yellow'
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 从文档记录算出划线文件路径。
|
|
35
|
+
*
|
|
36
|
+
* 🔴 与 `<主名>.md` **同目录同主名**(D127 后该目录是 runtime 的 `library/<documentId>/`),
|
|
37
|
+
* 也与 `<主名>.translation.json` 并排 —— 不需要额外记录"笔记在哪"。文档没有 Markdown 路径时
|
|
38
|
+
* 返回 `''`(调用方据此报"这篇还没有可标注的正文")。
|
|
39
|
+
*
|
|
40
|
+
* 🔴 必须先 hydrate:state.documents 里的记录是相对形态(路径按 PDF 目录相对存),
|
|
41
|
+
* 直接读 document.markdownPath 只会拿到 undefined,会把一篇明明解析好的论文误判成没有 Markdown。
|
|
42
|
+
*
|
|
43
|
+
* @param {{markdownPath?: string}} document 已 hydrate 或待 hydrate 的文档记录
|
|
44
|
+
* @returns {string}
|
|
45
|
+
*/
|
|
46
|
+
export function readerPathOf(document) {
|
|
47
|
+
const paths = documentPaths(hydrateDocument(document))
|
|
48
|
+
const markdownPath = typeof paths?.markdownPath === 'string' ? paths.markdownPath : ''
|
|
49
|
+
if (markdownPath === '') return ''
|
|
50
|
+
const stem = markdownPath.replace(/\.[^./\\]+$/, '')
|
|
51
|
+
return `${stem}${READER_SUFFIX}`
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 取字符串字段;非字符串(含 null / 数字 / undefined)一律按空串处理,不隐式转换。 */
|
|
55
|
+
function stringOf(value) {
|
|
56
|
+
return typeof value === 'string' ? value : ''
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 颜色收口到 {@link READER_COLORS} 之内;认不出的值降级到兜底色而不是让 UI 拿到 undefined。 */
|
|
60
|
+
function colorOf(value) {
|
|
61
|
+
return READER_COLORS.includes(value) ? value : DEFAULT_READER_COLOR
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 从顶层对象里取出划线数组;不是对象、`marks` 不是数组,一律当空。
|
|
66
|
+
* 读侧与写侧共用同一份口径,免得两边对"空文件"的理解分叉。
|
|
67
|
+
*/
|
|
68
|
+
function marksOf(store) {
|
|
69
|
+
return Array.isArray(store?.marks) ? store.marks : []
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** blockId → 块在文档里的下标。同一 id 出现两次时认第一个(文档顺序才是块的真实先后)。 */
|
|
73
|
+
function blockPositions(blocks) {
|
|
74
|
+
const positions = new Map()
|
|
75
|
+
const list = Array.isArray(blocks) ? blocks : []
|
|
76
|
+
list.forEach((block, position) => {
|
|
77
|
+
const id = stringOf(block?.id)
|
|
78
|
+
if (id !== '' && !positions.has(id)) positions.set(id, position)
|
|
79
|
+
})
|
|
80
|
+
return positions
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 块原文(没译出来 / 还没译时屏幕上显示的就是它)。 */
|
|
84
|
+
function sourceTextOfBlock(block) {
|
|
85
|
+
return stringOf(block?.sourceText)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 在**用户当时看到的那段文字**里定位原话,返回下标;文本里没有这句原话时返回 `-1`。
|
|
90
|
+
*
|
|
91
|
+
* 唯一命中直接用;多处命中时逐处用 prefix/suffix 校验,取第一个上下文对得上的。
|
|
92
|
+
* 都校验不上就退回第一处 —— 原话确实还在这一段里,{@link anchorInBlock} 因此仍判 exact。
|
|
93
|
+
* 🔴 这一步**不参与 stale 判定**:只因为块内重复而消歧失败就报「译文已改」是在说谎,
|
|
94
|
+
* 而且 T19 的高亮是**块级**的,块内精确到哪一处不影响用户看到的结论。
|
|
95
|
+
* prefix / suffix 为空串表示该侧不约束。
|
|
96
|
+
*/
|
|
97
|
+
function locateQuoteInText(text, quote, prefix, suffix) {
|
|
98
|
+
if (text === '' || quote === '') return -1
|
|
99
|
+
const first = text.indexOf(quote)
|
|
100
|
+
if (first < 0) return -1
|
|
101
|
+
if (text.indexOf(quote, first + 1) < 0) return first
|
|
102
|
+
for (let at = first; at >= 0; at = text.indexOf(quote, at + 1)) {
|
|
103
|
+
const before = prefix === '' || (at >= prefix.length && text.slice(at - prefix.length, at) === prefix)
|
|
104
|
+
const after = suffix === '' || text.slice(at + quote.length, at + quote.length + suffix.length) === suffix
|
|
105
|
+
if (before && after) return at
|
|
106
|
+
}
|
|
107
|
+
return first
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Unicode 上/下标字形 → ASCII。判命中时两份文字必须先折到同一形态才能比:
|
|
112
|
+
* 用户框选到的是**屏上渲染后**的字形(`atta\u2071ns`),盘上的 sourceText 是标签原串
|
|
113
|
+
* (`atta<sup>i</sup>ns`),而 D165 之后屏上真正显示的又是 `attains` —— 三方各不同。
|
|
114
|
+
* 折回是**等长**替换(一个码位换一个字符),所以折出来的下标仍能直接当屏上下标用。
|
|
115
|
+
*/
|
|
116
|
+
const SCRIPT_FOLD = Object.freeze({
|
|
117
|
+
'\u2070': '0', '\u00b9': '1', '\u00b2': '2', '\u00b3': '3', '\u2074': '4', '\u2075': '5',
|
|
118
|
+
'\u2076': '6', '\u2077': '7', '\u2078': '8', '\u2079': '9',
|
|
119
|
+
'\u207a': '+', '\u207b': '-', '\u207c': '=', '\u207d': '(', '\u207e': ')', '\u207f': 'n', '\u2071': 'i',
|
|
120
|
+
'\u2080': '0', '\u2081': '1', '\u2082': '2', '\u2083': '3', '\u2084': '4', '\u2085': '5',
|
|
121
|
+
'\u2086': '6', '\u2087': '7', '\u2088': '8', '\u2089': '9',
|
|
122
|
+
'\u208a': '+', '\u208b': '-', '\u208c': '=', '\u208d': '(', '\u208e': ')',
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
/** 上/下标折回 ASCII;长度不变,折出来的下标仍能直接当原文下标用。 */
|
|
126
|
+
function foldScript(value) {
|
|
127
|
+
return Array.from(String(value), ch => SCRIPT_FOLD[ch] ?? ch).join('')
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Markdown 反斜杠转义还原:`lives\_in` → `lives_in`(渲染之后屏上就是这个)。
|
|
132
|
+
* 只还原可打印的非字母数字:`**bold**` 这类标记里的反斜杠不在这条路上。
|
|
133
|
+
*/
|
|
134
|
+
function unescapeMarkdown(value) {
|
|
135
|
+
return String(value).replace(/\\([!-/:-@[-`{-~])/g, '$1')
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* **屏上那份文字**的近似形态:脱行内标签(与读取器渲染同口径)→ 还原 Markdown 转义
|
|
140
|
+
* → 上/下标折回 ASCII。
|
|
141
|
+
*
|
|
142
|
+
* 🔴 判定划线的基准必须是它,而不是原始 sourceText:用户是在**渲染后的正文**上划的线。
|
|
143
|
+
* 屏幕上的字与盘上的串在三处必然不同 —— 行内标签被脱壳、Markdown 转义被还原、上下标按
|
|
144
|
+
* D165 折回字母。拿原串去比,`prowess` 这种纯英文词也会被判成「译文已改」(实测:
|
|
145
|
+
* 一篇论文 13 条划线里 12 条假 stale,屏幕上一条线都画不出来)。
|
|
146
|
+
*/
|
|
147
|
+
function displayFormOf(value) {
|
|
148
|
+
return foldScript(unescapeMarkdown(plainInlineText(value)))
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** 短于这个长度的原话不用括号法判(太短,首尾随便就对上一堆)。 */
|
|
152
|
+
const BRACKET_MIN_QUOTE = 32
|
|
153
|
+
/** 首尾两截各自至少要这么长。 */
|
|
154
|
+
const BRACKET_MIN_SIDE = 8
|
|
155
|
+
/** 首尾两截合起来至少要盖住原话的这个比例。 */
|
|
156
|
+
const BRACKET_MIN_COVERAGE = 0.6
|
|
157
|
+
|
|
158
|
+
/** quote 的最长前缀中真的出现在 text 里的那一段;一段都配不上返回空串。 */
|
|
159
|
+
function quoteHeadInText(quote, text) {
|
|
160
|
+
for (let keep = quote.length; keep > 0; keep -= 1) {
|
|
161
|
+
const head = quote.slice(0, keep)
|
|
162
|
+
if (text.indexOf(head) >= 0) return head
|
|
163
|
+
}
|
|
164
|
+
return ''
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** quote 的最长后缀中真的出现在 text 里的那一段;一段都配不上返回空串。 */
|
|
168
|
+
function quoteTailInText(quote, text) {
|
|
169
|
+
for (let keep = quote.length; keep > 0; keep -= 1) {
|
|
170
|
+
const tail = quote.slice(quote.length - keep)
|
|
171
|
+
if (text.indexOf(tail) >= 0) return tail
|
|
172
|
+
}
|
|
173
|
+
return ''
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* 括号法:原话的**首尾两截**都在 text 里、合起来盖住原话的大部分,就判命中。
|
|
178
|
+
*
|
|
179
|
+
* 🔴 为什么必须有它:公式段在屏上是 KaTeX 渲染出来的,MathML 臂与 HTML 臂**都会留在**
|
|
180
|
+
* textContent 里,用户框选到的是这两臂拼起来的串,而盘上只有 LaTeX 源码。逐字比对
|
|
181
|
+
* 永远对不上,但句子首尾那两截大白话两边都有 —— 用它们夹出区间即可。
|
|
182
|
+
*
|
|
183
|
+
* 缺口必须**长得像渲染噪声**(含数学/标记字符):否则就是在把两个被换掉的词硬桥过去,
|
|
184
|
+
* 那正是「已改」的意思,不能算命中。
|
|
185
|
+
*/
|
|
186
|
+
function bracketSpan(text, quote) {
|
|
187
|
+
if (text === '' || quote.length < BRACKET_MIN_QUOTE) return null
|
|
188
|
+
const head = quoteHeadInText(quote, text)
|
|
189
|
+
const tail = quoteTailInText(quote, text)
|
|
190
|
+
if (head.length < BRACKET_MIN_SIDE || tail.length < BRACKET_MIN_SIDE) return null
|
|
191
|
+
if (head.length + tail.length < Math.ceil(quote.length * BRACKET_MIN_COVERAGE)) return null
|
|
192
|
+
const start = text.indexOf(head)
|
|
193
|
+
const end = text.lastIndexOf(tail) + tail.length
|
|
194
|
+
if (end <= start) return null
|
|
195
|
+
const gap = text.slice(start + head.length, end - tail.length)
|
|
196
|
+
if (gap.trim() !== '' && /[$\\{}^_]/.test(gap) === false) return null
|
|
197
|
+
return { start, end, head, tail }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* 在块的**原文**里定位原话,返回下标;定位不到返回 `-1`。
|
|
202
|
+
*
|
|
203
|
+
* 🔴 只认 `sourceText`,不回退译文:返回的 offset 是**原文坐标**,译文里的下标对原文没有意义。
|
|
204
|
+
* 顺带这也是「重译不散」的来源 —— 重译只换 zh,原文坐标纹丝不动。
|
|
205
|
+
* 要不要把译文也算作命中,是 {@link anchorInBlock} 的事。
|
|
206
|
+
*/
|
|
207
|
+
function locateInBlock(block, quote, prefix, suffix) {
|
|
208
|
+
return locateQuoteInText(sourceTextOfBlock(block), quote, prefix, suffix)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* 块存在时这条划线落在哪一档,恰好一个:
|
|
213
|
+
*
|
|
214
|
+
* - `'exact'` —— 原话**能在用户当时看到的那段文字里**定位到;
|
|
215
|
+
* - `'stale'` —— 屏幕上那份文字里找不到它,原文或译文被改过了。调用方**照样返回条目**,
|
|
216
|
+
* 绝不吞掉用户的划线。
|
|
217
|
+
*
|
|
218
|
+
* (第三档 `'orphan'` 是"块本身不在了",在 {@link resolveMarks} 里判 —— 它要先查 id 表。)
|
|
219
|
+
*
|
|
220
|
+
* 🔴 **判据的关键是「用户看到的那份文字」**。这是四步,每一步都换基准、不换口径:
|
|
221
|
+
* 1. 原始 sourceText —— 老路径,一字不改地留着(「重译不散」靠它);
|
|
222
|
+
* 2. **屏上那份原文**({@link displayFormOf})—— 脱行内标签、还原 Markdown 转义、
|
|
223
|
+
* 上下标折回字母。用户是在渲染后的正文上划的线,拿原串比会把 `prowess` 判成已改;
|
|
224
|
+
* 3. 译文(有译文时屏幕上显示的就是它)—— 模型换个词不该让划线变「已改」;
|
|
225
|
+
* 4. {@link bracketSpan} 括号法 —— 公式段在屏上是 KaTeX 两条渲染臂拼出来的串,
|
|
226
|
+
* 逐字永远对不上,但句子首尾两截大白话两边都有。
|
|
227
|
+
*/
|
|
228
|
+
function anchorInBlock(block, quote, prefix, suffix) {
|
|
229
|
+
const source = sourceTextOfBlock(block)
|
|
230
|
+
if (locateQuoteInText(source, quote, prefix, suffix) >= 0) return 'exact'
|
|
231
|
+
const shown = displayFormOf(source)
|
|
232
|
+
const foldedQuote = displayFormOf(quote)
|
|
233
|
+
const foldedPrefix = displayFormOf(prefix)
|
|
234
|
+
const foldedSuffix = displayFormOf(suffix)
|
|
235
|
+
if (locateQuoteInText(shown, foldedQuote, foldedPrefix, foldedSuffix) >= 0) return 'exact'
|
|
236
|
+
const zh = displayTextOf(block)
|
|
237
|
+
if (zh !== source && locateQuoteInText(displayFormOf(zh), foldedQuote, foldedPrefix, foldedSuffix) >= 0) return 'exact'
|
|
238
|
+
if (bracketSpan(shown, foldedQuote) !== null) return 'exact'
|
|
239
|
+
return zh !== source && bracketSpan(displayFormOf(zh), foldedQuote) !== null ? 'exact' : 'stale'
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** 块在屏幕上显示的那段文字:有译文就是译文,没有就退回原文。 */
|
|
243
|
+
function displayTextOf(block) {
|
|
244
|
+
const zh = stringOf(block?.zh)
|
|
245
|
+
return zh !== '' ? zh : sourceTextOfBlock(block)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** 解析划线文件的文本。读侧与写侧共用同一份"能不能解析",判据只写一遍。 */
|
|
249
|
+
function parseStoreText(text, path) {
|
|
250
|
+
let raw
|
|
251
|
+
try {
|
|
252
|
+
raw = JSON.parse(text)
|
|
253
|
+
} catch (error) {
|
|
254
|
+
throw new Error(`划线文件不是合法 JSON:${path}`, { cause: error })
|
|
255
|
+
}
|
|
256
|
+
if (!isPlainObject(raw)) throw new Error(`划线文件的顶层不是对象:${path}`)
|
|
257
|
+
return raw
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* 写侧的形状判定:读不懂的数据绝不能被覆盖。
|
|
262
|
+
*
|
|
263
|
+
* `marks` 缺失是合法的(空文件写过一次就是这样);给了但不是数组、或 schemaVersion 不是本插件
|
|
264
|
+
* 认得的那个,一律拒绝 —— 那是更新版本的插件或别的程序写的,写回去就是拿旧结构盖新结构。
|
|
265
|
+
*/
|
|
266
|
+
function assertWritableShape(raw, path) {
|
|
267
|
+
if (!isPlainObject(raw)) throw new Error(`划线文件的顶层不是对象,已停止写入以保留原数据:${path}`)
|
|
268
|
+
if (raw.marks !== undefined && !Array.isArray(raw.marks)) {
|
|
269
|
+
throw new Error(`划线文件的 marks 不是数组,已停止写入以保留原数据:${path}`)
|
|
270
|
+
}
|
|
271
|
+
if (raw.schemaVersion !== undefined && raw.schemaVersion !== READER_SCHEMA_VERSION) {
|
|
272
|
+
throw new Error(`划线文件的 schemaVersion 不是当前版本(${raw.schemaVersion} ≠ ${READER_SCHEMA_VERSION}),已停止写入以保留原数据:${path}`)
|
|
273
|
+
}
|
|
274
|
+
return raw
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* 读划线文件。文件不存在(ENOENT)、不是 JSON、顶层不是对象(含顶层是数组),一律返回 null
|
|
279
|
+
* —— 与 `readTranslation` 同口径:调用方按"还没有划线"处理,一次坏读不该让整篇的笔记都取不到,
|
|
280
|
+
* 更不该抛错。
|
|
281
|
+
*
|
|
282
|
+
* 返回的是**文件里的原样对象**;字段校验交给 {@link resolveMarks}(它容忍缺失与多余字段)。
|
|
283
|
+
*
|
|
284
|
+
* 🔴 **这条只给展示用。** 要基于文件内容改写的调用方必须用 {@link readReaderStoreForWrite}:
|
|
285
|
+
* 这里把"坏了"和"还没有"都折成 null,拿它去算下一份内容就是把原文件抹成一条。
|
|
286
|
+
*
|
|
287
|
+
* @param {string} path
|
|
288
|
+
* @returns {Promise<object|null>}
|
|
289
|
+
*/
|
|
290
|
+
export async function readReaderStore(path) {
|
|
291
|
+
let text
|
|
292
|
+
try {
|
|
293
|
+
text = await readFile(path, 'utf8')
|
|
294
|
+
} catch {
|
|
295
|
+
return null
|
|
296
|
+
}
|
|
297
|
+
if (text.trim() === '') return null
|
|
298
|
+
try {
|
|
299
|
+
return parseStoreText(text, path)
|
|
300
|
+
} catch {
|
|
301
|
+
return null
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* 划线文件的**写入侧**读法:三态,而不是"null 或对象"两态。
|
|
307
|
+
*
|
|
308
|
+
* 🔴 与 {@link readReaderStore} 的差别只有一个,但那一个正是丢数据的入口:展示用的读取把
|
|
309
|
+
* "文件读不出来"降级成"还没有划线",写入路径如果沿用这个降级结果,一次坏读就会把用户原有的
|
|
310
|
+
* 划线全部换掉(实测:损坏的划线文件上新增一条,文件里只剩新那条,HTTP 仍返回 200)。
|
|
311
|
+
*
|
|
312
|
+
* - 不存在 / 空文件 → `null`:可以创建;
|
|
313
|
+
* - 读得懂 → 文件里的原样对象;
|
|
314
|
+
* - 读不懂 → 抛错,由调用方折算成一次明确的失败。
|
|
315
|
+
*
|
|
316
|
+
* @param {string} path
|
|
317
|
+
* @returns {Promise<object|null>}
|
|
318
|
+
*/
|
|
319
|
+
export async function readReaderStoreForWrite(path) {
|
|
320
|
+
let text
|
|
321
|
+
try {
|
|
322
|
+
text = await readFile(path, 'utf8')
|
|
323
|
+
} catch (error) {
|
|
324
|
+
if (error?.code === 'ENOENT') return null
|
|
325
|
+
throw new Error('划线文件无法读取,已停止写入以保留原数据。', { cause: error })
|
|
326
|
+
}
|
|
327
|
+
if (text.trim() === '') return null
|
|
328
|
+
return assertWritableShape(parseStoreText(text, path), path)
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* 原子写划线文件:临时文件 + {@link replaceStateFile}(已处理 Windows 上 rename 被占用句柄的
|
|
333
|
+
* 退避重试)。临时名带 pid 与时间戳,并发写不会互相覆盖。
|
|
334
|
+
*
|
|
335
|
+
* 🔴 替换失败时**先删掉临时文件再抛** —— 留下半截 `.tmp` 会在用户的 analysis/ 里越积越多;
|
|
336
|
+
* 此时目标文件仍是上一次的完整内容,没有被改坏。
|
|
337
|
+
*
|
|
338
|
+
* @param {string} path
|
|
339
|
+
* @param {object} store 顶层对象(只取 `marks`;不是对象或 marks 不是数组时按空写)
|
|
340
|
+
* @param {{replace?: (temporary: string, path: string) => Promise<void>}} [options] 替换实现,测试注入用
|
|
341
|
+
* @returns {Promise<{schemaVersion: number, marks: object[]}>} 实际落盘的内容
|
|
342
|
+
*/
|
|
343
|
+
/** 见 library.js 的 temporarySequence:同毫秒并发的写必须有**独占的**临时名,否则 rename ENOENT。 */
|
|
344
|
+
let readerTemporarySequence = 0
|
|
345
|
+
|
|
346
|
+
export async function writeReaderStore(path, store, options = {}) {
|
|
347
|
+
const replace = typeof options?.replace === 'function' ? options.replace : replaceStateFile
|
|
348
|
+
// 责任放在写侧,而不是指望每个调用方都记得先严格读一次:这里再把关一次,
|
|
349
|
+
// 任何一条漏掉的写入路径都不会把读完不出来的文件换成空内容。
|
|
350
|
+
await assertReplaceableFile(path, { label: '划线文件', accept: raw => assertWritableShape(raw, path) })
|
|
351
|
+
const body = { schemaVersion: READER_SCHEMA_VERSION, marks: marksOf(store) }
|
|
352
|
+
await mkdir(dirname(path), { recursive: true })
|
|
353
|
+
// 序号见 library.js 的 temporarySequence:只用 pid + 毫秒会让同毫秒的并发写撞名 → rename ENOENT。
|
|
354
|
+
readerTemporarySequence += 1
|
|
355
|
+
const temporary = `${path}.${process.pid}.${Date.now()}.${readerTemporarySequence}.tmp`
|
|
356
|
+
await writeFile(temporary, JSON.stringify(body, null, 2), 'utf8')
|
|
357
|
+
try {
|
|
358
|
+
await replace(temporary, path)
|
|
359
|
+
} catch (error) {
|
|
360
|
+
await rm(temporary, { force: true })
|
|
361
|
+
throw error
|
|
362
|
+
}
|
|
363
|
+
return body
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* 造一条划线/笔记。id 与 createdAt 由这里给 —— 手写这两个字段迟早会漏一个。
|
|
368
|
+
*
|
|
369
|
+
* 不做校验、不抛错:本模块对坏数据的口径一贯是"降级读"(见 {@link resolveMarks}),
|
|
370
|
+
* 写侧塞进来什么就存什么。
|
|
371
|
+
*
|
|
372
|
+
* `gloss` 是**选区即时释义**在划线那一刻留下的那一行译文(D160,用户裁定「划线后译文要留在
|
|
373
|
+
* 段落旁边」)。它与 note 同路:随划线落盘、随划线导出、随论文删除一起消失。空串表示这条划线
|
|
374
|
+
* 没有释义(老文件、或用户没等它译出来就划了)。
|
|
375
|
+
*
|
|
376
|
+
* @param {{blockId?: unknown, quote?: unknown, prefix?: unknown, suffix?: unknown, color?: unknown, note?: unknown, gloss?: unknown}} input
|
|
377
|
+
* @returns {{id: string, blockId: string, quote: string, prefix: string, suffix: string, color: string, note: string, gloss: string, createdAt: string}}
|
|
378
|
+
*/
|
|
379
|
+
export function makeMark(input = {}) {
|
|
380
|
+
return {
|
|
381
|
+
id: randomUUID(),
|
|
382
|
+
blockId: stringOf(input?.blockId),
|
|
383
|
+
quote: stringOf(input?.quote),
|
|
384
|
+
prefix: stringOf(input?.prefix),
|
|
385
|
+
suffix: stringOf(input?.suffix),
|
|
386
|
+
color: colorOf(input?.color),
|
|
387
|
+
note: stringOf(input?.note),
|
|
388
|
+
gloss: stringOf(input?.gloss),
|
|
389
|
+
...(stringOf(input?.parallelQuote) ? {parallelQuote:stringOf(input.parallelQuote)} : {}),
|
|
390
|
+
...(['source','translation'].includes(input?.sourceLanguage) ? {sourceLanguage:input.sourceLanguage} : {}),
|
|
391
|
+
...(Number.isSafeInteger(input.pdfPage) && input.pdfPage > 0 ? { pdfPage: input.pdfPage } : {}),
|
|
392
|
+
// 一次跨块拖选落成的一组划线共用这个 id(D46)。**组只是标记,不是结构**:
|
|
393
|
+
// 每条仍然是一个完整的划线条目,锚点/定位/高亮全都只看自己那一条。
|
|
394
|
+
...(stringOf(input?.groupId) ? { groupId: stringOf(input.groupId) } : {}),
|
|
395
|
+
createdAt: new Date().toISOString(),
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** 阅读顺序:先按块在文档里的先后,块内再按下标,最后按落盘顺序。不减法 —— 有序里带 Infinity。 */
|
|
400
|
+
function compareOrder(a, b) {
|
|
401
|
+
if (a.position !== b.position) return a.position < b.position ? -1 : 1
|
|
402
|
+
if (a.offset !== b.offset) return a.offset < b.offset ? -1 : 1
|
|
403
|
+
return a.stored - b.stored
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* 把存好的划线与**当前**块列表对起来。
|
|
408
|
+
*
|
|
409
|
+
* 纯函数:不碰磁盘、不改入参、不看时钟。每条返回都带解析结果:
|
|
410
|
+
* - `anchor` —— `'exact'`(块还在且原话还在,见 {@link locateMark})/ `'stale'`(块还在但
|
|
411
|
+
* 原话已改)/ `'orphan'`(blockId 不在传入的块集合里)。后两档**照样返回条目**,绝不吞掉
|
|
412
|
+
* 用户的划线;
|
|
413
|
+
* - `stale` / `orphan` —— 上一条的两个布尔投影,给不方便比字符串的调用方(UI 与断言);
|
|
414
|
+
* - `offset` —— quote 在块**原文**里的下标;原文里定位不到时为 `-1`(译文命中、stale、orphan
|
|
415
|
+
* 都是 -1,宁可说"对不上"也不给一个指向别处的错误位置)。
|
|
416
|
+
*
|
|
417
|
+
* 排序是阅读顺序:先按块在文档里的先后,块内按原文下标;同块内定位不到的排在定位得到的之后,
|
|
418
|
+
* 位置完全相同的按落盘顺序(排序稳定)。
|
|
419
|
+
*
|
|
420
|
+
* 容错:顶层不是对象、`marks` 不是数组、条目不是对象,一律按"没有这条"处理;缺字段、多余字段、
|
|
421
|
+
* 字段类型不对,全部降级到默认值而不是抛错 —— 坏一条不该让整篇的笔记都读不出来。
|
|
422
|
+
*
|
|
423
|
+
* @param {unknown} store {@link readReaderStore} 的产物
|
|
424
|
+
* @param {unknown} blocks 当前块列表(blocks.js 的产物)
|
|
425
|
+
* @returns {Array<object>} 每条划线/笔记 + `anchor` / `offset` / `stale` / `orphan`
|
|
426
|
+
*/
|
|
427
|
+
export function resolveMarks(store, blocks) {
|
|
428
|
+
const blockList = Array.isArray(blocks) ? blocks : []
|
|
429
|
+
const positions = blockPositions(blockList)
|
|
430
|
+
const entries = []
|
|
431
|
+
marksOf(store).forEach((mark, stored) => {
|
|
432
|
+
if (mark === null || typeof mark !== 'object' || Array.isArray(mark)) return
|
|
433
|
+
const blockId = stringOf(mark.blockId)
|
|
434
|
+
const quote = stringOf(mark.quote)
|
|
435
|
+
const prefix = stringOf(mark.prefix)
|
|
436
|
+
const suffix = stringOf(mark.suffix)
|
|
437
|
+
const position = positions.get(blockId)
|
|
438
|
+
const orphan = position === undefined
|
|
439
|
+
const pdfPage = Number.isSafeInteger(mark.pdfPage) && mark.pdfPage > 0 ? mark.pdfPage : null
|
|
440
|
+
const anchor = orphan ? 'orphan' : pdfPage !== null && blockList[position].page === pdfPage ? 'exact' : anchorInBlock(blockList[position], quote, prefix, suffix)
|
|
441
|
+
// 原文里的下标:原文命中就是它,命中不了(译文命中 / stale / orphan)一律 -1 ——
|
|
442
|
+
// 让 UI 拿到一个"对不上原文"的 -1,而不是一个指向别处的错误位置。
|
|
443
|
+
const offset = anchor === 'exact' ? locateInBlock(blockList[position], quote, prefix, suffix) : -1
|
|
444
|
+
entries.push({
|
|
445
|
+
position: orphan ? Number.POSITIVE_INFINITY : position,
|
|
446
|
+
offset: offset < 0 ? Number.POSITIVE_INFINITY : offset,
|
|
447
|
+
stored,
|
|
448
|
+
entry: {
|
|
449
|
+
id: stringOf(mark.id),
|
|
450
|
+
blockId,
|
|
451
|
+
quote,
|
|
452
|
+
prefix,
|
|
453
|
+
suffix,
|
|
454
|
+
color: colorOf(mark.color),
|
|
455
|
+
note: stringOf(mark.note),
|
|
456
|
+
// 老文件没有这个字段 → 空串,面板与导出据此整行不出现(不是"显示一个空的行")。
|
|
457
|
+
gloss: stringOf(mark.gloss),
|
|
458
|
+
...(stringOf(mark.parallelQuote) ? {parallelQuote:stringOf(mark.parallelQuote)} : {}),
|
|
459
|
+
...(['source','translation'].includes(mark.sourceLanguage) ? {sourceLanguage:mark.sourceLanguage} : {}),
|
|
460
|
+
...(pdfPage !== null ? { pdfPage } : {}),
|
|
461
|
+
// 跨块选区分组(D46):老文件没有这个字段,下游据此按单条处理。
|
|
462
|
+
...(stringOf(mark.groupId) ? { groupId: stringOf(mark.groupId) } : {}),
|
|
463
|
+
createdAt: stringOf(mark.createdAt),
|
|
464
|
+
offset,
|
|
465
|
+
anchor,
|
|
466
|
+
stale: anchor === 'stale',
|
|
467
|
+
orphan,
|
|
468
|
+
},
|
|
469
|
+
})
|
|
470
|
+
})
|
|
471
|
+
entries.sort(compareOrder)
|
|
472
|
+
return entries.map(item => item.entry)
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* 把解析结果摊成「笔记面板」要的线性列表:按**原文顺序**排列。
|
|
477
|
+
*
|
|
478
|
+
* 返回的就是 {@link resolveMarks} 的那些条目对象本身,只是换了顺序 —— 面板不必自己再排一次。
|
|
479
|
+
* **不做过滤**:只划了线、没写笔记的条目同样是读者标过的位置,面板要能列出来。
|
|
480
|
+
* 孤儿与 `stale` 条目(块内位置对不上)没有原文下标,统一排在各自块的最后。
|
|
481
|
+
*
|
|
482
|
+
* @param {unknown} resolved {@link resolveMarks} 的产物
|
|
483
|
+
* @param {unknown} blocks 当前块列表
|
|
484
|
+
* @returns {Array<object>} 同样这些条目,按原文顺序
|
|
485
|
+
*/
|
|
486
|
+
export function summarizeNotes(resolved, blocks) {
|
|
487
|
+
const positions = blockPositions(blocks)
|
|
488
|
+
const list = Array.isArray(resolved) ? resolved : []
|
|
489
|
+
return list
|
|
490
|
+
.map((mark, stored) => {
|
|
491
|
+
const position = positions.get(stringOf(mark?.blockId))
|
|
492
|
+
const offset = Number.isInteger(mark?.offset) && mark.offset >= 0 ? mark.offset : Number.POSITIVE_INFINITY
|
|
493
|
+
return { position: position === undefined ? Number.POSITIVE_INFINITY : position, offset, stored, mark }
|
|
494
|
+
})
|
|
495
|
+
.sort(compareOrder)
|
|
496
|
+
.map(item => item.mark)
|
|
497
|
+
}
|