@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,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 从**已有的事实**里补齐引用的 authors / year。
|
|
3
|
+
*
|
|
4
|
+
* 🔴 为什么需要它(实测数据,73 篇真实库):`state.json` 里 authors 有 47 条、year 只有 5 条。
|
|
5
|
+
* 于是 68 篇的引用全是 `n.d.`、26 篇连 `author` 字段都不出现 —— 生成不出一份可用的参考文献表。
|
|
6
|
+
* 而**渲染器本身没问题**(拿一篇 authors+year 齐全的论文试,bibtex / APA / GB-T 都正确),
|
|
7
|
+
* 所以这不是 export.js 的 bug,是**元数据覆盖率**的问题。
|
|
8
|
+
*
|
|
9
|
+
* 三个来源都是现成事实,不需要联网、不需要调模型:
|
|
10
|
+
* 1. 记录自己身上的 `authors` / `year`(有就直接用,本模块不覆盖已填值);
|
|
11
|
+
* 2. **文件名**:入库时按 `作者 - 年份 - 标题` 命名,磁盘上 73/73 都带 ` - YYYY - `;
|
|
12
|
+
* 3. 正文首个 heading(有的论文 Info dict 全空,标题只在正文里)。
|
|
13
|
+
*
|
|
14
|
+
* ⚠️ 这里**只补空字段**,绝不改写已经有的值 —— 记录上的值来自出版方元数据,比文件名准。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { readFile, readdir } from 'node:fs/promises'
|
|
18
|
+
|
|
19
|
+
import { authorsFromBlockList, titleFromBlockList } from './block-authors.js'
|
|
20
|
+
import { plainInlineText } from './inline-html.js'
|
|
21
|
+
import { splitAuthors, yearSegment } from './rename.js'
|
|
22
|
+
|
|
23
|
+
/** 文件名里的 `—— 年份` 分隔段:`作者 - 2024 - 标题`。 */
|
|
24
|
+
const YEAR_SEGMENT = /\s-\s((?:19|20)\d{2})\s-\s/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 段尾的 `et al.` / `等`。
|
|
28
|
+
*
|
|
29
|
+
* 🔴 它**既是噪声也是信息**,两头都不能丢:
|
|
30
|
+
* - 当名字的一部分是错的:`author = {Prateek Chhikara et al.}` 把「还有别人」
|
|
31
|
+
* 当成了一个人的姓,必须剥掉;
|
|
32
|
+
* - 但它同时是**「这篇不止一位作者」的唯一证据**。只剥不留标记,引用就会断言
|
|
33
|
+
* 这是一篇单作者论文 —— 实测 29 篇被这么写成单作者,而其中 22 篇正文是多人署名
|
|
34
|
+
* (Mem0 正文 5 人、LoCoMo 9 人)。**错作者比没作者更糟**:写进综述就是错引。
|
|
35
|
+
*
|
|
36
|
+
* 所以剥掉名字、**留下一个 etal 标记**,交给渲染器决定怎么表达
|
|
37
|
+
* (GB/T 7714 写「首位, 等」、APA 写「首位, et al.」、bibtex 写 `and others`)。
|
|
38
|
+
*/
|
|
39
|
+
const TRAILING_ET_AL = /[\s,;]*\bet\s+al\.?\s*$|[\s,;]*等\s*$/i
|
|
40
|
+
|
|
41
|
+
/** 一个作者名段:去掉段尾的 et al. 与首尾空白。 */
|
|
42
|
+
function cleanAuthorName(value) {
|
|
43
|
+
return String(value ?? '').replace(TRAILING_ET_AL, '').trim()
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 名字段里有没有 et al. 的样子(剥之前判)。 */
|
|
47
|
+
function hasEtAl(value) {
|
|
48
|
+
return TRAILING_ET_AL.test(String(value ?? ''))
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 把 `作者 - 年份 - 标题` 拆开。缺哪段就返回空,**不猜**。
|
|
53
|
+
*
|
|
54
|
+
* 年份是唯一可靠的分界:没有 ` - YYYY - ` 就整段放弃(返回 null),
|
|
55
|
+
* 而不是把 "LONGMEMEVAL - BENCHMARKING…" 的第一段当作者 —— 那是标题的一部分。
|
|
56
|
+
*
|
|
57
|
+
* @param {unknown} pdfName 文件名或主名(可带 .pdf)
|
|
58
|
+
* @returns {{authors: string[], year: string}|null}
|
|
59
|
+
*/
|
|
60
|
+
export function metadataFromFileName(pdfName) {
|
|
61
|
+
const name = String(pdfName ?? '').replace(/\.pdf$/i, '').trim()
|
|
62
|
+
if (name === '') return null
|
|
63
|
+
const match = name.match(YEAR_SEGMENT)
|
|
64
|
+
if (match === null) return null
|
|
65
|
+
const year = match[1]
|
|
66
|
+
const head = name.slice(0, match.index ?? 0).trim()
|
|
67
|
+
// `作者` 段可能是 `Prateek Chhikara et al.`(3 位以上作者的写法):
|
|
68
|
+
// 剥掉尾部的 et al. 得到首作者,同时记住「还有别人」。
|
|
69
|
+
const authors = head === '' ? [] : splitAuthors(head).map(cleanAuthorName).filter(name => name !== '')
|
|
70
|
+
return { authors, year, etal: head !== '' && hasEtAl(head) }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 合成引用的元数据:**已填的优先,缺的才补**。
|
|
75
|
+
*
|
|
76
|
+
* @param {{authors?: unknown, year?: unknown, pdfName?: unknown, title?: unknown}} record
|
|
77
|
+
* @param {{headingAuthors?: unknown, headingYear?: unknown}} [extra] 正文首块里的线索(可选)
|
|
78
|
+
* @returns {{authors: string[], year: string, filledAuthors: boolean, filledYear: boolean}}
|
|
79
|
+
*/
|
|
80
|
+
export function citationMetadata(record = {}, extra = {}) {
|
|
81
|
+
const cleared = new Set(Array.isArray(record?.clearedMetadata) ? record.clearedMetadata : [])
|
|
82
|
+
const recorded = splitAuthors(record?.authors)
|
|
83
|
+
const hasAuthors = recorded.length > 0
|
|
84
|
+
const recordedYear = yearSegment(record?.year)
|
|
85
|
+
const hasYear = recordedYear !== ''
|
|
86
|
+
|
|
87
|
+
let authors = recorded
|
|
88
|
+
let year = recordedYear
|
|
89
|
+
// 记录自己有 ≥3 位作者时,渲染器已按「首位, 等」处理,不需要额外标记。
|
|
90
|
+
let etal = false
|
|
91
|
+
|
|
92
|
+
// ① 文件名:库里绝大多数记录只有它可用。
|
|
93
|
+
if (!hasAuthors || !hasYear) {
|
|
94
|
+
const fromName = metadataFromFileName(record?.pdfName)
|
|
95
|
+
if (fromName !== null) {
|
|
96
|
+
if (!hasAuthors && fromName.authors.length > 0) {
|
|
97
|
+
authors = fromName.authors
|
|
98
|
+
// 🔴 只有**从文件名补出来的**才需要 etal 标记:记录里那 47 条真实作者
|
|
99
|
+
// 是完整名单(3 位以上渲染器自己会加「等」),不该被文件名压成一位。
|
|
100
|
+
etal = fromName.etal
|
|
101
|
+
}
|
|
102
|
+
if (!hasYear) year = fromName.year
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ② 正文里给的线索(调用方从首个 heading / 首块里取,仍只在缺的时候补)。
|
|
107
|
+
if (authors.length === 0) {
|
|
108
|
+
const fromHeading = splitAuthors(extra?.headingAuthors)
|
|
109
|
+
if (fromHeading.length > 0) authors = fromHeading
|
|
110
|
+
}
|
|
111
|
+
if (year === '') {
|
|
112
|
+
const fromHeading = yearSegment(extra?.headingYear)
|
|
113
|
+
if (fromHeading !== '') year = fromHeading
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return {
|
|
117
|
+
authors: cleared.has('authors') ? [] : authors,
|
|
118
|
+
year: cleared.has('year') ? '' : year,
|
|
119
|
+
// 「还有更多作者,名单没拿到」:渲染器据此写「等 / et al. / and others」。
|
|
120
|
+
// 与 authors.length >= 3 是两条独立的信号:这里是**名单不完整**,那里是**名单完整但太长**。
|
|
121
|
+
etal: !cleared.has('authors') && etal,
|
|
122
|
+
// 调用方据此知道哪些是补出来的(用于 notice / 诊断,不改变引用本身)。
|
|
123
|
+
filledAuthors: !cleared.has('authors') && !hasAuthors && authors.length > 0,
|
|
124
|
+
filledYear: !cleared.has('year') && !hasYear && year !== '',
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* 从块列表(`<主名>.content.json`)里取标题与作者。
|
|
130
|
+
*
|
|
131
|
+
* 🔴 这一层解决的是**「标题就是文件名」**那 14 条:它们从来没拿到过真标题,
|
|
132
|
+
* 一直拿 `pdfName` 兜底,于是引用里出现
|
|
133
|
+
* `Mofasshara Rafique, Laurent Bindschaedler. Mofasshara Rafique, Laurent Bindschaedlers - 2026 - ClawVM- ….pdf. 2026.`
|
|
134
|
+
* —— 标题重复一遍文件名、还带 `.pdf`。
|
|
135
|
+
*
|
|
136
|
+
* 为什么不能复用 `titleFromBlocks`(translate-prompts.js):它只认 `type === 'heading'` 的块,
|
|
137
|
+
* 而**这个库 73/73 篇一个 heading 都没有**(块类型只有 text / ref_text / table / equation …)。
|
|
138
|
+
* 所以这里按**位置**取:块列表里第 1 个 text 是标题、作者行紧随其后(见 block-authors.js)。
|
|
139
|
+
*
|
|
140
|
+
* 读不到块列表(老产物、MinerU 降级)就返回空 —— 调用方保留原值,绝不拿文件名冒充标题。
|
|
141
|
+
*
|
|
142
|
+
* @param {string} contentPath 块列表文件(`<主名>.content.json`)
|
|
143
|
+
* @returns {Promise<{title: string, authors: string[], etal: boolean}>}
|
|
144
|
+
*/
|
|
145
|
+
export async function metadataFromBlocks(contentPath) {
|
|
146
|
+
const path = typeof contentPath === 'string' ? contentPath.trim() : ''
|
|
147
|
+
if (path === '') return { title: '', authors: [], etal: false }
|
|
148
|
+
let blocks
|
|
149
|
+
try {
|
|
150
|
+
blocks = JSON.parse(await readFile(path, 'utf8'))
|
|
151
|
+
} catch {
|
|
152
|
+
return { title: '', authors: [], etal: false }
|
|
153
|
+
}
|
|
154
|
+
if (!Array.isArray(blocks)) return { title: '', authors: [], etal: false }
|
|
155
|
+
const title = titleFromBlockList(blocks, plainInlineText)
|
|
156
|
+
const authored = authorsFromBlockList(blocks, plainInlineText)
|
|
157
|
+
return { title, authors: authored.authors, etal: authored.etal }
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* 一条文献记录 → 引用元数据。**所有读取路径共用这一个函数**。
|
|
162
|
+
*
|
|
163
|
+
* 🔴 为什么要收成一处(实测):`Paper_library citation` 在工具侧拼输入,`Paper_library get`
|
|
164
|
+
* 直接读记录 —— 同一条 Mem0,citation 拿到 5 位作者,get 只有首位并标「等」。
|
|
165
|
+
* 差的不是数据,是两条路径各自拼了一遍输入。收成一个函数后**结构上不可能再漂**。
|
|
166
|
+
*
|
|
167
|
+
* 优先级(高 → 低),只补空字段、绝不覆盖已有值:
|
|
168
|
+
* ① 记录自己的值(来自出版方元数据,最准);
|
|
169
|
+
* ② 块列表里的作者行(实测块 0 是标题、块 1 是完整作者行);
|
|
170
|
+
* ③ 文件名 / `sourceDir` 里的磁盘规范名(只到「首作者 + et al.」的粒度)。
|
|
171
|
+
*
|
|
172
|
+
* ②必须在③之前:文件名只能给出首作者,块列表里有完整名单。
|
|
173
|
+
*
|
|
174
|
+
* @param {object} record 文献记录(authors / year / pdfName / sourceDir)。
|
|
175
|
+
* @param {string} contentPath 块列表路径;没有就传空串。
|
|
176
|
+
* @returns {Promise<object>} {@link citationMetadataWithDisk} 的产物,外加 `fromBlocks`,
|
|
177
|
+
* 以及**相对记录**算的 `filledAuthors` / `filledYear`(调用方据此说「这是补出来的」)。
|
|
178
|
+
*/
|
|
179
|
+
export async function citationMetadataOfRecord(record, contentPath) {
|
|
180
|
+
const fromBlocks = await metadataFromBlocks(contentPath)
|
|
181
|
+
const recordedAuthors = Array.isArray(record?.authors) && record.authors.length > 0
|
|
182
|
+
const recordedYear = yearSegment(record?.year) !== ''
|
|
183
|
+
const blockAuthors = fromBlocks.authors
|
|
184
|
+
const nameAuthors = metadataFromFileName(record?.pdfName)?.authors ?? []
|
|
185
|
+
// 🔴 块列表**承认自己没拿全**(etal)而文件名给了更长的名单时,用文件名的。
|
|
186
|
+
// 实测 ClawVM:两位作者分处两个文本块,块解析只拿到首位并标了 etal,而文件名
|
|
187
|
+
// (来自出版方元数据)有完整两位 —— 此时优先块列表会把两人论文写成一人。
|
|
188
|
+
// 只在这一种形状下换源:文件名名单更长,且块列表自己说了不完整。
|
|
189
|
+
const preferFileName = blockAuthors.length > 0 && fromBlocks.etal === true && nameAuthors.length > blockAuthors.length
|
|
190
|
+
const useBlockAuthors = !recordedAuthors && !preferFileName && blockAuthors.length > 0
|
|
191
|
+
const citation = await citationMetadataWithDisk({
|
|
192
|
+
authors: recordedAuthors
|
|
193
|
+
? record.authors
|
|
194
|
+
: (useBlockAuthors ? blockAuthors : undefined),
|
|
195
|
+
year: record?.year,
|
|
196
|
+
pdfName: record?.pdfName,
|
|
197
|
+
sourceDir: record?.sourceDir,
|
|
198
|
+
sourcePdfPath: record?.sourcePdfPath,
|
|
199
|
+
clearedMetadata: record?.clearedMetadata,
|
|
200
|
+
})
|
|
201
|
+
return {
|
|
202
|
+
...citation,
|
|
203
|
+
// Completeness belongs to the selected author list, not a lower-priority source.
|
|
204
|
+
etal: !record?.clearedMetadata?.includes('authors') && (useBlockAuthors ? fromBlocks.etal : citation.etal === true),
|
|
205
|
+
// 「这个值不是记录里存的」—— 与 citationMetadataWithDisk 的 filled* 不同:
|
|
206
|
+
// 后者只看它自己那一层,而这里要说清「相对原始记录补没补」。
|
|
207
|
+
filledAuthors: !recordedAuthors && citation.authors.length > 0,
|
|
208
|
+
filledYear: !recordedYear && citation.year !== '',
|
|
209
|
+
fromBlocks,
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* 从 `sourceDir` 读**磁盘上的规范文件名**,再合成一次元数据。
|
|
215
|
+
*
|
|
216
|
+
* 🔴 为什么需要第二层(实测数据):`state.json` 里的 `pdfName` 是**入库那一刻**的旧名,
|
|
217
|
+
* 73 篇里只有 9 篇带 ` - YYYY - `;而同一批论文**磁盘上的**文件名 73/73 都带 ——
|
|
218
|
+
* 那是改名功能上线后规范化的结果,只是没回写进记录(`bind` 按内容哈希比对,
|
|
219
|
+
* 明确回「已是最新」,本来就不会刷新显示名)。
|
|
220
|
+
*
|
|
221
|
+
* 实测代价:73 篇顺序 `readdir` 共 **6 ms**(并行 1 ms),所以走读时合成而不是一次性脚本 ——
|
|
222
|
+
* 以后新增的论文也自动受益,不需要再跑一次迁移。
|
|
223
|
+
*
|
|
224
|
+
* 磁盘名拿不到(目录被删、没绑 sourceDir、没有 PDF)时**原样退回**上一层的结果,不报错:
|
|
225
|
+
* 引用少一个年份不该让导出失败。
|
|
226
|
+
*
|
|
227
|
+
* @param {{authors?: unknown, year?: unknown, pdfName?: unknown, sourceDir?: unknown}} record
|
|
228
|
+
* @param {{headingAuthors?: unknown, headingYear?: unknown}} [extra]
|
|
229
|
+
* @returns {Promise<{authors: string[], year: string, filledAuthors: boolean, filledYear: boolean, fromDiskName: string}>}
|
|
230
|
+
*/
|
|
231
|
+
export async function citationMetadataWithDisk(record = {}, extra = {}) {
|
|
232
|
+
const base = citationMetadata(record, extra)
|
|
233
|
+
// 两样都齐了就不碰磁盘 —— 这是绝大多数「元数据完整」的论文的路径。
|
|
234
|
+
if (base.authors.length > 0 && base.year !== '') return { ...base, fromDiskName: '' }
|
|
235
|
+
const dir = typeof record?.sourceDir === 'string' ? record.sourceDir.trim() : ''
|
|
236
|
+
if (dir === '') return { ...base, fromDiskName: '' }
|
|
237
|
+
let diskName = ''
|
|
238
|
+
try {
|
|
239
|
+
const entries = await readdir(dir)
|
|
240
|
+
const pdfs = entries.filter(name => name.toLowerCase().endsWith('.pdf'))
|
|
241
|
+
const sourceName = typeof record?.sourcePdfPath === 'string' ? record.sourcePdfPath.split(/[\\/]/).at(-1) : ''
|
|
242
|
+
const expected = sourceName || record?.pdfName
|
|
243
|
+
const matching = typeof expected === 'string' ? pdfs.find(name => name.toLowerCase() === expected.toLowerCase()) : undefined
|
|
244
|
+
// A known source takes priority. Ambiguous neighbouring PDFs cannot supply publication facts.
|
|
245
|
+
const candidate = matching ?? (!sourceName && pdfs.length === 1 ? pdfs[0] : '')
|
|
246
|
+
diskName = YEAR_SEGMENT.test(candidate) ? candidate : ''
|
|
247
|
+
} catch {
|
|
248
|
+
return { ...base, fromDiskName: '' }
|
|
249
|
+
}
|
|
250
|
+
if (diskName === '') return { ...base, fromDiskName: '' }
|
|
251
|
+
const merged = citationMetadata({ ...record, pdfName: diskName }, extra)
|
|
252
|
+
return {
|
|
253
|
+
...merged,
|
|
254
|
+
// 后一层可能只是把同一个值重新算出来,filled* 以「原始记录缺不缺」为准。
|
|
255
|
+
filledAuthors: base.filledAuthors || merged.filledAuthors,
|
|
256
|
+
filledYear: base.filledYear || merged.filledYear,
|
|
257
|
+
etal: base.etal || merged.etal,
|
|
258
|
+
fromDiskName: diskName,
|
|
259
|
+
}
|
|
260
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { mkdir, readFile, readdir, writeFile, rm } from 'node:fs/promises'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { citationLibrary } from './bibliography-formats.js'
|
|
5
|
+
import { replaceStateFile } from './storage.js'
|
|
6
|
+
import { DOMParser } from '@xmldom/xmldom'
|
|
7
|
+
|
|
8
|
+
const BUNDLED = ['gb-t-7714', 'ieee', 'nature']
|
|
9
|
+
const DEFAULTS = ['apa', 'vancouver', 'harvard1']
|
|
10
|
+
const MAX_STYLE_BYTES = 2 * 1024 * 1024
|
|
11
|
+
const LOCALES = ['en-US', 'zh-CN', 'de-DE', 'fr-FR', 'es-ES', 'nl-NL']
|
|
12
|
+
const assets = new URL('./csl/', import.meta.url)
|
|
13
|
+
const digest = value => createHash('sha256').update(value).digest('hex')
|
|
14
|
+
const CSL_NS = 'http://purl.org/net/xbiblio/csl'
|
|
15
|
+
|
|
16
|
+
/** CSL files remain local data. DTDs and entities are rejected before passing XML to citeproc. */
|
|
17
|
+
export function describeStyle(xml, key) {
|
|
18
|
+
if (typeof xml !== 'string' || !xml.trim() || Buffer.byteLength(xml) > MAX_STYLE_BYTES) throw new Error('CSL 样式须为不超过 2 MiB 的 XML 文本')
|
|
19
|
+
if (/<!DOCTYPE|<!ENTITY/i.test(xml)) throw new Error('CSL 样式不允许 DTD 或实体声明')
|
|
20
|
+
const doc = new DOMParser({ onError: (_level, message) => { throw new Error('CSL XML 无效:' + message) } }).parseFromString(xml, 'application/xml')
|
|
21
|
+
if (doc.documentElement?.localName !== 'style' || doc.documentElement.namespaceURI !== CSL_NS) throw new Error('这不是有效的 CSL 样式文件')
|
|
22
|
+
const elements = (node, name) => [...node.getElementsByTagNameNS(CSL_NS, name)]
|
|
23
|
+
const info = elements(doc, 'info')[0]
|
|
24
|
+
const id = info && elements(info, 'id')[0]?.textContent.trim(), title = info && elements(info, 'title')[0]?.textContent.trim()
|
|
25
|
+
if (!id || !title || id.length > 2048 || title.length > 512) throw new Error('CSL 样式缺少有效的 id 或 title')
|
|
26
|
+
const parent = elements(info, 'link').find(link => link.getAttribute('rel') === 'independent-parent')
|
|
27
|
+
if (!parent) {
|
|
28
|
+
if (!elements(doc, 'citation').length) throw new Error('CSL 独立样式缺少 citation')
|
|
29
|
+
const macros = new Set(elements(doc, 'macro').map(node => node.getAttribute('name')))
|
|
30
|
+
for (const node of doc.getElementsByTagName('*')) if (node.hasAttribute('macro') && !macros.has(node.getAttribute('macro'))) throw new Error('CSL 样式引用了不存在的宏:' + node.getAttribute('macro'))
|
|
31
|
+
}
|
|
32
|
+
return { key: key ?? 'custom-' + digest(id).slice(0, 24), id, title, ...(parent ? { parent: parent.getAttribute('href') } : {}) }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function createCitationStyles(repository) {
|
|
36
|
+
const directory = join(repository.root, 'csl', 'styles')
|
|
37
|
+
async function load() {
|
|
38
|
+
const { plugins } = await citationLibrary()
|
|
39
|
+
const config = plugins.config.get('@csl')
|
|
40
|
+
const styles = DEFAULTS.map(key => ({ ...describeStyle(config.styles.get(key), key), xml: config.styles.get(key), builtin: true }))
|
|
41
|
+
for (const key of BUNDLED) {
|
|
42
|
+
const xml = await readFile(new URL(key + '.csl', assets), 'utf8')
|
|
43
|
+
styles.push({ ...describeStyle(xml, key), xml, builtin: true })
|
|
44
|
+
}
|
|
45
|
+
const locale = await readFile(new URL('locales-zh-CN.xml', assets), 'utf8')
|
|
46
|
+
config.locales.add('zh-CN', locale)
|
|
47
|
+
const warnings = []
|
|
48
|
+
let names = []
|
|
49
|
+
try { names = await readdir(directory) } catch (error) { if (error.code !== 'ENOENT') throw error }
|
|
50
|
+
for (const name of names.filter(name => /^custom-[a-f0-9]{24}\.csl$/.test(name)).sort()) {
|
|
51
|
+
try {
|
|
52
|
+
const xml = await readFile(join(directory, name), 'utf8')
|
|
53
|
+
const style = describeStyle(xml)
|
|
54
|
+
if (name !== style.key + '.csl') throw new Error('样式身份与文件名不符')
|
|
55
|
+
styles.push({ ...style, xml, builtin: false })
|
|
56
|
+
} catch (error) { warnings.push(name + ':' + error.message) }
|
|
57
|
+
}
|
|
58
|
+
return { styles, warnings, config }
|
|
59
|
+
}
|
|
60
|
+
function independent(style, styles, seen = new Set()) {
|
|
61
|
+
if (seen.has(style.id)) throw new Error('CSL 父样式形成循环')
|
|
62
|
+
if (!style.parent) return style
|
|
63
|
+
seen.add(style.id)
|
|
64
|
+
const parent = styles.find(candidate => candidate.id === style.parent)
|
|
65
|
+
if (!parent) throw new Error('请先安装父样式:' + style.parent)
|
|
66
|
+
return independent(parent, styles, seen)
|
|
67
|
+
}
|
|
68
|
+
async function list() {
|
|
69
|
+
const { styles, warnings } = await load()
|
|
70
|
+
const { settings } = await repository.snapshot()
|
|
71
|
+
return { styles: styles.map(({ xml: _xml, ...style }) => style), warnings,
|
|
72
|
+
selected: settings.citationStyle ?? 'gb-t-7714', locale: settings.citationLocale ?? 'zh-CN', locales: LOCALES }
|
|
73
|
+
}
|
|
74
|
+
async function render(items, { style, locale, mode = 'bibliography' } = {}) {
|
|
75
|
+
if (!['bibliography', 'citation'].includes(mode)) throw new Error('CSL 排版类型必须是 bibliography / citation')
|
|
76
|
+
if (!items.length) throw new Error('请选择要排版的文献')
|
|
77
|
+
const { styles, config } = await load()
|
|
78
|
+
const { settings } = await repository.snapshot()
|
|
79
|
+
const key = style ?? settings.citationStyle ?? 'gb-t-7714'
|
|
80
|
+
const language = locale ?? settings.citationLocale ?? 'zh-CN'
|
|
81
|
+
if (!LOCALES.includes(language)) throw new Error('不支持的 CSL 语言:' + language)
|
|
82
|
+
const requested = styles.find(row => row.key === key || row.id === key)
|
|
83
|
+
if (!requested) throw new Error('CSL 样式尚未安装:' + key)
|
|
84
|
+
const source = independent(requested, styles)
|
|
85
|
+
const template = 'dsh-paper-' + digest(source.xml)
|
|
86
|
+
if (!config.styles.has(template)) config.styles.add(template, source.xml)
|
|
87
|
+
const { Cite } = await citationLibrary()
|
|
88
|
+
const text = new Cite(items).format(mode, { template, lang: language, format: 'text' })
|
|
89
|
+
return { format: 'csl', style: requested.key, styleTitle: requested.title, locale: language, mode, text }
|
|
90
|
+
}
|
|
91
|
+
async function install(xml) {
|
|
92
|
+
const info = describeStyle(xml)
|
|
93
|
+
return repository.withNamedWrite('citation-styles', async () => {
|
|
94
|
+
const { styles, config } = await load()
|
|
95
|
+
if (styles.some(style => style.builtin && style.id === info.id)) throw new Error('内置样式不能覆盖;请为自定义样式设置独立 id')
|
|
96
|
+
const candidates = [...styles.filter(style => style.id !== info.id), { ...info, xml }]
|
|
97
|
+
const source = independent({ ...info, xml }, candidates)
|
|
98
|
+
const template = 'dsh-paper-' + digest(source.xml)
|
|
99
|
+
const { Cite } = await citationLibrary()
|
|
100
|
+
config.styles.add(template, source.xml)
|
|
101
|
+
try { new Cite([{ id: 'validation', type: 'article-journal', title: 'Style validation', issued: { 'date-parts': [[2026]] } }]).format('citation', { template, format: 'text', lang: 'en-US' }) }
|
|
102
|
+
catch (error) { throw new Error('CSL 样式无法排版:' + error.message) }
|
|
103
|
+
await mkdir(directory, { recursive: true })
|
|
104
|
+
const file = join(directory, info.key + '.csl'), temporary = file + '.' + randomUUID() + '.tmp'
|
|
105
|
+
try { await writeFile(temporary, xml, { encoding: 'utf8', flag: 'wx' }); await replaceStateFile(temporary, file) }
|
|
106
|
+
catch (error) { await rm(temporary, { force: true }); throw error }
|
|
107
|
+
return { installed: info, ...await list() }
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
async function select(style, locale) {
|
|
111
|
+
const view = await list()
|
|
112
|
+
const row = view.styles.find(row => row.key === style || row.id === style)
|
|
113
|
+
if (!row) throw new Error('CSL 样式尚未安装:' + style)
|
|
114
|
+
if (locale !== undefined && !LOCALES.includes(locale)) throw new Error('不支持的 CSL 语言:' + locale)
|
|
115
|
+
await render([{ id: 'validation', type: 'article-journal', title: 'Style validation' }], { style: row.key, locale: locale ?? view.locale, mode: 'citation' })
|
|
116
|
+
await repository.update(state => { state.settings.citationStyle = row.key; state.settings.citationLocale = locale ?? view.locale })
|
|
117
|
+
return list()
|
|
118
|
+
}
|
|
119
|
+
return { list, render, install, select }
|
|
120
|
+
}
|