@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,157 @@
|
|
|
1
|
+
import { inflateRawSync } from 'node:zlib'
|
|
2
|
+
|
|
3
|
+
export const MAX_RESULT_ARCHIVE_BYTES = 256 * 1024 * 1024
|
|
4
|
+
const MAX_RESULT_FILES = 10_000
|
|
5
|
+
const MAX_IMAGE_BYTES = 64 * 1024 * 1024
|
|
6
|
+
const MAX_TOTAL_IMAGE_BYTES = 256 * 1024 * 1024
|
|
7
|
+
const END_SIGNATURE = 0x06054b50
|
|
8
|
+
const CENTRAL_SIGNATURE = 0x02014b50
|
|
9
|
+
const LOCAL_SIGNATURE = 0x04034b50
|
|
10
|
+
const CRC32_TABLE = new Uint32Array(256)
|
|
11
|
+
for (let index = 0; index < CRC32_TABLE.length; index += 1) {
|
|
12
|
+
let value = index
|
|
13
|
+
for (let bit = 0; bit < 8; bit += 1) value = (value >>> 1) ^ (0xedb88320 & -(value & 1))
|
|
14
|
+
CRC32_TABLE[index] = value >>> 0
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function requireRange(buffer, offset, length, subject) {
|
|
18
|
+
if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || offset + length > buffer.length) {
|
|
19
|
+
throw new Error(`MinerU 结果 ZIP 的 ${subject} 越界`)
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function endRecordOffset(buffer) {
|
|
24
|
+
const minimum = Math.max(0, buffer.length - 65_557)
|
|
25
|
+
for (let offset = buffer.length - 22; offset >= minimum; offset -= 1) {
|
|
26
|
+
if (buffer.readUInt32LE(offset) !== END_SIGNATURE) continue
|
|
27
|
+
const commentLength = buffer.readUInt16LE(offset + 20)
|
|
28
|
+
if (offset + 22 + commentLength === buffer.length) return offset
|
|
29
|
+
}
|
|
30
|
+
throw new Error('MinerU 结果不是有效 ZIP')
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function safeEntryName(buffer) {
|
|
34
|
+
const name = buffer.toString('utf8').replaceAll('\\', '/')
|
|
35
|
+
const segments = name.split('/')
|
|
36
|
+
if (name.includes('\0') || name.startsWith('/') || /^[a-z]:/i.test(name) || segments.includes('..')) return undefined
|
|
37
|
+
return segments.filter(segment => segment !== '' && segment !== '.').join('/')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function requestedPathFor(entryName, requestedPaths) {
|
|
41
|
+
let match
|
|
42
|
+
for (const requestedPath of requestedPaths) {
|
|
43
|
+
if (entryName === requestedPath) return requestedPath
|
|
44
|
+
if (entryName.endsWith(`/${requestedPath}`)) {
|
|
45
|
+
if (match !== undefined) throw new Error(`MinerU 结果 ZIP 图片路径歧义:${entryName}`)
|
|
46
|
+
match = requestedPath
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return match
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function crc32(buffer) {
|
|
53
|
+
let crc = 0xffffffff
|
|
54
|
+
for (const byte of buffer) crc = (crc >>> 8) ^ CRC32_TABLE[(crc ^ byte) & 0xff]
|
|
55
|
+
return (crc ^ 0xffffffff) >>> 0
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function entryData(archive, entry) {
|
|
59
|
+
requireRange(archive, entry.localOffset, 30, '本地文件头')
|
|
60
|
+
if (archive.readUInt32LE(entry.localOffset) !== LOCAL_SIGNATURE) throw new Error('MinerU 结果 ZIP 的本地文件头无效')
|
|
61
|
+
if (archive.readUInt16LE(entry.localOffset + 8) !== entry.method) throw new Error('MinerU 结果 ZIP 的压缩方式不一致')
|
|
62
|
+
const nameLength = archive.readUInt16LE(entry.localOffset + 26)
|
|
63
|
+
const extraLength = archive.readUInt16LE(entry.localOffset + 28)
|
|
64
|
+
const dataOffset = entry.localOffset + 30 + nameLength + extraLength
|
|
65
|
+
requireRange(archive, dataOffset, entry.compressedSize, '图片数据')
|
|
66
|
+
if (dataOffset + entry.compressedSize > entry.centralOffset) throw new Error('MinerU 结果 ZIP 图片数据与中央目录重叠')
|
|
67
|
+
const compressed = archive.subarray(dataOffset, dataOffset + entry.compressedSize)
|
|
68
|
+
let data
|
|
69
|
+
if (entry.method === 0) data = Buffer.from(compressed)
|
|
70
|
+
else if (entry.method === 8) data = inflateRawSync(compressed, { maxOutputLength: entry.uncompressedSize })
|
|
71
|
+
else throw new Error(`MinerU 结果 ZIP 使用不支持的压缩方式:${entry.method}`)
|
|
72
|
+
if (data.length !== entry.uncompressedSize) throw new Error('MinerU 结果 ZIP 图片解压大小不匹配')
|
|
73
|
+
if (crc32(data) !== entry.checksum) throw new Error('MinerU 结果 ZIP 图片校验失败')
|
|
74
|
+
return data
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 走一遍中央目录,把每个非目录条目交给 `visit`。
|
|
79
|
+
*
|
|
80
|
+
* 这是本模块**唯一**读中央目录的地方:`requestedFilesFromZip` 按名字取数据,
|
|
81
|
+
* `zipEntryNames` 只列名字,两者共用同一套边界校验(分卷 / ZIP64 / 条目数上限)。
|
|
82
|
+
*
|
|
83
|
+
* @param {Buffer} archive 结果 ZIP 的字节。
|
|
84
|
+
* @param {(entry: {entryName: string, flags: number, method: number, checksum: number, compressedSize: number, uncompressedSize: number, localOffset: number, centralOffset: number}) => void} visit 逐条回调。
|
|
85
|
+
*/
|
|
86
|
+
function walkEntries(archive, visit) {
|
|
87
|
+
const endOffset = endRecordOffset(archive)
|
|
88
|
+
requireRange(archive, endOffset, 22, '目录结束记录')
|
|
89
|
+
const disk = archive.readUInt16LE(endOffset + 4)
|
|
90
|
+
const centralDisk = archive.readUInt16LE(endOffset + 6)
|
|
91
|
+
const diskEntries = archive.readUInt16LE(endOffset + 8)
|
|
92
|
+
const totalEntries = archive.readUInt16LE(endOffset + 10)
|
|
93
|
+
const centralSize = archive.readUInt32LE(endOffset + 12)
|
|
94
|
+
const centralOffset = archive.readUInt32LE(endOffset + 16)
|
|
95
|
+
if (disk !== 0 || centralDisk !== 0 || diskEntries !== totalEntries) throw new Error('不支持分卷 MinerU 结果 ZIP')
|
|
96
|
+
if (totalEntries === 0xffff || centralSize === 0xffffffff || centralOffset === 0xffffffff) throw new Error('不支持 ZIP64 MinerU 结果 ZIP')
|
|
97
|
+
if (totalEntries > MAX_RESULT_FILES) throw new Error(`MinerU 结果 ZIP 文件数超过 ${MAX_RESULT_FILES}`)
|
|
98
|
+
requireRange(archive, centralOffset, centralSize, '中央目录')
|
|
99
|
+
if (centralOffset + centralSize > endOffset) throw new Error('MinerU 结果 ZIP 中央目录与结束记录重叠')
|
|
100
|
+
let cursor = centralOffset
|
|
101
|
+
for (let index = 0; index < totalEntries; index += 1) {
|
|
102
|
+
requireRange(archive, cursor, 46, '中央目录项')
|
|
103
|
+
if (archive.readUInt32LE(cursor) !== CENTRAL_SIGNATURE) throw new Error('MinerU 结果 ZIP 中央目录项无效')
|
|
104
|
+
const flags = archive.readUInt16LE(cursor + 8)
|
|
105
|
+
const method = archive.readUInt16LE(cursor + 10)
|
|
106
|
+
const checksum = archive.readUInt32LE(cursor + 16)
|
|
107
|
+
const compressedSize = archive.readUInt32LE(cursor + 20)
|
|
108
|
+
const uncompressedSize = archive.readUInt32LE(cursor + 24)
|
|
109
|
+
const nameLength = archive.readUInt16LE(cursor + 28)
|
|
110
|
+
const extraLength = archive.readUInt16LE(cursor + 30)
|
|
111
|
+
const commentLength = archive.readUInt16LE(cursor + 32)
|
|
112
|
+
const localOffset = archive.readUInt32LE(cursor + 42)
|
|
113
|
+
if (compressedSize === 0xffffffff || uncompressedSize === 0xffffffff || localOffset === 0xffffffff) throw new Error('不支持 ZIP64 MinerU 结果 ZIP')
|
|
114
|
+
requireRange(archive, cursor + 46, nameLength + extraLength + commentLength, '中央目录名称')
|
|
115
|
+
const entryName = safeEntryName(archive.subarray(cursor + 46, cursor + 46 + nameLength))
|
|
116
|
+
cursor += 46 + nameLength + extraLength + commentLength
|
|
117
|
+
if (entryName === undefined || entryName.endsWith('/')) continue
|
|
118
|
+
visit({ entryName, flags, method, checksum, compressedSize, uncompressedSize, localOffset, centralOffset })
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function requestedFilesFromZip(value, requestedPaths) {
|
|
123
|
+
const archive = Buffer.isBuffer(value) ? value : Buffer.from(value)
|
|
124
|
+
if (archive.length > MAX_RESULT_ARCHIVE_BYTES) throw new Error('MinerU 结果 ZIP 超过 256 MiB 限制')
|
|
125
|
+
const requested = new Set(requestedPaths.map(path => path.replaceAll('\\', '/')))
|
|
126
|
+
if (requested.size === 0) return new Map()
|
|
127
|
+
const found = new Map()
|
|
128
|
+
let totalBytes = 0
|
|
129
|
+
walkEntries(archive, entry => {
|
|
130
|
+
const requestedPath = requestedPathFor(entry.entryName, requested)
|
|
131
|
+
if (requestedPath === undefined) return
|
|
132
|
+
if (found.has(requestedPath)) throw new Error(`MinerU 结果 ZIP 图片重复:${requestedPath}`)
|
|
133
|
+
if ((entry.flags & 1) !== 0) throw new Error(`MinerU 结果 ZIP 图片已加密:${requestedPath}`)
|
|
134
|
+
if (entry.uncompressedSize > MAX_IMAGE_BYTES) throw new Error(`MinerU 图片超过 64 MiB 限制:${requestedPath}`)
|
|
135
|
+
totalBytes += entry.uncompressedSize
|
|
136
|
+
if (totalBytes > MAX_TOTAL_IMAGE_BYTES) throw new Error('MinerU 图片解压总量超过 256 MiB 限制')
|
|
137
|
+
found.set(requestedPath, entryData(archive, entry))
|
|
138
|
+
})
|
|
139
|
+
return found
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* 只列出结果 ZIP 里的条目名(不读数据)。
|
|
144
|
+
*
|
|
145
|
+
* 给「按名字找块列表」用:云端把块列表命名为 `<任务UUID>_content_list.json`(D134 实测),
|
|
146
|
+
* 主名不是文件名,光靠猜文件名永远猜不中 —— 得先知道 ZIP 里到底有哪些条目。
|
|
147
|
+
*
|
|
148
|
+
* @param {Buffer|Uint8Array} value 结果 ZIP 的字节。
|
|
149
|
+
* @returns {string[]} 安全化后的条目名(跳过目录项)。
|
|
150
|
+
*/
|
|
151
|
+
export function zipEntryNames(value) {
|
|
152
|
+
const archive = Buffer.isBuffer(value) ? value : Buffer.from(value)
|
|
153
|
+
if (archive.length > MAX_RESULT_ARCHIVE_BYTES) throw new Error('MinerU 结果 ZIP 超过 256 MiB 限制')
|
|
154
|
+
const names = []
|
|
155
|
+
walkEntries(archive, entry => names.push(entry.entryName))
|
|
156
|
+
return names
|
|
157
|
+
}
|
package/lib/revisions.js
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The mtime+size fast path for Markdown and outline files.
|
|
3
|
+
*
|
|
4
|
+
* The injection decision walks every paper in `desired ∪ delivered` on every pre-step, and
|
|
5
|
+
* the sidebar reads `/state` on a 2s rhythm; re-reading and re-hashing every whole Markdown
|
|
6
|
+
* is then tens of megabytes of disk per turn for a hundred papers. Change detection here is
|
|
7
|
+
* `stat`'s mtime plus size: when neither moved and the entry is still inside its trust
|
|
8
|
+
* window, the previous outline and content hash are reused, and only a real change re-reads
|
|
9
|
+
* the file and recomputes the hash.
|
|
10
|
+
*
|
|
11
|
+
* The trust window covers the one case mtime+size cannot see — an outside rewrite that
|
|
12
|
+
* preserved both the original timestamp and the byte count (a restore, a tool that stamps
|
|
13
|
+
* files). Such a change is picked up at the latest `REVISION_TRUST_MS` after it was cached.
|
|
14
|
+
*
|
|
15
|
+
* @module dsh-paper/revisions
|
|
16
|
+
*/
|
|
17
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
18
|
+
import { readFile, rm, stat, writeFile } from 'node:fs/promises'
|
|
19
|
+
import { headingTitle, splitBlocks, withDocumentTitle } from './blocks.js'
|
|
20
|
+
import { DEFAULT_OUTLINE_BUDGET_BYTES, OUTLINE_VERSION, buildOutline, outlineFileText, outlineInputRevision, parseOutlineFile } from './outline.js'
|
|
21
|
+
import { hydrateDocument, readDocumentManifest } from './portable.js'
|
|
22
|
+
import { replaceStateFile } from './storage.js'
|
|
23
|
+
|
|
24
|
+
/** Cached entries per file class; each paper keeps at most one outline, oldest evicted first. */
|
|
25
|
+
export const MAX_CACHED_FILES = 128
|
|
26
|
+
/** How long an mtime+size match is trusted before the file is read again. */
|
|
27
|
+
export const REVISION_TRUST_MS = 10 * 60 * 1000
|
|
28
|
+
|
|
29
|
+
function boundedCache(limit) {
|
|
30
|
+
const entries = new Map()
|
|
31
|
+
return {
|
|
32
|
+
get: key => entries.get(key),
|
|
33
|
+
set(key, value) {
|
|
34
|
+
if (entries.size >= limit && !entries.has(key)) entries.delete(entries.keys().next().value)
|
|
35
|
+
entries.set(key, value)
|
|
36
|
+
},
|
|
37
|
+
size: () => entries.size,
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Build a paper-file reader with the mtime+size fast path.
|
|
43
|
+
*
|
|
44
|
+
* The read and stat implementations are injectable so a test can assert "unchanged means
|
|
45
|
+
* nothing was read from disk"; production callers take the defaults.
|
|
46
|
+
*
|
|
47
|
+
* @param options - `{ readFileImpl, statImpl, nowImpl }`.
|
|
48
|
+
* @returns `{ usableDocument, documentView, cachedFiles }`.
|
|
49
|
+
*/
|
|
50
|
+
export function createDocumentReader({
|
|
51
|
+
readFileImpl = readFile,
|
|
52
|
+
statImpl = stat,
|
|
53
|
+
writeFileImpl = writeFile,
|
|
54
|
+
replaceFileImpl = replaceStateFile,
|
|
55
|
+
nowImpl = Date.now,
|
|
56
|
+
} = {}) {
|
|
57
|
+
const markdowns = boundedCache(MAX_CACHED_FILES)
|
|
58
|
+
const outlines = boundedCache(MAX_CACHED_FILES)
|
|
59
|
+
const contents = boundedCache(MAX_CACHED_FILES)
|
|
60
|
+
const pendingOutlines = new Map()
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* A cache entry is reused when its key matches, neither mtime nor size moved, and it is
|
|
64
|
+
* still inside the trust window.
|
|
65
|
+
*
|
|
66
|
+
* The Markdown key carries the outline budget: a different budget must re-render the
|
|
67
|
+
* outline rather than keep the truncation the old budget produced.
|
|
68
|
+
*
|
|
69
|
+
* @param cache - the cache for this file class.
|
|
70
|
+
* @param path - the file to stat and, on a miss, read.
|
|
71
|
+
* @param key - cache key (the path plus whatever else changes the read result).
|
|
72
|
+
* @param read - builds the cache entry on a miss.
|
|
73
|
+
* @returns the cache entry; a failed stat or read throws.
|
|
74
|
+
*/
|
|
75
|
+
async function readCached(cache, path, key, read) {
|
|
76
|
+
const info = await statImpl(path)
|
|
77
|
+
if (!info.isFile()) throw new Error(`${path} 不是文件`)
|
|
78
|
+
const now = nowImpl()
|
|
79
|
+
const cached = cache.get(key)
|
|
80
|
+
if (cached !== undefined
|
|
81
|
+
&& cached.mtimeMs === info.mtimeMs
|
|
82
|
+
&& cached.size === info.size
|
|
83
|
+
&& now - cached.readAt <= REVISION_TRUST_MS) return cached
|
|
84
|
+
const value = { ...await read(info), mtimeMs: info.mtimeMs, size: info.size, readAt: now }
|
|
85
|
+
cache.set(key, value)
|
|
86
|
+
return value
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 读一篇论文的块列表,连同它的**指纹**一起交出去。
|
|
91
|
+
*
|
|
92
|
+
* 块列表是**可选**产物(旧批次、MinerU 降级都没有它),任何一步失败都按「这篇没有块列表」
|
|
93
|
+
* 处理:注入退到纯标题目录,不报错、也不影响这篇论文本身的可用性。
|
|
94
|
+
*
|
|
95
|
+
* 指纹进 Markdown 的缓存键:目录由块序列渲染,块列表换了目录就得重渲 —— 而 Markdown 的
|
|
96
|
+
* mtime 未必跟着动(手工换掉 content.json 是合法操作)。缺文件时指纹为空串,与"没有块列表"
|
|
97
|
+
* 是同一种输入,同一个缓存项。
|
|
98
|
+
*/
|
|
99
|
+
async function contentListOf(resolved) {
|
|
100
|
+
const path = resolved.contentPath
|
|
101
|
+
if (typeof path !== 'string' || path === '') return { blocks: undefined, fingerprint: '' }
|
|
102
|
+
try {
|
|
103
|
+
const cached = await readCached(contents, path, path, async () => {
|
|
104
|
+
const parsed = JSON.parse(await readFileImpl(path, 'utf8'))
|
|
105
|
+
return { blocks: Array.isArray(parsed) ? splitBlocks(parsed) : undefined }
|
|
106
|
+
})
|
|
107
|
+
let blocks = cached.blocks
|
|
108
|
+
if ((blocks?.find(block => block.type === 'heading')?.sourceText?.length ?? 0) > 300) {
|
|
109
|
+
const record = await readDocumentManifest(resolved, { validateArtifacts: false }) ?? resolved
|
|
110
|
+
blocks = withDocumentTitle(blocks, record.title ?? record.metadata?.title)
|
|
111
|
+
}
|
|
112
|
+
return { blocks, fingerprint: `${cached.mtimeMs}:${cached.size}:${blocks?.find(block => block.displayTitle)?.displayTitle ?? ''}` }
|
|
113
|
+
} catch { return { blocks: undefined, fingerprint: '' } }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Whether one paper may be injected: reads the Markdown for the outline and revision. */
|
|
117
|
+
async function usableDocument(document, outlineBudgetBytes) {
|
|
118
|
+
const resolved = hydrateDocument(document)
|
|
119
|
+
try {
|
|
120
|
+
const { blocks, fingerprint } = await contentListOf(resolved)
|
|
121
|
+
const key = `${resolved.markdownPath}\u0000${outlineBudgetBytes}\u0000${fingerprint}`
|
|
122
|
+
const cached = await readCached(markdowns, resolved.markdownPath, key,
|
|
123
|
+
async () => {
|
|
124
|
+
const markdown = await readFileImpl(resolved.markdownPath, 'utf8')
|
|
125
|
+
if (markdown.trim() === '') throw new Error('Markdown 文件为空')
|
|
126
|
+
const outline = buildOutline(markdown, outlineBudgetBytes, blocks)
|
|
127
|
+
return {
|
|
128
|
+
revision: createHash('sha256').update(markdown).digest('hex'),
|
|
129
|
+
outlineText: outline.text,
|
|
130
|
+
outlineTruncated: outline.truncated,
|
|
131
|
+
}
|
|
132
|
+
})
|
|
133
|
+
return {
|
|
134
|
+
...resolved,
|
|
135
|
+
outlineText: cached.outlineText,
|
|
136
|
+
outlineTruncated: cached.outlineTruncated,
|
|
137
|
+
markdownRevision: cached.revision,
|
|
138
|
+
}
|
|
139
|
+
} catch { return { ...document, unavailable: true } }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** 记住一份读出来(或重建出来)的目录,并把当时的 mtime+size 一起记下。 */
|
|
143
|
+
function rememberOutline(key, text, info) {
|
|
144
|
+
const entry = { text, mtimeMs: info?.mtimeMs ?? 0, size: info?.size ?? 0, readAt: nowImpl() }
|
|
145
|
+
outlines.set(key, entry)
|
|
146
|
+
return entry
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* 目录的**输入修订身份**:它是由哪一版 Markdown 与块列表渲染出来的。
|
|
151
|
+
*
|
|
152
|
+
* @param {{markdownPath?: string, contentPath?: string}} paths 论文的落点。
|
|
153
|
+
* @returns {Promise<string>} 见 outline.js 的 outlineInputRevision;Markdown 不在时是空串。
|
|
154
|
+
*/
|
|
155
|
+
async function revisionInputsOf(paths) {
|
|
156
|
+
const markdownInfo = typeof paths?.markdownPath === 'string' && paths.markdownPath !== ''
|
|
157
|
+
? await statImpl(paths.markdownPath).catch(() => null)
|
|
158
|
+
: null
|
|
159
|
+
const contentInfo = typeof paths?.contentPath === 'string' && paths.contentPath !== ''
|
|
160
|
+
? await statImpl(paths.contentPath).catch(() => null)
|
|
161
|
+
: null
|
|
162
|
+
return { markdownInfo, contentInfo, revision: outlineInputRevision(markdownInfo, contentInfo) }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 盘上这份目录是不是**当前输入**产出的。
|
|
167
|
+
*
|
|
168
|
+
* 两种判据,按产物有没有身份分:
|
|
169
|
+
* - 头里有 `rev`(本版本写出的)→ 与当前输入身份**相等**才算数。这一条连「mtime 往回改」
|
|
170
|
+
* 都能发现 —— 换回旧文件、从备份还原,时间戳变小但内容也变了;
|
|
171
|
+
* - 头里没有 `rev`(迁移前的同版本文件、手工产物、夹具)→ 退回「目录不早于它的输入」:
|
|
172
|
+
* 输入比目录新就重算。宁可多算一次,也不留一份对不上的目录。
|
|
173
|
+
* - **身份算不出来**(Markdown 已不在)→ 认为盘上这份仍然有效:那是用户手里仅有的一份目录,
|
|
174
|
+
* 删掉它比留一份可能过期的更糟。
|
|
175
|
+
*
|
|
176
|
+
* @param {{revision: string}} parsed 盘上目录的头。
|
|
177
|
+
* @param {{markdownInfo: object|null, contentInfo: object|null, revision: string}} inputs 当前输入。
|
|
178
|
+
* @param {{mtimeMs?: number}} info 目录文件本身的 stat。
|
|
179
|
+
* @returns {boolean}
|
|
180
|
+
*/
|
|
181
|
+
function outlineMatchesInputs(parsed, inputs, info) {
|
|
182
|
+
if (inputs.revision === '') return true
|
|
183
|
+
if (typeof parsed?.revision === 'string' && parsed.revision !== '') return parsed.revision === inputs.revision
|
|
184
|
+
const newest = Math.max(inputs.markdownInfo?.mtimeMs ?? 0, inputs.contentInfo?.mtimeMs ?? 0)
|
|
185
|
+
return (info?.mtimeMs ?? 0) >= newest
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** 按当前代码从 Markdown + 块列表重建目录,并回写文件(写不进去只意味着下次还要再算)。 */
|
|
189
|
+
async function rebuildOutline(resolved, budget, revision) {
|
|
190
|
+
const markdown = await readFileImpl(resolved.markdownPath, 'utf8')
|
|
191
|
+
if (markdown.trim() === '') return { text: '', persisted: false }
|
|
192
|
+
const { blocks } = await contentListOf(resolved)
|
|
193
|
+
const fresh = buildOutline(markdown, budget, blocks)
|
|
194
|
+
const temporary = resolved.outlinePath + '.' + randomUUID() + '.tmp'
|
|
195
|
+
try {
|
|
196
|
+
await writeFileImpl(temporary, outlineFileText(fresh, budget, revision), 'utf8')
|
|
197
|
+
await replaceFileImpl(temporary, resolved.outlinePath)
|
|
198
|
+
return { text: fresh.text, persisted: true }
|
|
199
|
+
} catch { return { text: fresh.text, persisted: false } }
|
|
200
|
+
finally { await rm(temporary, { force: true }).catch(() => {}) }
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* 盘上的章节树,**版本或预算不符时按当前代码重建**。
|
|
205
|
+
*
|
|
206
|
+
* 🔴 章节树在解析时落盘,之后一直照着旧文件读 —— 只改 `buildOutline` 不会让任何一篇
|
|
207
|
+
* 变样。所以文件头记着 OUTLINE_VERSION 与产出时的字节预算;不符就重建并覆盖,
|
|
208
|
+
* 启动迁移覆盖全库;后续读取也核对版本和预算,失败后仍可重试。
|
|
209
|
+
*
|
|
210
|
+
* 文件**不存在**时不算过期信号:没有目录就是没有(读端降级成空串),不凭空造一份。
|
|
211
|
+
*/
|
|
212
|
+
async function outlineOf(resolved, budget) {
|
|
213
|
+
const content = await contentListOf(resolved)
|
|
214
|
+
const key = `${resolved.outlinePath}\u0000${budget}\u0000${content.fingerprint}`
|
|
215
|
+
const cached = outlines.get(key)
|
|
216
|
+
let info
|
|
217
|
+
try { info = await statImpl(resolved.outlinePath) } catch { return { text: resolved.outlineText ?? '' } }
|
|
218
|
+
if (cached !== undefined && cached.mtimeMs === info.mtimeMs && cached.size === info.size
|
|
219
|
+
&& nowImpl() - cached.readAt <= REVISION_TRUST_MS) return cached
|
|
220
|
+
const raw = await readFileImpl(resolved.outlinePath, 'utf8').catch(() => '')
|
|
221
|
+
const parsed = parseOutlineFile(raw)
|
|
222
|
+
const root = content.blocks?.find(block => block.type === 'heading')
|
|
223
|
+
const rootPrefix = (root?.sourceText?.length ?? 0) > 300 ? '- ' + headingTitle(root) + ' [b:' + root.id + ' .. ' : undefined
|
|
224
|
+
const inputs = await revisionInputsOf(resolved)
|
|
225
|
+
if (parsed.version === OUTLINE_VERSION && parsed.budget === budget
|
|
226
|
+
&& (!rootPrefix || parsed.text.split('\n')[0].startsWith(rootPrefix))
|
|
227
|
+
&& outlineMatchesInputs(parsed, inputs, info)) {
|
|
228
|
+
return rememberOutline(key, parsed.text, info)
|
|
229
|
+
}
|
|
230
|
+
const rebuilt = await rebuildOutline(resolved, budget, inputs.revision)
|
|
231
|
+
if (!rebuilt.persisted) return rebuilt
|
|
232
|
+
return rememberOutline(key, rebuilt.text, await statImpl(resolved.outlinePath).catch(() => null))
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function ensureOutline(document, budget = DEFAULT_OUTLINE_BUDGET_BYTES) {
|
|
236
|
+
const resolved = hydrateDocument(document)
|
|
237
|
+
const key = `${resolved.outlinePath}\0${budget}`
|
|
238
|
+
if (pendingOutlines.has(key)) return pendingOutlines.get(key)
|
|
239
|
+
const operation = outlineOf(resolved, budget)
|
|
240
|
+
pendingOutlines.set(key, operation)
|
|
241
|
+
try { return await operation } finally { pendingOutlines.delete(key) }
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Reconcile the whole library once at activation; failures retain the previous complete file. */
|
|
245
|
+
async function migrateOutlines(documents, budget = DEFAULT_OUTLINE_BUDGET_BYTES) {
|
|
246
|
+
const report = { changed: 0, failures: [] }
|
|
247
|
+
for (let start = 0; start < documents.length; start += 4) {
|
|
248
|
+
await Promise.all(documents.slice(start, start + 4).map(async document => {
|
|
249
|
+
try {
|
|
250
|
+
const resolved = hydrateDocument(document)
|
|
251
|
+
if (!resolved.outlinePath || !resolved.markdownPath) return
|
|
252
|
+
const raw = await readFileImpl(resolved.outlinePath, 'utf8').catch(error => {
|
|
253
|
+
if (error.code === 'ENOENT') return undefined
|
|
254
|
+
throw error
|
|
255
|
+
})
|
|
256
|
+
if (raw === undefined) return
|
|
257
|
+
const old = parseOutlineFile(raw)
|
|
258
|
+
// 同版本也可能已经过期(输入的块列表换过),所以还要核对输入身份。
|
|
259
|
+
const info = await statImpl(resolved.outlinePath).catch(() => null)
|
|
260
|
+
if (old.version === OUTLINE_VERSION && old.budget === budget
|
|
261
|
+
&& outlineMatchesInputs(old, await revisionInputsOf(resolved), info)) return
|
|
262
|
+
const result = await ensureOutline(resolved, budget)
|
|
263
|
+
if (result.persisted === false) report.failures.push({ id: document.id, error: '目录无法保存,原文件已保留。' })
|
|
264
|
+
else report.changed++
|
|
265
|
+
} catch (error) { report.failures.push({ id: document.id, error: String(error.message ?? error) }) }
|
|
266
|
+
}))
|
|
267
|
+
}
|
|
268
|
+
return report
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** The `/state` view: the body is only stat-ed, and the outline text comes from cache. */
|
|
272
|
+
async function documentView(document, outlineBudgetBytes = DEFAULT_OUTLINE_BUDGET_BYTES) {
|
|
273
|
+
try {
|
|
274
|
+
const resolved = hydrateDocument(document)
|
|
275
|
+
const info = await statImpl(resolved.markdownPath)
|
|
276
|
+
const outline = await ensureOutline(resolved, outlineBudgetBytes)
|
|
277
|
+
return { ...resolved, outlineText: outline.text.trimEnd(), available: info.isFile() && info.size > 0 }
|
|
278
|
+
} catch { return { ...document, available: false } }
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
return {
|
|
282
|
+
usableDocument,
|
|
283
|
+
documentView,
|
|
284
|
+
ensureOutline,
|
|
285
|
+
migrateOutlines,
|
|
286
|
+
cachedFiles: () => markdowns.size() + outlines.size() + contents.size(),
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** 论文落点上的目录输入身份(工具侧重建目录时用;口径与 {@link createDocumentReader} 内部一致)。 */
|
|
291
|
+
export async function outlineRevisionAt(paths, { statImpl = stat } = {}) {
|
|
292
|
+
const markdownInfo = typeof paths?.markdownPath === 'string' && paths.markdownPath !== ''
|
|
293
|
+
? await statImpl(paths.markdownPath).catch(() => null)
|
|
294
|
+
: null
|
|
295
|
+
const contentInfo = typeof paths?.contentPath === 'string' && paths.contentPath !== ''
|
|
296
|
+
? await statImpl(paths.contentPath).catch(() => null)
|
|
297
|
+
: null
|
|
298
|
+
return outlineInputRevision(markdownInfo, contentInfo)
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* 给盘上目录补上**输入修订身份**(发布之后用)。
|
|
303
|
+
*
|
|
304
|
+
* 发布是一次事务按 markdown → outline → content 的顺序提交的(见 portable.writeAnalysisBundle):
|
|
305
|
+
* 目录写出时后两者的最终 mtime 还不存在,而身份正是从这些 mtime 算的。所以在整批提交完成、
|
|
306
|
+
* manifest 也写完之后再补一次头(只改第一行)。
|
|
307
|
+
*
|
|
308
|
+
* 🔴 只在**这次发布确实写/重算了目录**时调用。目录是旧输入产出的、只是块列表换了,补一个
|
|
309
|
+
* 新身份等于给过期目录盖章 —— 那正是 F38 要消灭的东西,所以调用方要为「写了目录」负责。
|
|
310
|
+
* 写不进去不算失败:下次读取发现身份不符会重建一次,结果一样,只是多算一遍。
|
|
311
|
+
*
|
|
312
|
+
* @param {{markdownPath?: string, outlinePath?: string, contentPath?: string}} resolved 论文落点。
|
|
313
|
+
* @returns {Promise<boolean>} 是否真的改写了文件。
|
|
314
|
+
*/
|
|
315
|
+
export async function stampOutlineRevision(resolved, { statImpl = stat, writeFileImpl = writeFile, replaceFileImpl = replaceStateFile } = {}) {
|
|
316
|
+
const outlinePath = typeof resolved?.outlinePath === 'string' ? resolved.outlinePath : ''
|
|
317
|
+
if (outlinePath === '') return false
|
|
318
|
+
const revision = await outlineRevisionAt(resolved, { statImpl })
|
|
319
|
+
if (revision === '') return false
|
|
320
|
+
const raw = await readFile(outlinePath, 'utf8').catch(() => '')
|
|
321
|
+
if (raw === '') return false
|
|
322
|
+
const parsed = parseOutlineFile(raw)
|
|
323
|
+
if (parsed.version !== OUTLINE_VERSION || parsed.revision === revision) return false
|
|
324
|
+
const temporary = outlinePath + '.' + randomUUID() + '.tmp'
|
|
325
|
+
try {
|
|
326
|
+
await writeFileImpl(temporary, outlineFileText({ text: parsed.text }, parsed.budget, revision), 'utf8')
|
|
327
|
+
await replaceFileImpl(temporary, outlinePath)
|
|
328
|
+
return true
|
|
329
|
+
} catch { return false } finally { await rm(temporary, { force: true }).catch(() => {}) }
|
|
330
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import { mkdir } from 'node:fs/promises'
|
|
3
|
+
import { dirname, resolve } from 'node:path'
|
|
4
|
+
import { indexDatabasePath } from './store-paths.js'
|
|
5
|
+
|
|
6
|
+
const active = new AsyncLocalStorage()
|
|
7
|
+
const DATABASE_VERSION = 1
|
|
8
|
+
|
|
9
|
+
/** Connections belong to one operation and close on every success, failure and HMR generation. */
|
|
10
|
+
export async function withIndexDatabase(root, operation, write = false) {
|
|
11
|
+
const path = resolve(indexDatabasePath(root))
|
|
12
|
+
const current = active.getStore()
|
|
13
|
+
if (current?.path === path) {
|
|
14
|
+
if (write && !current.write) throw new Error('Cannot write through a read-only search transaction')
|
|
15
|
+
return operation(current.db, current.prepare)
|
|
16
|
+
}
|
|
17
|
+
// Optional at startup: a host without node:sqlite still registers all paper tools and scans.
|
|
18
|
+
const { DatabaseSync } = await import('node:sqlite')
|
|
19
|
+
if (write) await mkdir(dirname(path), { recursive: true })
|
|
20
|
+
const db = new DatabaseSync(path, { readOnly: !write })
|
|
21
|
+
const statements = new Map()
|
|
22
|
+
const prepare = sql => {
|
|
23
|
+
if (!statements.has(sql)) statements.set(sql, db.prepare(sql))
|
|
24
|
+
return statements.get(sql)
|
|
25
|
+
}
|
|
26
|
+
let transaction = false
|
|
27
|
+
try {
|
|
28
|
+
db.exec('PRAGMA busy_timeout=1000')
|
|
29
|
+
const version = db.prepare('PRAGMA user_version').get().user_version
|
|
30
|
+
if (version !== 0 && version !== DATABASE_VERSION) throw new Error('Unsupported paper search database version')
|
|
31
|
+
if (write) {
|
|
32
|
+
db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL')
|
|
33
|
+
db.exec(`CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;
|
|
34
|
+
CREATE TABLE IF NOT EXISTS documents (doc_no INTEGER PRIMARY KEY, value TEXT NOT NULL);
|
|
35
|
+
CREATE TABLE IF NOT EXISTS postings (
|
|
36
|
+
term TEXT NOT NULL, doc_no INTEGER NOT NULL, block_index INTEGER NOT NULL CHECK(block_index >= 0),
|
|
37
|
+
tf INTEGER NOT NULL CHECK(tf > 0), PRIMARY KEY(term, doc_no, block_index)
|
|
38
|
+
) WITHOUT ROWID;
|
|
39
|
+
CREATE INDEX IF NOT EXISTS postings_by_document ON postings(doc_no);
|
|
40
|
+
PRAGMA user_version=1;`)
|
|
41
|
+
}
|
|
42
|
+
db.exec(write ? 'BEGIN IMMEDIATE' : 'BEGIN')
|
|
43
|
+
transaction = true
|
|
44
|
+
const value = await active.run({ path, db, prepare, write }, () => operation(db, prepare))
|
|
45
|
+
db.exec('COMMIT')
|
|
46
|
+
transaction = false
|
|
47
|
+
return value
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (transaction) db.exec('ROLLBACK')
|
|
50
|
+
throw error
|
|
51
|
+
} finally {
|
|
52
|
+
db.close()
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function databaseRead(root, operation) {
|
|
57
|
+
return withIndexDatabase(root, operation, false)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function databaseWrite(root, operation) {
|
|
61
|
+
return withIndexDatabase(root, operation, true)
|
|
62
|
+
}
|