@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.
- package/LICENSE +21 -0
- package/README.md +137 -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 +2607 -0
- package/lib/client.js +9569 -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 +294 -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 +183 -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,210 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises'
|
|
2
|
+
import { dirname, extname, isAbsolute, relative, resolve, sep } from 'node:path'
|
|
3
|
+
import { isPageImageUnavailable } from './page-image.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 宿主资源路由:把 MinerU 结果目录里的图片与页面位图**按字节**喂给浏览器。
|
|
7
|
+
*
|
|
8
|
+
* 客户端用 `<img src="/api/dsh-paper/analysis-asset?...">` 取图,而 `<img onError>` 只认状态码,
|
|
9
|
+
* 所以这里回的是原始字节而不是 JSON 信封;出错时回一句纯文本原因(界面只当它失败,原因留给
|
|
10
|
+
* 开发面板)。
|
|
11
|
+
*
|
|
12
|
+
* 两条路由的依赖**全部由 deps 注入**,测试可整体替身(不起 uvx、不碰网络、不碰 runtime 目录):
|
|
13
|
+
*
|
|
14
|
+
* - `documentFor(documentId)` —— 查表函数,返回 `{ markdownPath, pdfPath }`(Promise 或同步值都行,
|
|
15
|
+
* 查不到返回 null)。`markdownPath` 供 `/analysis-asset` 定结果目录,`pdfPath` 供 `/page-image` 渲染。
|
|
16
|
+
* - `renderPageImages(input, options)` —— **必须是 lib/page-image.js 的那一个**:D49 要求共用渲染器与
|
|
17
|
+
* 缓存族、只取不同 width variant。这里不新建渲染链。
|
|
18
|
+
* - `cacheDir` —— 页面图缓存根目录(`<cacheDir>/pages/<内容标识>/<页码>@<宽度>.webp`)。
|
|
19
|
+
* - `command` —— 可选启动器覆盖,原样透传给 renderPageImages(不传就是它自己的默认值)。
|
|
20
|
+
*
|
|
21
|
+
* @param {{documentFor?: Function, renderPageImages?: Function, cacheDir?: string, command?: string}} [deps]
|
|
22
|
+
* @returns {{'analysis-asset': (request: Request, url?: URL|string) => Promise<Response>,
|
|
23
|
+
* 'page-image': (request: Request, url?: URL|string) => Promise<Response>}}
|
|
24
|
+
*/
|
|
25
|
+
export function createAssetRoutes(deps = {}) {
|
|
26
|
+
const documentFor = typeof deps.documentFor === 'function' ? deps.documentFor : null
|
|
27
|
+
const renderPageImages = typeof deps.renderPageImages === 'function' ? deps.renderPageImages : null
|
|
28
|
+
const cacheDir = typeof deps.cacheDir === 'string' ? deps.cacheDir.trim() : ''
|
|
29
|
+
const command = typeof deps.command === 'string' && deps.command.trim() !== '' ? deps.command : undefined
|
|
30
|
+
|
|
31
|
+
/** `GET /analysis-asset?documentId=&path=`:结果目录内的图片。 */
|
|
32
|
+
async function analysisAsset(request, url) {
|
|
33
|
+
const params = searchParamsOf(request, url)
|
|
34
|
+
const documentId = (params.get('documentId') ?? '').trim()
|
|
35
|
+
const rawPath = (params.get('path') ?? '').trim()
|
|
36
|
+
if (documentId === '' || rawPath === '') return textResponse('缺少 documentId 或 path', 400)
|
|
37
|
+
if (documentFor === null) return textResponse('论文查表未接线,无法定位结果目录', 503)
|
|
38
|
+
const markdownPath = pathOf(await documentFor(documentId), 'markdownPath')
|
|
39
|
+
if (markdownPath === '') return textResponse('论文不存在或尚未就绪', 404)
|
|
40
|
+
let path
|
|
41
|
+
try {
|
|
42
|
+
path = resolvedAssetPath(markdownPath, rawPath)
|
|
43
|
+
} catch (error) {
|
|
44
|
+
return textResponse(reasonOf(error), 400)
|
|
45
|
+
}
|
|
46
|
+
let data
|
|
47
|
+
try {
|
|
48
|
+
data = await readFile(path)
|
|
49
|
+
} catch (error) {
|
|
50
|
+
// 不存在、不是文件、读不动都收成同一个 404:客户端只有"画得出来/画不出来"两种结果,
|
|
51
|
+
// 区别只在原因串里(带上 errno,便于在开发面板里分辨到底是缺文件还是权限)。
|
|
52
|
+
return textResponse(`图片不存在或读不到(${error?.code ?? reasonOf(error)})`, 404)
|
|
53
|
+
}
|
|
54
|
+
return byteResponse(data, IMAGE_TYPES.get(extname(path).toLowerCase()) ?? OCTET_STREAM)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** `GET /page-image?documentId=&page=&width=`:PDF 某一页的位图(缺省 1200 宽的 UI 变体)。 */
|
|
58
|
+
async function pageImage(request, url) {
|
|
59
|
+
const params = searchParamsOf(request, url)
|
|
60
|
+
const documentId = (params.get('documentId') ?? '').trim()
|
|
61
|
+
if (documentId === '' || !DOCUMENT_ID_PATTERN.test(documentId)) {
|
|
62
|
+
return textResponse('documentId 缺失或格式非法(只允许 [A-Za-z0-9._-])', 400)
|
|
63
|
+
}
|
|
64
|
+
const page = positiveInteger(params.get('page'))
|
|
65
|
+
if (page === null) return textResponse('page 必须是正整数', 400)
|
|
66
|
+
const widthParam = params.get('width')
|
|
67
|
+
const width = widthParam === null || widthParam.trim() === '' ? DEFAULT_PAGE_WIDTH : positiveInteger(widthParam)
|
|
68
|
+
if (width === null || width > MAX_PAGE_WIDTH) {
|
|
69
|
+
return textResponse(`width 必须是 1–${MAX_PAGE_WIDTH} 的整数`, 400)
|
|
70
|
+
}
|
|
71
|
+
if (documentFor === null || renderPageImages === null || cacheDir === '') {
|
|
72
|
+
return textResponse('页面图渲染未接线:缺少论文查表 / 渲染器 / 缓存目录', 503)
|
|
73
|
+
}
|
|
74
|
+
const pdfPath = pathOf(await documentFor(documentId), 'pdfPath')
|
|
75
|
+
if (pdfPath === '') return textResponse('论文不存在或尚未就绪', 404)
|
|
76
|
+
// 裁边开关随查询串下来(?crop=1);缺省不裁,与接入前逐字节一致。
|
|
77
|
+
const crop = params.get('crop') === '1'
|
|
78
|
+
let result
|
|
79
|
+
try {
|
|
80
|
+
result = await renderPageImages(
|
|
81
|
+
{ pdfPath, pages: [page], width, documentId, crop },
|
|
82
|
+
{ cacheDir, command },
|
|
83
|
+
)
|
|
84
|
+
} catch (error) {
|
|
85
|
+
// 🔴 渲染不可用(uvx 缺失 / 超时 / helper 报错)在这里收成 503 + 一句可读原因:
|
|
86
|
+
// 既不能裸崩成 500,也不能拿一张空白图冒充。其它错误属于接线缺陷,原样抛给调用方,
|
|
87
|
+
// 由它的 catch 记栈 —— 那才是能定位的形状。
|
|
88
|
+
if (!isPageImageUnavailable(error)) throw error
|
|
89
|
+
return textResponse(`页面图暂不可用:${reasonOf(error)}`, 503)
|
|
90
|
+
}
|
|
91
|
+
const images = Array.isArray(result?.images) ? result.images : []
|
|
92
|
+
const image = images.find(entry => entry?.page === page)
|
|
93
|
+
// 页码越界或渲染被跳过:page-image.js 把它记进 skipped,images 里就没有这一页。
|
|
94
|
+
if (!image || !(image.data instanceof Uint8Array) || image.data.byteLength === 0) {
|
|
95
|
+
return textResponse(`第 ${page} 页没有页面图`, 404)
|
|
96
|
+
}
|
|
97
|
+
return byteResponse(image.data, PAGE_IMAGE_CONTENT_TYPE)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return { 'analysis-asset': analysisAsset, 'page-image': pageImage }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 扩展名 → Content-Type。**不猜**:表里没有的一律 application/octet-stream。 */
|
|
104
|
+
const IMAGE_TYPES = new Map([
|
|
105
|
+
['.jpg', 'image/jpeg'],
|
|
106
|
+
['.jpeg', 'image/jpeg'],
|
|
107
|
+
['.png', 'image/png'],
|
|
108
|
+
['.webp', 'image/webp'],
|
|
109
|
+
])
|
|
110
|
+
const OCTET_STREAM = 'application/octet-stream'
|
|
111
|
+
const PAGE_IMAGE_CONTENT_TYPE = 'image/webp'
|
|
112
|
+
/** 结果目录内的图片与内容寻址的页图都属于「私有一小时的静态资源」。 */
|
|
113
|
+
const CACHE_CONTROL = 'private, max-age=3600'
|
|
114
|
+
/** UI 高清变体;翻译侧走 896,两档在缓存键里分开(D49),互不干扰。 */
|
|
115
|
+
const DEFAULT_PAGE_WIDTH = 1200
|
|
116
|
+
/** width 直接决定 uvx 渲染出的位图大小,不设上限就是一个内存放大器。 */
|
|
117
|
+
const MAX_PAGE_WIDTH = 4096
|
|
118
|
+
/**
|
|
119
|
+
* documentId 会被 page-image.js 拼进缓存路径,必须与它同一口径地挡掉分隔符;
|
|
120
|
+
* 比它多挡一条:纯 `.` / `..` 虽然过了它的字符类,却会让缓存落到 `pages/` 的上一级。
|
|
121
|
+
*/
|
|
122
|
+
const DOCUMENT_ID_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]+$/
|
|
123
|
+
/** 503 的原因串来自 uvx 的 stderr,不能整段塞进响应体。 */
|
|
124
|
+
const MAX_REASON_CHARS = 400
|
|
125
|
+
const LOCAL_ORIGIN = 'http://127.0.0.1'
|
|
126
|
+
|
|
127
|
+
function reasonOf(error) {
|
|
128
|
+
const text = String(error?.message ?? error ?? '').trim() || '未知原因'
|
|
129
|
+
return text.length > MAX_REASON_CHARS ? `${text.slice(0, MAX_REASON_CHARS)}…` : text
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 取查询串。宿主把 url 直接交给 handler,但单测与将来的调用点未必;三种形态都认:
|
|
134
|
+
* URL 对象、字符串、以及只有 request.url 的情况。
|
|
135
|
+
*/
|
|
136
|
+
function searchParamsOf(request, url) {
|
|
137
|
+
if (url && typeof url === 'object' && typeof url.searchParams?.get === 'function') return url.searchParams
|
|
138
|
+
const raw = typeof url === 'string' && url !== '' ? url : request?.url
|
|
139
|
+
try {
|
|
140
|
+
return new URL(String(raw ?? ''), LOCAL_ORIGIN).searchParams
|
|
141
|
+
} catch {
|
|
142
|
+
return new URLSearchParams()
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 查表结果里的路径字段;不是非空字符串就当"这篇还没就绪"。 */
|
|
147
|
+
function pathOf(document, key) {
|
|
148
|
+
const value = document?.[key]
|
|
149
|
+
return typeof value === 'string' ? value.trim() : ''
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function positiveInteger(value) {
|
|
153
|
+
if (value === null || value === undefined) return null
|
|
154
|
+
const text = String(value).trim()
|
|
155
|
+
if (!/^\d+$/.test(text)) return null
|
|
156
|
+
const number = Number(text)
|
|
157
|
+
return Number.isSafeInteger(number) && number > 0 ? number : null
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* 把查询串里的 `path` 收成一个结果目录内的绝对路径,越界抛错。
|
|
162
|
+
*
|
|
163
|
+
* 🔴 口径与 markdown-assets.js#resolvedImagePath **完全一致** —— 同一类问题在仓库里已经解过一次,
|
|
164
|
+
* 不发明第二套:先按 `?`/`#` 截断、再 `decodeURIComponent`(它遇到孤立的 `%` 会抛错,那时
|
|
165
|
+
* 按原值处理)、然后 `resolve`,最后用 `relative` 判是不是还在根里(`''` 放行,`..` 开头或
|
|
166
|
+
* 绝对路径拒绝)。`path` 来自可被改写的 MinerU 产物,这是一条**安全边界**而不是防御性编程:
|
|
167
|
+
* 放行绝对路径就等于把整个磁盘读给浏览器。
|
|
168
|
+
*/
|
|
169
|
+
function resolvedAssetPath(markdownPath, rawPath) {
|
|
170
|
+
const withoutSuffix = rawPath.split(/[?#]/, 1)[0]
|
|
171
|
+
let decoded
|
|
172
|
+
try {
|
|
173
|
+
decoded = decodeURIComponent(withoutSuffix)
|
|
174
|
+
} catch {
|
|
175
|
+
decoded = withoutSuffix
|
|
176
|
+
}
|
|
177
|
+
if (decoded.trim() === '') throw new Error('图片路径为空')
|
|
178
|
+
// 显式先挡绝对路径:不依赖各平台 relative() 的返回值形状给出同一个状态码。
|
|
179
|
+
if (isAbsolute(decoded)) throw new Error(`不接受绝对路径:${decoded}`)
|
|
180
|
+
const root = dirname(resolve(markdownPath))
|
|
181
|
+
const path = resolve(root, decoded)
|
|
182
|
+
const child = relative(root, path)
|
|
183
|
+
if (child !== '' && (isAbsolute(child) || child === '..' || child.startsWith(`..${sep}`))) {
|
|
184
|
+
throw new Error(`图片路径越出结果目录:${decoded}`)
|
|
185
|
+
}
|
|
186
|
+
return path
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function byteResponse(data, contentType) {
|
|
190
|
+
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data)
|
|
191
|
+
return new Response(bytes, {
|
|
192
|
+
status: 200,
|
|
193
|
+
// Content-Length 显式给出:客户端按它拿进度,测试也按它断言"回的是字节"。
|
|
194
|
+
headers: {
|
|
195
|
+
'Content-Type': contentType,
|
|
196
|
+
'Content-Length': String(bytes.byteLength),
|
|
197
|
+
'Cache-Control': CACHE_CONTROL,
|
|
198
|
+
},
|
|
199
|
+
})
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function textResponse(message, status) {
|
|
203
|
+
return new Response(`${message}\n`, {
|
|
204
|
+
status,
|
|
205
|
+
headers: {
|
|
206
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
207
|
+
'Cache-Control': 'no-store',
|
|
208
|
+
},
|
|
209
|
+
})
|
|
210
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { effectiveBibliography } from './bibliography.js'
|
|
2
|
+
import { effectiveMetadata } from './paper-metadata.js'
|
|
3
|
+
import { citationMetadataOfRecord } from './citation-metadata.js'
|
|
4
|
+
import { documentPaths, hydrateDocument } from './portable.js'
|
|
5
|
+
|
|
6
|
+
export const BIBLIOGRAPHY_FORMATS = Object.freeze(['bibtex', 'ris', 'csl-json'])
|
|
7
|
+
export const MAX_BIBLIOGRAPHY_BYTES = 8 * 1024 * 1024
|
|
8
|
+
export const MAX_BIBLIOGRAPHY_ITEMS = 5000
|
|
9
|
+
let engine
|
|
10
|
+
|
|
11
|
+
/** Load local parsers only. Imported DOI, URL and attachment fields never trigger requests. */
|
|
12
|
+
export async function citationLibrary() {
|
|
13
|
+
engine ??= Promise.all([
|
|
14
|
+
import('@citation-js/core'), import('@citation-js/plugin-bibtex'),
|
|
15
|
+
import('@citation-js/plugin-ris'), import('@citation-js/plugin-csl'),
|
|
16
|
+
]).then(([core]) => core).catch(error => { engine = undefined; throw new Error('书目引擎加载失败,请安装插件依赖:' + error.message) })
|
|
17
|
+
return engine
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const string = value => typeof value === 'string' ? value.trim() : ''
|
|
21
|
+
const clone = value => JSON.parse(JSON.stringify(value))
|
|
22
|
+
export const creatorName = name => string(name?.literal) || [name?.given, name?.['dropping-particle'], name?.['non-dropping-particle'], name?.family, name?.suffix].map(string).filter(Boolean).join(' ')
|
|
23
|
+
const TYPE_TO_CSL = { article: 'article-journal', journalArticle: 'article-journal', journal: 'article-journal',
|
|
24
|
+
conference: 'paper-conference', conferencePaper: 'paper-conference', inproceedings: 'paper-conference',
|
|
25
|
+
bookSection: 'chapter', incollection: 'chapter', part: 'chapter', preprint: 'article', thesis: 'thesis', dissertation: 'thesis', webpage: 'webpage' }
|
|
26
|
+
const TYPE_FROM_CSL = { 'article-journal': 'article', 'paper-conference': 'conference', chapter: 'chapter' }
|
|
27
|
+
const CSL_FIELDS = { publicationTitle: 'container-title', publisher: 'publisher', volume: 'volume', issue: 'issue', pages: 'page',
|
|
28
|
+
place: 'publisher-place', doi: 'DOI', url: 'URL', abstract: 'abstract', language: 'language', shortTitle: 'title-short',
|
|
29
|
+
series: 'collection-title', seriesNumber: 'collection-number', rights: 'license', extra: 'note', citationKey: 'citation-key' }
|
|
30
|
+
|
|
31
|
+
export function fieldsFromCsl(item) {
|
|
32
|
+
const issued = item.issued?.['date-parts']?.[0]
|
|
33
|
+
const year = Array.isArray(issued) && Number.isInteger(issued[0]) ? String(issued[0]) : ''
|
|
34
|
+
const result = { title: string(item.title), authors: (item.author ?? []).map(creatorName).filter(Boolean), year,
|
|
35
|
+
itemType: TYPE_FROM_CSL[item.type] ?? string(item.type) }
|
|
36
|
+
for (const [field, csl] of Object.entries(CSL_FIELDS)) {
|
|
37
|
+
const value = Array.isArray(item[csl]) ? item[csl].join('; ') : item[csl]
|
|
38
|
+
if (string(value)) result[field] = string(value)
|
|
39
|
+
}
|
|
40
|
+
if (year) result.date = issued.slice(0, 3).map((part, index) => index ? String(part).padStart(2, '0') : String(part)).join('-')
|
|
41
|
+
return result
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Parse the complete input before any write; reject empty, malformed or oversized databases. */
|
|
45
|
+
export async function parseBibliography(data, format) {
|
|
46
|
+
if (!BIBLIOGRAPHY_FORMATS.includes(format)) throw new Error('书目格式必须是 bibtex / ris / csl-json')
|
|
47
|
+
if (typeof data !== 'string' || !data.trim()) throw new Error('书目内容不能为空')
|
|
48
|
+
if (Buffer.byteLength(data, 'utf8') > MAX_BIBLIOGRAPHY_BYTES) throw new Error('书目文件超过 8 MiB,请分批导入')
|
|
49
|
+
let input = data.replace(/^\uFEFF/, '')
|
|
50
|
+
if (format === 'csl-json') {
|
|
51
|
+
try { input = JSON.parse(input) } catch { throw new Error('CSL-JSON 不是合法 JSON') }
|
|
52
|
+
if (!Array.isArray(input)) throw new Error('CSL-JSON 须为条目数组')
|
|
53
|
+
if (input.some(item => !item || typeof item !== 'object' || Array.isArray(item))) throw new Error('CSL-JSON 条目须为对象')
|
|
54
|
+
} else if (format === 'bibtex' && !/@\w+\s*[{(]/.test(input)) throw new Error('没有找到 BibTeX 条目')
|
|
55
|
+
else if (format === 'ris' && (!/^TY\s{2}- /m.test(input) || !/^ER\s{2}-/m.test(input))) throw new Error('RIS 须包含 TY 和 ER 条目标记')
|
|
56
|
+
const { Cite } = await citationLibrary()
|
|
57
|
+
let parsed
|
|
58
|
+
try { parsed = new Cite(input, { forceType: { bibtex: '@biblatex/text', ris: '@ris/file', 'csl-json': '@csl/list+object' }[format] }).data }
|
|
59
|
+
catch (error) { throw new Error('无法解析书目:' + error.message) }
|
|
60
|
+
if (!parsed.length || parsed.length > MAX_BIBLIOGRAPHY_ITEMS) throw new Error('每批须包含 1–5000 条书目')
|
|
61
|
+
return parsed.map((item, index) => {
|
|
62
|
+
const clean = clone(item)
|
|
63
|
+
delete clean._graph
|
|
64
|
+
delete clean._wiki
|
|
65
|
+
if (!string(clean.title) && !string(clean.DOI) && !string(clean.ISBN)) throw new Error('第 ' + (index + 1) + ' 条缺少题名、DOI 或 ISBN')
|
|
66
|
+
if (clean.author !== undefined && (!Array.isArray(clean.author) || clean.author.some(name => !name || typeof name !== 'object'))) throw new Error('第 ' + (index + 1) + ' 条作者格式无效')
|
|
67
|
+
return clean
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Keep structured imported creators unless the user has edited the corresponding flat field. */
|
|
72
|
+
export async function cslOfRecord(record) {
|
|
73
|
+
const meta = await effectiveMetadata(record).catch(error => {
|
|
74
|
+
if (error.code !== 'ENOENT') throw error
|
|
75
|
+
return citationMetadataOfRecord(record, documentPaths(hydrateDocument(record)).contentPath)
|
|
76
|
+
})
|
|
77
|
+
const bibliography = effectiveBibliography(record)
|
|
78
|
+
const item = clone(record.csl ?? {})
|
|
79
|
+
delete item._graph
|
|
80
|
+
item.id = record.id
|
|
81
|
+
item.type = (TYPE_TO_CSL[bibliography.itemType] ?? bibliography.itemType) || item.type
|
|
82
|
+
|| (bibliography.doi || bibliography.url || bibliography.sourceUrl || record.sourceUrl ? 'webpage' : 'document')
|
|
83
|
+
item.title = record.clearedMetadata?.includes('title') ? '' : string(record.title) || meta.title || meta.fromBlocks?.title
|
|
84
|
+
|| (record.kind === 'bibliography' ? '' : string(record.pdfName).replace(/\.pdf$/i, ''))
|
|
85
|
+
const names = (item.author ?? []).map(creatorName)
|
|
86
|
+
if (JSON.stringify(names) !== JSON.stringify(meta.authors ?? [])) item.author = (meta.authors ?? []).map(literal => ({ literal }))
|
|
87
|
+
const cleared = new Set(record.clearedMetadata ?? [])
|
|
88
|
+
for (const [field, csl] of Object.entries(CSL_FIELDS)) {
|
|
89
|
+
if (cleared.has(field)) delete item[csl]
|
|
90
|
+
else if (bibliography[field]) item[csl] = bibliography[field]
|
|
91
|
+
}
|
|
92
|
+
if (!cleared.has('url') && !item.URL) item.URL = bibliography.sourceUrl || record.sourceUrl || undefined
|
|
93
|
+
if (cleared.has('itemType')) delete item.type
|
|
94
|
+
if (cleared.has('year') || cleared.has('date')) delete item.issued
|
|
95
|
+
else if (bibliography.date && /^\d{4}(?:-\d{1,2}){0,2}$/.test(bibliography.date)) item.issued = { 'date-parts': [bibliography.date.split('-').map(Number)] }
|
|
96
|
+
else if (meta.year && String(item.issued?.['date-parts']?.[0]?.[0] ?? '') !== String(meta.year)) item.issued = { 'date-parts': [[Number(meta.year)]] }
|
|
97
|
+
if (cleared.has('accessDate')) delete item.accessed
|
|
98
|
+
else if (/^\d{4}-\d{2}-\d{2}$/.test(bibliography.accessDate)) item.accessed = { 'date-parts': [bibliography.accessDate.split('-').map(Number)] }
|
|
99
|
+
return item
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function serializeBibliography(items, format) {
|
|
103
|
+
if (!BIBLIOGRAPHY_FORMATS.includes(format)) throw new Error('书目格式必须是 bibtex / ris / csl-json')
|
|
104
|
+
if (format === 'csl-json') return JSON.stringify(items, null, 2) + '\n'
|
|
105
|
+
const { Cite, plugins } = await citationLibrary()
|
|
106
|
+
if (format === 'bibtex') {
|
|
107
|
+
const used = new Set()
|
|
108
|
+
items = items.map((item, index) => {
|
|
109
|
+
const original = string(item['citation-key'])
|
|
110
|
+
const base = /^[\p{L}\p{N}_:.+/-]+$/u.test(original) ? original : 'dsh_' + String(item.id ?? index).replace(/[^a-z0-9_]/gi, '').slice(0, 24)
|
|
111
|
+
let key = base, suffix = 2
|
|
112
|
+
while (used.has(key)) key = base + '_' + suffix++
|
|
113
|
+
used.add(key)
|
|
114
|
+
// Generic CSL documents have no BibTeX journal field; retain the recorded source as a note.
|
|
115
|
+
const note = ['document', 'webpage'].includes(item.type) && item['container-title']
|
|
116
|
+
? [item.note, item['container-title']].filter(Boolean).join('; ') : item.note
|
|
117
|
+
return { ...item, ...(note ? { note } : {}), 'citation-key': key }
|
|
118
|
+
})
|
|
119
|
+
// Citation.js otherwise replaces legal keys containing a hyphen. Formatting is synchronous.
|
|
120
|
+
const config = plugins.config.get('@bibtex')
|
|
121
|
+
const checkLabel = config.format.checkLabel
|
|
122
|
+
try { config.format.checkLabel = false; return new Cite(items).format(format) }
|
|
123
|
+
finally { config.format.checkLabel = checkLabel }
|
|
124
|
+
}
|
|
125
|
+
return new Cite(items).format(format)
|
|
126
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { effectiveBibliography, METADATA_FACT_FIELDS } from './bibliography.js'
|
|
3
|
+
import { fieldsFromCsl, parseBibliography } from './bibliography-formats.js'
|
|
4
|
+
import { readDocumentManifest } from './portable.js'
|
|
5
|
+
import { itemPathOf, readItem, writeItem } from './library.js'
|
|
6
|
+
import { validateMetadata } from './paper-metadata.js'
|
|
7
|
+
|
|
8
|
+
const text = value => typeof value === 'string' ? value.trim() : ''
|
|
9
|
+
const fold = value => text(value).normalize('NFKC').toLowerCase().replace(/\s+/g, ' ')
|
|
10
|
+
const doiOf = value => fold(value).replace(/^https?:\/\/(?:dx\.)?doi\.org\//, '').replace(/^doi:\s*/, '')
|
|
11
|
+
const populated = value => Array.isArray(value) ? value.length > 0 : value !== undefined && value !== null && text(String(value)) !== ''
|
|
12
|
+
|
|
13
|
+
function identity(item) {
|
|
14
|
+
if (text(item.DOI)) return 'doi:' + doiOf(item.DOI)
|
|
15
|
+
if (text(item.ISBN)) return 'isbn:' + fold(item.ISBN).replace(/[^0-9x]/g, '') + ':' + fold(item.title)
|
|
16
|
+
const fields = fieldsFromCsl(item)
|
|
17
|
+
return 'title:' + fold(fields.title) + ':' + fold(fields.authors.join(';')) + ':' + fields.year
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function matches(record, item) {
|
|
21
|
+
const bibliography = effectiveBibliography(record)
|
|
22
|
+
if (text(item.DOI)) return doiOf(bibliography.doi) === doiOf(item.DOI)
|
|
23
|
+
if (text(item.ISBN) && record.csl?.ISBN) return identity(record.csl) === identity(item)
|
|
24
|
+
const fields = fieldsFromCsl(item)
|
|
25
|
+
// A title alone is insufficient evidence for joining two records.
|
|
26
|
+
return fields.title && fields.authors.length && fields.year && fold(record.title) === fold(fields.title)
|
|
27
|
+
&& fold((record.authors ?? []).join(';')) === fold(fields.authors.join(';')) && String(record.year ?? '') === fields.year
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function missingFields(record, fields) {
|
|
31
|
+
const bibliography = effectiveBibliography(record)
|
|
32
|
+
const cleared = new Set(record.clearedMetadata ?? [])
|
|
33
|
+
return Object.fromEntries(Object.entries(fields).filter(([key, value]) => METADATA_FACT_FIELDS.includes(key) && populated(value)
|
|
34
|
+
&& !cleared.has(key) && record.metadataSources?.[key]?.provider !== 'manual'
|
|
35
|
+
&& !populated(['title', 'authors', 'year'].includes(key) ? record[key] : bibliography[key])))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Preview and commit use the same identity rules. Conflicts never overwrite existing facts. */
|
|
39
|
+
export function createBibliographyImporter({ repository, allDocuments, libraryService }) {
|
|
40
|
+
async function run({ data, format, dryRun = true, collectionId } = {}) {
|
|
41
|
+
const entries = await parseBibliography(data, format)
|
|
42
|
+
for (const item of entries) validateMetadata(fieldsFromCsl(item))
|
|
43
|
+
const execute = async () => {
|
|
44
|
+
if (collectionId && !(await libraryService.load()).collections.some(row => row.id === collectionId)) throw new Error('目标集合不存在')
|
|
45
|
+
const records = await allDocuments()
|
|
46
|
+
const rows = [], failures = []
|
|
47
|
+
let imported = 0, updated = 0, unchanged = 0
|
|
48
|
+
for (const [index, csl] of entries.entries()) {
|
|
49
|
+
try {
|
|
50
|
+
const fields = fieldsFromCsl(csl)
|
|
51
|
+
const documentId = createHash('sha256').update('dsh-paper:bibliography:' + identity(csl)).digest('hex')
|
|
52
|
+
const candidates = records.filter(record => record.id === documentId || matches(record, csl))
|
|
53
|
+
if (candidates.length > 1) throw new Error('匹配到多个已有条目,请先核对重复文献;本条未导入')
|
|
54
|
+
const existing = candidates[0]
|
|
55
|
+
const id = existing?.id ?? documentId
|
|
56
|
+
let changed = existing ? missingFields(existing, fields) : fields
|
|
57
|
+
let action = existing ? Object.keys(changed).length ? 'update' : 'unchanged' : 'import'
|
|
58
|
+
if (dryRun === false) {
|
|
59
|
+
await repository.withDocumentWrite(id, () => repository.update(async state => {
|
|
60
|
+
const stored = state.documents[id] ?? await repository.archivedDocument(id)
|
|
61
|
+
const raw = stored ? await readDocumentManifest(stored) ?? stored : undefined
|
|
62
|
+
changed = raw ? missingFields(raw, fields) : fields
|
|
63
|
+
action = raw ? Object.keys(changed).length ? 'update' : 'unchanged' : 'import'
|
|
64
|
+
const next = raw ? { ...raw, bibliography: effectiveBibliography(raw) } : {
|
|
65
|
+
id, kind: 'bibliography', pdfName: '书目 - ' + id.slice(0, 12), pdfPath: '',
|
|
66
|
+
title: '', authors: [], year: '', bibliography: {}, createdAt: new Date().toISOString(),
|
|
67
|
+
}
|
|
68
|
+
for (const [key, value] of Object.entries(changed)) {
|
|
69
|
+
if (['title', 'authors', 'year'].includes(key)) next[key] = value
|
|
70
|
+
else next.bibliography[key] = value
|
|
71
|
+
}
|
|
72
|
+
// Preserve structured creators and fields not represented by the editing form.
|
|
73
|
+
next.csl = { ...csl, ...(raw?.csl ?? {}), id }
|
|
74
|
+
delete next.csl._graph
|
|
75
|
+
next.bibliography.modifiedAt = new Date().toISOString()
|
|
76
|
+
await repository.writeArchivedDocument(next)
|
|
77
|
+
// PDF-free facts live in the durable record, without a second state.json copy.
|
|
78
|
+
if (next.kind === 'bibliography') delete state.documents[id]
|
|
79
|
+
else if (state.documents[id]) state.documents[id] = next
|
|
80
|
+
const position = records.findIndex(record => record.id === id)
|
|
81
|
+
if (position < 0) records.push(next)
|
|
82
|
+
else records[position] = next
|
|
83
|
+
}))
|
|
84
|
+
const record = records.find(row => row.id === id)
|
|
85
|
+
const path = itemPathOf(repository.root, record)
|
|
86
|
+
if (path) {
|
|
87
|
+
const item = await readItem(path)
|
|
88
|
+
if (!item.added) await writeItem(path, item)
|
|
89
|
+
}
|
|
90
|
+
if (collectionId) await libraryService.attachImported(collectionId, [id])
|
|
91
|
+
} else if (!existing) {
|
|
92
|
+
records.push({ id, ...fields, bibliography: fields, csl })
|
|
93
|
+
}
|
|
94
|
+
if (action === 'import') imported += 1
|
|
95
|
+
else if (action === 'update') updated += 1
|
|
96
|
+
else unchanged += 1
|
|
97
|
+
rows.push({ index: index + 1, documentId: id, title: fields.title, action, fields: Object.keys(changed) })
|
|
98
|
+
} catch (error) { failures.push({ index: index + 1, error: error.message }) }
|
|
99
|
+
}
|
|
100
|
+
return { dryRun: dryRun !== false, total: entries.length, imported, updated, unchanged, rows, failures }
|
|
101
|
+
}
|
|
102
|
+
return dryRun === false ? repository.withNamedWrite('bibliography-import', execute) : execute()
|
|
103
|
+
}
|
|
104
|
+
return { run }
|
|
105
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { cslOfRecord, serializeBibliography, BIBLIOGRAPHY_FORMATS } from './bibliography-formats.js'
|
|
3
|
+
import { createBibliographyImporter } from './bibliography-import.js'
|
|
4
|
+
import { createCitationStyles } from './citation-styles.js'
|
|
5
|
+
import { readDocumentManifest } from './portable.js'
|
|
6
|
+
|
|
7
|
+
export function createBibliographyService({ repository, allDocuments, libraryService }) {
|
|
8
|
+
const styles = createCitationStyles(repository)
|
|
9
|
+
const importer = createBibliographyImporter({ repository, allDocuments, libraryService })
|
|
10
|
+
async function exportRecords(documentIds, format = 'csl-json', options = {}) {
|
|
11
|
+
if (!Array.isArray(documentIds) || !documentIds.length || documentIds.length > 5000 || documentIds.some(id => typeof id !== 'string' || !/^[a-f0-9]{64}$/.test(id))) throw new Error('请选择 1–5000 条有效书目')
|
|
12
|
+
const ids = [...new Set(documentIds)]
|
|
13
|
+
const items = []
|
|
14
|
+
const state = await repository.snapshot()
|
|
15
|
+
for (const id of ids) {
|
|
16
|
+
const record = state.documents[id] ?? await repository.archivedDocument(id)
|
|
17
|
+
if (!record) throw new Error('书目不存在:' + id)
|
|
18
|
+
const raw = await readDocumentManifest(record, { validateArtifacts: false }).catch(error => {
|
|
19
|
+
if (error.code !== 'ENOENT') throw error
|
|
20
|
+
return undefined
|
|
21
|
+
}) ?? record
|
|
22
|
+
items.push(await cslOfRecord(raw))
|
|
23
|
+
}
|
|
24
|
+
const exportId = createHash('sha256').update(ids.join('\n')).digest('hex')
|
|
25
|
+
if (BIBLIOGRAPHY_FORMATS.includes(format)) return { format, count: items.length, exportId,
|
|
26
|
+
extension: { bibtex: 'bib', ris: 'ris', 'csl-json': 'json' }[format], text: await serializeBibliography(items, format) }
|
|
27
|
+
if (!['csl', 'apa', 'gb-t-7714'].includes(format)) throw new Error('导出格式必须是 bibtex / ris / csl-json / csl / apa / gb-t-7714')
|
|
28
|
+
const rendered = items.map(item => item.DOI ? { ...item, URL: undefined } : item)
|
|
29
|
+
const output = await styles.render(rendered, { ...options, ...(['apa', 'gb-t-7714'].includes(format) ? { style: format } : {}) })
|
|
30
|
+
return { ...output, format, count: items.length, exportId, extension: 'txt' }
|
|
31
|
+
}
|
|
32
|
+
async function run(request) {
|
|
33
|
+
if (request.action === 'styles') return { ok: true, notice: '已读取 CSL 样式。', styleCatalog: await styles.list() }
|
|
34
|
+
if (request.action === 'style-install') return { ok: true, notice: 'CSL 样式已安装。', styleCatalog: await styles.install(request.data) }
|
|
35
|
+
if (request.action === 'style-select') return { ok: true, notice: '默认 CSL 样式已保存。', styleCatalog: await styles.select(request.style, request.locale) }
|
|
36
|
+
if (request.action === 'import') {
|
|
37
|
+
const report = await importer.run(request)
|
|
38
|
+
return { ok: report.failures.length === 0, notice: (report.dryRun ? '预览:' : '已处理:') + '新增 ' + report.imported + ' 条,补全 ' + report.updated + ' 条,保留 ' + report.unchanged + ' 条,失败 ' + report.failures.length + ' 条。', importReport: report }
|
|
39
|
+
}
|
|
40
|
+
throw new Error('不支持的书目操作')
|
|
41
|
+
}
|
|
42
|
+
return { run, exportRecords, styles }
|
|
43
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export const BIBLIOGRAPHIC_FIELDS = Object.freeze([
|
|
2
|
+
'itemType', 'citationKey', 'titleTranslation', 'abstract', 'abstractTranslation',
|
|
3
|
+
'publicationTitle', 'publisher', 'volume', 'issue', 'pages', 'category',
|
|
4
|
+
'repository', 'archiveId', 'place', 'date', 'series', 'seriesNumber',
|
|
5
|
+
'doi', 'url', 'sourceUrl', 'accessDate', 'archive', 'archiveLocation',
|
|
6
|
+
'shortTitle', 'language', 'libraryCatalog', 'callNumber', 'rights', 'extra', 'modifiedAt',
|
|
7
|
+
])
|
|
8
|
+
|
|
9
|
+
export const METADATA_FACT_FIELDS = Object.freeze(['title', 'authors', 'year', ...BIBLIOGRAPHIC_FIELDS.filter(key => key !== 'modifiedAt')])
|
|
10
|
+
|
|
11
|
+
/** Persist only recognized field provenance; it contains public URLs, never asset paths. */
|
|
12
|
+
export function metadataSourcesOf(value) {
|
|
13
|
+
return Object.fromEntries(METADATA_FACT_FIELDS.flatMap(field => {
|
|
14
|
+
const source = value?.[field]
|
|
15
|
+
if (!source || !['manual', 'acl', 'crossref', 'doi', 'arxiv'].includes(source.provider)) return []
|
|
16
|
+
const row = { provider: source.provider }
|
|
17
|
+
for (const key of ['identifier', 'checkedAt']) if (typeof source[key] === 'string' && source[key].length < 2048) row[key] = source[key]
|
|
18
|
+
if (typeof source.url === 'string') {
|
|
19
|
+
try {
|
|
20
|
+
const url = new URL(source.url)
|
|
21
|
+
if (url.protocol === 'https:' && !url.username && !url.password) row.url = url.href
|
|
22
|
+
} catch {}
|
|
23
|
+
}
|
|
24
|
+
return [[field, row]]
|
|
25
|
+
}))
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Bibliographic values are recorded facts; missing values stay empty. */
|
|
29
|
+
export function bibliographyOf(...sources) {
|
|
30
|
+
return Object.fromEntries(BIBLIOGRAPHIC_FIELDS.map(field => [field,
|
|
31
|
+
sources.map(source => source?.[field]).find(value => typeof value === 'string' && value.trim() !== '')?.trim() ?? '',
|
|
32
|
+
]))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Canonical fields include explicit empty values; fallbacks fill only absent fields. */
|
|
36
|
+
export function effectiveBibliography(record) {
|
|
37
|
+
const result = bibliographyOf(record?.metadata?.bibliography, record?.metadata, record)
|
|
38
|
+
for (const field of BIBLIOGRAPHIC_FIELDS) {
|
|
39
|
+
if (typeof record?.bibliography?.[field] === 'string') result[field] = record.bibliography[field].trim()
|
|
40
|
+
}
|
|
41
|
+
return result
|
|
42
|
+
}
|