dsh-pdf-workbench 1.4.1 → 1.5.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/README.md +108 -78
- package/assets/screenshot-hero.jpg +0 -0
- package/assets/screenshot-settings-data.jpg +0 -0
- package/assets/screenshot-settings-env.jpg +0 -0
- package/assets/screenshot-settings-mode.jpg +0 -0
- package/assets/screenshot-settings-reading.jpg +0 -0
- package/assets/screenshot-shelf.jpg +0 -0
- package/client.js +4106 -469
- package/docs/LAYOUT.md +56 -0
- package/docs/RELEASE.md +8 -0
- package/docs/TESTING.md +16 -0
- package/docs/ci.md +18 -13
- package/docs/copy/templates.md +4 -4
- package/docs/decisions.md +119 -0
- package/docs/features.md +14 -8
- package/docs/requirements/2026-11-25-v1.5/346/224/271/350/277/233/351/234/200/346/261/202.md +622 -0
- package/docs/roles/{release-manager.md → ci.md} +37 -47
- package/docs/roles/programmer.md +45 -59
- package/docs/roles/requirements.md +68 -0
- package/docs/todo.md +590 -32
- package/index.js +337 -1
- package/package.json +1 -1
- package/screenshots.json +6 -4
- package/src/host/backup.js +172 -33
- package/src/host/book-wizard.js +454 -0
- package/src/host/digest.js +4 -0
- package/src/host/engine.js +88 -0
- package/src/host/exports.js +159 -0
- package/src/host/http.js +28 -1
- package/src/host/imports.js +650 -0
- package/src/host/index-source.js +117 -11
- package/src/host/library-export.js +162 -0
- package/src/host/pdf-source.js +6 -2
- package/src/host/routes.js +1020 -120
- package/src/host/shortcut.js +238 -0
- package/src/host/storage.js +421 -0
- package/src/host/translate-blocks.js +49 -45
- package/src/host/translate-job.js +37 -10
- package/src/host/translate.js +19 -45
- package/src/host/translation-cache.js +209 -0
- package/src/host/typst-install.js +132 -0
- package/src/host/zip.js +486 -4
- package/tools/latex_to_typst.py +1353 -0
- package/tools/md2overlay.py +147 -152
- package/tools/md2overlay_typst.py +312 -0
- package/tools/md2typst.py +818 -0
- package/tools/overlay_layout.py +332 -0
- package/tools/pdf_blocks.py +82 -10
- package/tools/realign_overlay.py +4 -1
- package/tools/rebuild_overlay.py +3 -1
- package/tools/split_pdf.py +158 -0
- package/tools/typst_runtime.py +98 -0
- package/vendor/katex/LICENSE +21 -0
- package/vendor/katex/fonts/KaTeX_AMS-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-Italic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Math-Italic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Script-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size1-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size2-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size3-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size4-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
- package/vendor/katex/katex.min.css +1 -0
- package/vendor/katex/katex.min.js +1 -0
- package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +9 -1
- package/docs/boss-handover.md +0 -84
- package/docs/roles/auditor.md +0 -123
- package/docs/roles/boss.md +0 -162
- package/docs/roles/code-reviewer.md +0 -132
- package/docs/roles/feature-inventory.md +0 -119
- package/docs/roles/feedback-collector.md +0 -105
- package/docs/roles/tester.md +0 -140
- package/docs/roles/ui-copywriter.md +0 -122
- package/src/host/book-import.js +0 -98
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Book-package import: inspect a PDF package (with an optional notes package)
|
|
3
|
+
* and import only the books the user ticked.
|
|
4
|
+
*
|
|
5
|
+
* A PDF package is a ZIP that may mix both shapes the library uses:
|
|
6
|
+
* - split books: `<书id>/<章>.pdf` (a leading `分片/` is ignored), one book per
|
|
7
|
+
* first-level folder;
|
|
8
|
+
* - whole books: a loose `<书名>.pdf` (a leading `整本/` is ignored), one book
|
|
9
|
+
* per file.
|
|
10
|
+
* A notes package is either a library export (`manifest.json` with
|
|
11
|
+
* `pdfdesk-library-export`, paths under `.pdfdesk/…`) or a migration backup
|
|
12
|
+
* (`format: 1`, paths under `libraries/<libId>/.pdfdesk/…`).
|
|
13
|
+
*
|
|
14
|
+
* Packages are read entry by entry, never as one buffered archive: inspecting
|
|
15
|
+
* only looks at names, sizes and each PDF's header, content hashes are streamed,
|
|
16
|
+
* and importing streams each PDF into a temp file in its destination folder
|
|
17
|
+
* before the atomic rename.
|
|
18
|
+
*
|
|
19
|
+
* Existing books are detected by content (size + sha256) against the active
|
|
20
|
+
* library's PDFs; such a book keeps its PDF untouched and only its notes can be
|
|
21
|
+
* written (merge, overwrite or skip, per book).
|
|
22
|
+
*
|
|
23
|
+
* @module dsh-pdf-workbench/book-wizard
|
|
24
|
+
*/
|
|
25
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
26
|
+
import { createReadStream, createWriteStream } from 'node:fs'
|
|
27
|
+
import { mkdir, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
28
|
+
import { dirname, extname, join } from 'node:path'
|
|
29
|
+
import { Transform } from 'node:stream'
|
|
30
|
+
|
|
31
|
+
import { walkFiles } from './backup.js'
|
|
32
|
+
import { MAX_ARCHIVE_FILE_BYTES } from './imports.js'
|
|
33
|
+
import { listZipEntries, pipeZipEntry, readZipEntryBuffer, readZipEntryHead, safeZipName } from './zip.js'
|
|
34
|
+
|
|
35
|
+
/** Categories of per-book data a notes package may carry. */
|
|
36
|
+
export const NOTE_CATEGORIES = ['annotations', 'questions', 'attachments']
|
|
37
|
+
|
|
38
|
+
/** PDF header, per ISO 32000. */
|
|
39
|
+
const PDF_SIGNATURE = '%PDF-'
|
|
40
|
+
|
|
41
|
+
/** Content hash used for "same PDF" detection, streamed so a book is never buffered. */
|
|
42
|
+
function hashFileStream(path) {
|
|
43
|
+
return new Promise((resolve, reject) => {
|
|
44
|
+
const hash = createHash('sha256')
|
|
45
|
+
createReadStream(path)
|
|
46
|
+
.on('data', chunk => hash.update(chunk))
|
|
47
|
+
.on('error', reject)
|
|
48
|
+
.on('end', () => resolve(hash.digest('hex')))
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A safe book id (folder name under `分片/`).
|
|
54
|
+
* @param {string} raw - proposed id.
|
|
55
|
+
* @returns {string} the id, or '' when unusable.
|
|
56
|
+
*/
|
|
57
|
+
export function bookIdOf(raw) {
|
|
58
|
+
const value = String(raw ?? '').trim()
|
|
59
|
+
if (value === '' || value === '.' || value === '..') return ''
|
|
60
|
+
if (/[\\/:*?"<>|\u0000-\u001f]/.test(value)) return ''
|
|
61
|
+
if (value.startsWith('.')) return ''
|
|
62
|
+
return value.slice(0, 120)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The one grouping rule for PDF packages, shared by the buffered helper and the
|
|
67
|
+
* streaming wizard path so they cannot drift.
|
|
68
|
+
*
|
|
69
|
+
* @param {Iterable<{ name: string, bytes: number, isPdf: boolean, payload: unknown }>} items - every archive entry, in directory order, with its PDF-header verdict.
|
|
70
|
+
* @returns {{ books: Array<{ id: string, kind: 'split'|'whole', files: Array<{ name: string, bytes: number, payload: unknown }> }>, warnings: string[] }} the books.
|
|
71
|
+
*/
|
|
72
|
+
function groupPdfEntries(items) {
|
|
73
|
+
const books = new Map()
|
|
74
|
+
const warnings = []
|
|
75
|
+
for (const item of items) {
|
|
76
|
+
const entryName = item.name
|
|
77
|
+
if (entryName.endsWith('/')) continue
|
|
78
|
+
const safe = safeZipName(entryName)
|
|
79
|
+
const parts = safe.split('/').filter(part => part !== '')
|
|
80
|
+
const leaf = parts[parts.length - 1]
|
|
81
|
+
if (extname(leaf).toLowerCase() !== '.pdf') {
|
|
82
|
+
warnings.push(`跳过非 PDF:${safe}`)
|
|
83
|
+
continue
|
|
84
|
+
}
|
|
85
|
+
if (!item.isPdf) {
|
|
86
|
+
warnings.push(`跳过假 PDF(文件头不是 ${PDF_SIGNATURE}):${safe}`)
|
|
87
|
+
continue
|
|
88
|
+
}
|
|
89
|
+
// Ignore the library's own zone wrappers so both `书/章.pdf` and
|
|
90
|
+
// `分片/书/章.pdf` describe the same book.
|
|
91
|
+
const rest = parts.length > 1 && (parts[0] === '分片' || parts[0] === '整本') ? parts.slice(1) : parts
|
|
92
|
+
const split = rest.length >= 2
|
|
93
|
+
const rawId = split ? rest[0] : leaf.replace(/\.pdf$/i, '')
|
|
94
|
+
const id = bookIdOf(rawId)
|
|
95
|
+
if (id === '') {
|
|
96
|
+
warnings.push(`书名不合法,已跳过:${safe}`)
|
|
97
|
+
continue
|
|
98
|
+
}
|
|
99
|
+
if (!books.has(id)) books.set(id, { id, kind: split ? 'split' : 'whole', files: [] })
|
|
100
|
+
const book = books.get(id)
|
|
101
|
+
if (book.kind === 'whole' && split) {
|
|
102
|
+
book.kind = 'split'
|
|
103
|
+
warnings.push(`《${id}》同时有整本与章节文件,按分片书处理`)
|
|
104
|
+
}
|
|
105
|
+
if (!split && book.kind === 'split') {
|
|
106
|
+
warnings.push(`《${id}》的散装文件已忽略(书内已有章节文件)`)
|
|
107
|
+
continue
|
|
108
|
+
}
|
|
109
|
+
book.files.push({ name: leaf, bytes: item.bytes, payload: item.payload })
|
|
110
|
+
}
|
|
111
|
+
return { books: [...books.values()], warnings }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Group one PDF archive into books.
|
|
116
|
+
* @param {Map<string, Buffer>} entries - archive entries.
|
|
117
|
+
* @returns {{ books: Array<{ id: string, kind: 'split'|'whole', files: Array<{ name: string, bytes: number, data: Buffer }> }>, warnings: string[] }} the books.
|
|
118
|
+
*/
|
|
119
|
+
export function booksFromPdfEntries(entries) {
|
|
120
|
+
const items = []
|
|
121
|
+
for (const [entryName, data] of entries) {
|
|
122
|
+
items.push({
|
|
123
|
+
name: entryName,
|
|
124
|
+
bytes: data.length,
|
|
125
|
+
isPdf: data.length >= PDF_SIGNATURE.length && data.subarray(0, PDF_SIGNATURE.length).toString('latin1') === PDF_SIGNATURE,
|
|
126
|
+
payload: data,
|
|
127
|
+
})
|
|
128
|
+
}
|
|
129
|
+
const { books, warnings } = groupPdfEntries(items)
|
|
130
|
+
return {
|
|
131
|
+
books: books.map(book => ({
|
|
132
|
+
id: book.id,
|
|
133
|
+
kind: book.kind,
|
|
134
|
+
files: book.files.map(file => ({ name: file.name, bytes: file.bytes, data: file.payload })),
|
|
135
|
+
})),
|
|
136
|
+
warnings,
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Whether a listed entry can be a PDF, from its leaf name only.
|
|
142
|
+
* @param {string} entryName - normalized archive name.
|
|
143
|
+
* @returns {boolean} true when the leaf ends in `.pdf`.
|
|
144
|
+
*/
|
|
145
|
+
function looksLikePdfName(entryName) {
|
|
146
|
+
const leaf = String(entryName).split('/').pop() ?? ''
|
|
147
|
+
return extname(leaf).toLowerCase() === '.pdf'
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Group a listed archive into books without reading any PDF body: the header is
|
|
152
|
+
* peeked through the stream, and the payload is the entry itself (`listZipEntries`
|
|
153
|
+
* shape), which `pipeZipEntry` can later unpack one at a time.
|
|
154
|
+
* @param {string} archivePath - archive on disk.
|
|
155
|
+
* @param {Array<object>} listing - `listZipEntries` result.
|
|
156
|
+
* @returns {Promise<{ books: Array<{ id: string, kind: 'split'|'whole', files: Array<{ name: string, bytes: number, entry: object }> }>, warnings: string[] }>} the books.
|
|
157
|
+
*/
|
|
158
|
+
async function booksFromListing(archivePath, listing) {
|
|
159
|
+
const items = []
|
|
160
|
+
for (const entry of listing) {
|
|
161
|
+
let isPdf = false
|
|
162
|
+
if (looksLikePdfName(entry.name) && entry.size >= PDF_SIGNATURE.length) {
|
|
163
|
+
const head = await readZipEntryHead(archivePath, entry, PDF_SIGNATURE.length)
|
|
164
|
+
isPdf = head.length === PDF_SIGNATURE.length && head.toString('latin1') === PDF_SIGNATURE
|
|
165
|
+
}
|
|
166
|
+
items.push({ name: entry.name, bytes: entry.size, isPdf, payload: entry })
|
|
167
|
+
}
|
|
168
|
+
const { books, warnings } = groupPdfEntries(items)
|
|
169
|
+
return {
|
|
170
|
+
books: books.map(book => ({
|
|
171
|
+
id: book.id,
|
|
172
|
+
kind: book.kind,
|
|
173
|
+
files: book.files.map(file => ({ name: file.name, bytes: file.bytes, entry: file.payload })),
|
|
174
|
+
})),
|
|
175
|
+
warnings,
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Where one entry belongs in a notes tree, or null when it is not a note.
|
|
181
|
+
* @param {string} entryName - archive name.
|
|
182
|
+
* @returns {{ id: string, category: string, path: string } | null} the note destination.
|
|
183
|
+
*/
|
|
184
|
+
function noteTargetOf(entryName) {
|
|
185
|
+
const safe = safeZipName(entryName)
|
|
186
|
+
const parts = safe.split('/').filter(part => part !== '')
|
|
187
|
+
let rest = parts
|
|
188
|
+
// Migration backup: libraries/<libId>/.pdfdesk/...
|
|
189
|
+
if (rest[0] === 'libraries') {
|
|
190
|
+
const pdfdeskAt = rest.indexOf('.pdfdesk')
|
|
191
|
+
if (pdfdeskAt < 2) return null
|
|
192
|
+
rest = rest.slice(pdfdeskAt)
|
|
193
|
+
}
|
|
194
|
+
if (rest[0] !== '.pdfdesk' || rest.length < 4) return null
|
|
195
|
+
const category = rest[1]
|
|
196
|
+
if (!NOTE_CATEGORIES.includes(category)) return null
|
|
197
|
+
const id = bookIdOf(rest[2])
|
|
198
|
+
if (id === '') return null
|
|
199
|
+
const path = rest.slice(3).join('/')
|
|
200
|
+
if (path === '') return null
|
|
201
|
+
return { id, category, path }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Per-book note data from a notes package.
|
|
206
|
+
* @param {Map<string, Buffer>} entries - archive entries.
|
|
207
|
+
* @returns {Map<string, Array<{ category: string, path: string, data: Buffer }>>} notes by book id.
|
|
208
|
+
*/
|
|
209
|
+
export function notesFromEntries(entries) {
|
|
210
|
+
const notes = new Map()
|
|
211
|
+
for (const [entryName, data] of entries) {
|
|
212
|
+
const target = noteTargetOf(entryName)
|
|
213
|
+
if (target === null) continue
|
|
214
|
+
if (!notes.has(target.id)) notes.set(target.id, [])
|
|
215
|
+
notes.get(target.id).push({ category: target.category, path: target.path, data })
|
|
216
|
+
}
|
|
217
|
+
return notes
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Read the note entries of a listed package. Notes are small JSON/image files by
|
|
222
|
+
* design, so they stay buffered (the pure helpers take buffers); a single entry
|
|
223
|
+
* is still capped, so a lying package cannot exhaust memory here.
|
|
224
|
+
* @param {string} archivePath - notes package on disk.
|
|
225
|
+
* @param {Array<object>} listing - `listZipEntries` result.
|
|
226
|
+
* @returns {Promise<Map<string, Array<{ category: string, path: string, data: Buffer }>>>} notes by book id.
|
|
227
|
+
*/
|
|
228
|
+
async function notesFromListing(archivePath, listing) {
|
|
229
|
+
const notes = new Map()
|
|
230
|
+
for (const entry of listing) {
|
|
231
|
+
const target = noteTargetOf(entry.name)
|
|
232
|
+
if (target === null) continue
|
|
233
|
+
const data = await readZipEntryBuffer(archivePath, entry, MAX_ARCHIVE_FILE_BYTES)
|
|
234
|
+
if (!notes.has(target.id)) notes.set(target.id, [])
|
|
235
|
+
notes.get(target.id).push({ category: target.category, path: target.path, data })
|
|
236
|
+
}
|
|
237
|
+
return notes
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Hash one archive entry by streaming it through a discarding sink.
|
|
242
|
+
* @param {string} archivePath - archive on disk.
|
|
243
|
+
* @param {object} entry - one `listZipEntries` entry.
|
|
244
|
+
* @returns {Promise<string>} hex sha256 of the entry's content.
|
|
245
|
+
*/
|
|
246
|
+
async function hashEntry(archivePath, entry) {
|
|
247
|
+
const sink = new Transform({
|
|
248
|
+
transform(_chunk, _encoding, callback) {
|
|
249
|
+
callback()
|
|
250
|
+
},
|
|
251
|
+
})
|
|
252
|
+
const result = await pipeZipEntry(archivePath, entry, sink)
|
|
253
|
+
return result.sha256
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Hash one library PDF only when its size can match; the index keeps the work
|
|
258
|
+
* proportional to the books being imported.
|
|
259
|
+
* @param {string} libraryDir - library root.
|
|
260
|
+
* @returns {Promise<Map<number, Array<{ path: string, hash: string | null }>>>} size → files.
|
|
261
|
+
*/
|
|
262
|
+
async function libraryPdfIndex(libraryDir) {
|
|
263
|
+
const index = new Map()
|
|
264
|
+
const paths = []
|
|
265
|
+
for (const name of await readdir(join(libraryDir, '整本')).catch(() => [])) {
|
|
266
|
+
if (extname(name).toLowerCase() === '.pdf') paths.push(join(libraryDir, '整本', name))
|
|
267
|
+
}
|
|
268
|
+
for (const relative of await walkFiles(join(libraryDir, '分片')).catch(() => [])) {
|
|
269
|
+
if (extname(relative).toLowerCase() === '.pdf') paths.push(join(libraryDir, '分片', relative))
|
|
270
|
+
}
|
|
271
|
+
for (const path of paths) {
|
|
272
|
+
const info = await stat(path).catch(() => null)
|
|
273
|
+
if (info === null || !info.isFile()) continue
|
|
274
|
+
if (!index.has(info.size)) index.set(info.size, [])
|
|
275
|
+
index.get(info.size).push({ path, hash: null })
|
|
276
|
+
}
|
|
277
|
+
return index
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Find an identical file already in the library.
|
|
282
|
+
* @param {Map<number, Array<{ path: string, hash: string | null }>>} index - library index.
|
|
283
|
+
* @param {number} size - candidate size.
|
|
284
|
+
* @param {string} hash - candidate sha256.
|
|
285
|
+
* @returns {Promise<string | null>} the existing path, or null.
|
|
286
|
+
*/
|
|
287
|
+
async function existingFile(index, size, hash) {
|
|
288
|
+
const candidates = index.get(size)
|
|
289
|
+
if (candidates === undefined) return null
|
|
290
|
+
for (const candidate of candidates) {
|
|
291
|
+
if (candidate.hash === null) candidate.hash = await hashFileStream(candidate.path)
|
|
292
|
+
if (candidate.hash === hash) return candidate.path
|
|
293
|
+
}
|
|
294
|
+
return null
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Inspect a PDF package (and an optional notes package).
|
|
299
|
+
* @param {{ archivePath: string, notesPath?: string, libraryDir: string }} options - packages and the active library.
|
|
300
|
+
* @returns {Promise<{ books: Array<object>, notesBooks: string[], warnings: string[], notes: boolean }>} the inspection.
|
|
301
|
+
*/
|
|
302
|
+
export async function inspectBookPack(options) {
|
|
303
|
+
const { books, warnings } = await booksFromListing(options.archivePath, await listZipEntries(options.archivePath))
|
|
304
|
+
let notes = new Map()
|
|
305
|
+
if (typeof options.notesPath === 'string' && options.notesPath !== '') {
|
|
306
|
+
notes = await notesFromListing(options.notesPath, await listZipEntries(options.notesPath))
|
|
307
|
+
}
|
|
308
|
+
const index = await libraryPdfIndex(options.libraryDir)
|
|
309
|
+
const result = []
|
|
310
|
+
for (const book of books) {
|
|
311
|
+
const matched = []
|
|
312
|
+
for (const file of book.files) {
|
|
313
|
+
const hash = await hashEntry(options.archivePath, file.entry)
|
|
314
|
+
const existing = await existingFile(index, file.bytes, hash)
|
|
315
|
+
if (existing !== null) matched.push(existing)
|
|
316
|
+
}
|
|
317
|
+
const bookNotes = notes.get(book.id) ?? []
|
|
318
|
+
result.push({
|
|
319
|
+
id: book.id,
|
|
320
|
+
kind: book.kind,
|
|
321
|
+
files: book.files.map(file => ({ name: file.name, bytes: file.bytes })),
|
|
322
|
+
totalBytes: book.files.reduce((sum, file) => sum + file.bytes, 0),
|
|
323
|
+
existing: matched.length === book.files.length && book.files.length > 0,
|
|
324
|
+
matchedFiles: matched.length,
|
|
325
|
+
notes: bookNotes.length > 0 ? { files: bookNotes.length, bytes: bookNotes.reduce((sum, note) => sum + note.data.length, 0) } : null,
|
|
326
|
+
})
|
|
327
|
+
}
|
|
328
|
+
return {
|
|
329
|
+
books: result,
|
|
330
|
+
notesBooks: [...notes.keys()],
|
|
331
|
+
notes: notes.size > 0,
|
|
332
|
+
warnings,
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Stream one archive entry into the destination folder, then give it a free name
|
|
338
|
+
* under the wizard's `-1…` suffix rule (an identical neighbour is a duplicate).
|
|
339
|
+
* @param {string} targetDir - destination.
|
|
340
|
+
* @param {string} name - file name (a leaf, never a path).
|
|
341
|
+
* @param {string} archivePath - the package the entry lives in.
|
|
342
|
+
* @param {object} entry - one `listZipEntries` entry.
|
|
343
|
+
* @returns {Promise<{ name: string, written: boolean, duplicate: string | null }>} what happened.
|
|
344
|
+
*/
|
|
345
|
+
async function writePdfEntry(targetDir, name, archivePath, entry) {
|
|
346
|
+
await mkdir(targetDir, { recursive: true })
|
|
347
|
+
const extension = extname(name)
|
|
348
|
+
const stem = extension === '' ? name : name.slice(0, -extension.length)
|
|
349
|
+
const temporary = join(targetDir, `.import-${randomUUID()}.pdf`)
|
|
350
|
+
let hash
|
|
351
|
+
try {
|
|
352
|
+
const streamed = await pipeZipEntry(archivePath, entry, createWriteStream(temporary))
|
|
353
|
+
hash = streamed.sha256
|
|
354
|
+
} catch (error) {
|
|
355
|
+
await rm(temporary, { force: true }).catch(() => {})
|
|
356
|
+
throw error
|
|
357
|
+
}
|
|
358
|
+
try {
|
|
359
|
+
for (let counter = 0; counter < 1000; counter += 1) {
|
|
360
|
+
const candidate = counter === 0 ? name : `${stem}-${counter}${extension}`
|
|
361
|
+
const target = join(targetDir, candidate)
|
|
362
|
+
const info = await stat(target).catch(() => null)
|
|
363
|
+
if (info === null) {
|
|
364
|
+
await rename(temporary, target)
|
|
365
|
+
return { name: candidate, written: true, duplicate: null }
|
|
366
|
+
}
|
|
367
|
+
if (await hashFileStream(target) === hash) {
|
|
368
|
+
await rm(temporary, { force: true }).catch(() => {})
|
|
369
|
+
return { name: candidate, written: false, duplicate: candidate }
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
} catch (error) {
|
|
373
|
+
await rm(temporary, { force: true }).catch(() => {})
|
|
374
|
+
throw error
|
|
375
|
+
}
|
|
376
|
+
await rm(temporary, { force: true }).catch(() => {})
|
|
377
|
+
throw new Error(`同名文件太多:${name}`)
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Import the selected books, then their notes per book.
|
|
382
|
+
* @param {{ archivePath: string, notesPath?: string, libraryDir: string, selection: Array<{ id: string, include?: boolean, notes?: 'merge'|'overwrite'|'skip' }> }} options - packages, library and ticked books.
|
|
383
|
+
* @returns {Promise<{ books: Array<object>, warnings: string[] }>} the report.
|
|
384
|
+
*/
|
|
385
|
+
export async function applyBookPack(options) {
|
|
386
|
+
const { books, warnings } = await booksFromListing(options.archivePath, await listZipEntries(options.archivePath))
|
|
387
|
+
const notes = typeof options.notesPath === 'string' && options.notesPath !== ''
|
|
388
|
+
? await notesFromListing(options.notesPath, await listZipEntries(options.notesPath))
|
|
389
|
+
: new Map()
|
|
390
|
+
const wanted = new Map()
|
|
391
|
+
for (const row of Array.isArray(options.selection) ? options.selection : []) {
|
|
392
|
+
if (row === null || typeof row !== 'object' || row.include === false) continue
|
|
393
|
+
const id = bookIdOf(row.id)
|
|
394
|
+
if (id !== '') wanted.set(id, row.notes === 'overwrite' || row.notes === 'skip' ? row.notes : 'merge')
|
|
395
|
+
}
|
|
396
|
+
const report = []
|
|
397
|
+
for (const book of books) {
|
|
398
|
+
if (!wanted.has(book.id)) continue
|
|
399
|
+
const row = { id: book.id, kind: book.kind, imported: [], duplicates: [], skipped: false, notes: null }
|
|
400
|
+
const index = await libraryPdfIndex(options.libraryDir)
|
|
401
|
+
let allExisting = book.files.length > 0
|
|
402
|
+
for (const file of book.files) {
|
|
403
|
+
const hash = await hashEntry(options.archivePath, file.entry)
|
|
404
|
+
const existing = await existingFile(index, file.bytes, hash)
|
|
405
|
+
if (existing === null) allExisting = false
|
|
406
|
+
}
|
|
407
|
+
row.skipped = allExisting
|
|
408
|
+
if (!allExisting) {
|
|
409
|
+
const targetDir = book.kind === 'split' ? join(options.libraryDir, '分片', book.id) : join(options.libraryDir, '整本')
|
|
410
|
+
for (const file of book.files) {
|
|
411
|
+
const result = await writePdfEntry(targetDir, file.name, options.archivePath, file.entry)
|
|
412
|
+
if (result.written) row.imported.push(result.name)
|
|
413
|
+
else row.duplicates.push(result.name)
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
const policy = wanted.get(book.id)
|
|
417
|
+
const bookNotes = notes.get(book.id) ?? []
|
|
418
|
+
if (bookNotes.length > 0 && policy !== 'skip') {
|
|
419
|
+
let written = 0
|
|
420
|
+
let kept = 0
|
|
421
|
+
for (const note of bookNotes) {
|
|
422
|
+
const target = join(options.libraryDir, '.pdfdesk', note.category, book.id, ...note.path.split('/'))
|
|
423
|
+
const exists = await stat(target).catch(() => null)
|
|
424
|
+
if (exists !== null && policy === 'merge') {
|
|
425
|
+
kept += 1
|
|
426
|
+
continue
|
|
427
|
+
}
|
|
428
|
+
await mkdir(dirname(target), { recursive: true })
|
|
429
|
+
const temporary = `${target}.${process.pid}.importing`
|
|
430
|
+
await writeFile(temporary, note.data)
|
|
431
|
+
await rename(temporary, target)
|
|
432
|
+
written += 1
|
|
433
|
+
}
|
|
434
|
+
row.notes = { policy, written, kept }
|
|
435
|
+
} else if (bookNotes.length > 0) {
|
|
436
|
+
row.notes = { policy: 'skip', written: 0, kept: bookNotes.length }
|
|
437
|
+
}
|
|
438
|
+
report.push(row)
|
|
439
|
+
}
|
|
440
|
+
const selected = [...wanted.keys()]
|
|
441
|
+
for (const id of selected) {
|
|
442
|
+
if (!books.some(book => book.id === id)) warnings.push(`选择的书不在包里:${id}`)
|
|
443
|
+
}
|
|
444
|
+
return { books: report, warnings }
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Remove a staged upload once the wizard is done with it.
|
|
449
|
+
* @param {string} path - staged file.
|
|
450
|
+
* @returns {Promise<void>}
|
|
451
|
+
*/
|
|
452
|
+
export async function discardStage(path) {
|
|
453
|
+
await rm(path, { force: true }).catch(() => {})
|
|
454
|
+
}
|
package/src/host/digest.js
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* @module dsh-pdf-workbench/digest
|
|
15
15
|
*/
|
|
16
16
|
import { mkdir, writeFile } from 'node:fs/promises'
|
|
17
|
+
import { randomUUID } from 'node:crypto'
|
|
17
18
|
import { join } from 'node:path'
|
|
18
19
|
|
|
19
20
|
/** Characters of transcript sent to the model; longer chapters are cut. */
|
|
@@ -126,6 +127,9 @@ export async function summarize(selection, stream, input) {
|
|
|
126
127
|
system: SYSTEM,
|
|
127
128
|
messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
|
|
128
129
|
maxTokens: 2400,
|
|
130
|
+
// Same routing key the translation channel carries: OpenCode requires its
|
|
131
|
+
// `x-opencode-session` header and DSH fills it from this field only.
|
|
132
|
+
sessionId: `session-pdfdesk-digest-${randomUUID()}`,
|
|
129
133
|
})
|
|
130
134
|
for await (const chunk of chunks) {
|
|
131
135
|
if (chunk === null || typeof chunk !== 'object') continue
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which typesetting kernel the workbench uses for the translation products.
|
|
3
|
+
*
|
|
4
|
+
* v1.5 D replaced the LaTeX overlay/reading kernels with Typst. The engine is
|
|
5
|
+
* resolved once per Host start: an explicit `MATH_DESK_TYPST` (or a copy under
|
|
6
|
+
* `tools/typst/`, or `typst` on PATH) enables Typst when both Typst scripts are
|
|
7
|
+
* present; otherwise the LaTeX kernels stay in charge so the plugin still works
|
|
8
|
+
* on a machine without Typst. `MATH_DESK_ENGINE=latex` forces the old path.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-pdf-workbench/engine
|
|
11
|
+
*/
|
|
12
|
+
import { existsSync } from 'node:fs'
|
|
13
|
+
import { delimiter, join } from 'node:path'
|
|
14
|
+
import { probeVersion } from './typst-install.js'
|
|
15
|
+
|
|
16
|
+
const TYPST_NAMES = ['typst.exe', 'typst']
|
|
17
|
+
|
|
18
|
+
function onPath(name) {
|
|
19
|
+
for (const entry of String(process.env.PATH ?? '').split(delimiter)) {
|
|
20
|
+
const dir = entry.trim()
|
|
21
|
+
if (dir === '') continue
|
|
22
|
+
const candidate = join(dir, name)
|
|
23
|
+
if (existsSync(candidate)) return candidate
|
|
24
|
+
}
|
|
25
|
+
return ''
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Absolute path to a Typst executable, or '' when none is installed. */
|
|
29
|
+
export function findTypst(toolsDir) {
|
|
30
|
+
return locateTypst(toolsDir).path
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Where the binary came from, so the settings page can explain a fallback.
|
|
35
|
+
* @param {string} toolsDir - absolute path of the bundled `tools/`.
|
|
36
|
+
* @returns {{ path: string, source: 'env'|'tools'|'local'|'path'|'' }} the chosen copy.
|
|
37
|
+
*/
|
|
38
|
+
export function locateTypst(toolsDir) {
|
|
39
|
+
const explicit = String(process.env.MATH_DESK_TYPST ?? '').trim()
|
|
40
|
+
if (explicit !== '' && existsSync(explicit)) return { path: explicit, source: 'env' }
|
|
41
|
+
for (const name of TYPST_NAMES) {
|
|
42
|
+
const local = join(toolsDir, 'typst', name)
|
|
43
|
+
if (existsSync(local)) return { path: local, source: 'tools' }
|
|
44
|
+
}
|
|
45
|
+
// A per-user install keeps the 52 MB binary out of the plugin package; this is
|
|
46
|
+
// where a manual/on-demand install is expected to land.
|
|
47
|
+
const localAppData = String(process.env.LOCALAPPDATA ?? '').trim()
|
|
48
|
+
if (localAppData !== '') {
|
|
49
|
+
for (const name of TYPST_NAMES) {
|
|
50
|
+
const perUser = join(localAppData, 'dsh-pdf-workbench', 'typst', name)
|
|
51
|
+
if (existsSync(perUser)) return { path: perUser, source: 'local' }
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
for (const name of TYPST_NAMES) {
|
|
55
|
+
const found = onPath(name)
|
|
56
|
+
if (found !== '') return { path: found, source: 'path' }
|
|
57
|
+
}
|
|
58
|
+
return { path: '', source: '' }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Resolve the engine and the two scripts that belong to it.
|
|
63
|
+
* @param {string} toolsDir - absolute path of the bundled `tools/`.
|
|
64
|
+
* @returns {{ engine: 'typst'|'latex', typst: string, overlayScript: string, readingScript: string, overlayName: string, env: Record<string,string> }} the choice.
|
|
65
|
+
*/
|
|
66
|
+
export function resolveTypeset(toolsDir) {
|
|
67
|
+
const requested = String(process.env.MATH_DESK_ENGINE ?? 'auto').trim().toLowerCase()
|
|
68
|
+
const found = locateTypst(toolsDir)
|
|
69
|
+
const typst = found.path
|
|
70
|
+
const typstReady = typst !== ''
|
|
71
|
+
&& existsSync(join(toolsDir, 'md2overlay_typst.py'))
|
|
72
|
+
&& existsSync(join(toolsDir, 'md2typst.py'))
|
|
73
|
+
const useTypst = typstReady && requested !== 'latex'
|
|
74
|
+
return {
|
|
75
|
+
engine: useTypst ? 'typst' : 'latex',
|
|
76
|
+
typst: useTypst ? typst : '',
|
|
77
|
+
typstVersion: useTypst ? probeVersion(typst) : '',
|
|
78
|
+
// Why Typst is not in charge, for the settings row: forced, missing, or the
|
|
79
|
+
// bundled scripts are absent (an old package).
|
|
80
|
+
typstSource: useTypst ? found.source : requested === 'latex' ? 'forced' : typst === '' ? 'missing' : 'incomplete',
|
|
81
|
+
overlayScript: join(toolsDir, useTypst ? 'md2overlay_typst.py' : 'md2overlay.py'),
|
|
82
|
+
readingScript: join(toolsDir, useTypst ? 'md2typst.py' : 'md2tex.py'),
|
|
83
|
+
overlayName: useTypst ? 'md2overlay_typst.py' : 'md2overlay.py',
|
|
84
|
+
// The Python tools resolve Typst themselves; a copy far from tools/typst
|
|
85
|
+
// (for example the tests' .dsh-scratch install) is handed over explicitly.
|
|
86
|
+
env: useTypst ? { MATH_DESK_TYPST: typst } : {},
|
|
87
|
+
}
|
|
88
|
+
}
|