dsh-pdf-workbench 1.3.4 → 1.4.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 +143 -117
- package/assets/screenshot-attachments.jpg +0 -0
- package/assets/screenshot-canvas.jpg +0 -0
- package/assets/screenshot-questions.jpg +0 -0
- package/assets/screenshot-settings-data.jpg +0 -0
- package/assets/screenshot-settings-mode.jpg +0 -0
- package/assets/screenshot-settings-reading.jpg +0 -0
- package/client.js +6243 -974
- package/docs/DETAIL.md +1 -69
- package/docs/RELEASE.md +207 -58
- package/docs/SIDE-PREVIEW.md +5 -1
- package/docs/boss-handover.md +84 -0
- package/docs/ci.md +159 -0
- package/docs/copy/templates.md +110 -0
- package/docs/copy/terms.md +62 -0
- package/docs/decisions.md +325 -0
- package/docs/features.md +55 -0
- package/docs/feedback/.gitkeep +0 -0
- package/docs/preview.svg +86 -0
- package/docs/requirements/.gitkeep +0 -0
- package/docs/reviews/.gitkeep +0 -0
- package/docs/reviews/T-20261124-01.md +180 -0
- package/docs/reviews/T-20261124-03.md +85 -0
- package/docs/reviews/T-20261124-04.md +106 -0
- package/docs/reviews/T-20261124-05.md +94 -0
- package/docs/reviews/T-20261124-07.md +115 -0
- package/docs/reviews/T-20261124-08.md +292 -0
- package/docs/reviews/T-20261124-09.md +112 -0
- package/docs/reviews/T-20261124-10.md +112 -0
- package/docs/roles/auditor.md +123 -0
- package/docs/roles/boss.md +162 -0
- package/docs/roles/code-reviewer.md +132 -0
- package/docs/roles/feature-inventory.md +119 -0
- package/docs/roles/feedback-collector.md +105 -0
- package/docs/roles/programmer.md +112 -0
- package/docs/roles/release-manager.md +108 -0
- package/docs/roles/tester.md +140 -0
- package/docs/roles/ui-copywriter.md +122 -0
- package/docs/tests/.gitkeep +0 -0
- package/docs/tests/T-20261124-01.md +146 -0
- package/docs/tests/T-20261124-03.md +81 -0
- package/docs/tests/T-20261124-04.md +51 -0
- package/docs/tests/T-20261124-05.md +51 -0
- package/docs/tests/T-20261124-07.md +60 -0
- package/docs/tests/T-20261124-08.md +61 -0
- package/docs/tests/T-20261124-09.md +60 -0
- package/docs/tests/T-20261124-10.md +61 -0
- package/docs/todo.md +277 -0
- package/icon.svg +6 -5
- package/index.js +8 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +1 -1
- package/screenshots.json +6 -1
- package/src/host/artifacts.js +31 -3
- package/src/host/attachments.js +159 -0
- package/src/host/backup.js +457 -0
- package/src/host/base-session.js +146 -0
- package/src/host/book-import.js +98 -0
- package/src/host/chapter-sessions.js +154 -0
- package/src/host/chapter-text.js +91 -0
- package/src/host/fonts.js +190 -0
- package/src/host/pdf-stream.js +168 -0
- package/src/host/ppt.js +153 -0
- package/src/host/print.js +191 -0
- package/src/host/questions.js +186 -0
- package/src/host/routes.js +661 -25
- package/src/host/state.js +1 -1
- package/src/host/zip.js +186 -0
- package/tools/pdf_text.py +34 -0
- package/vendor/fonts/zhhand/Xiaolai-Regular.ttf +0 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Import a user-supplied PDF archive into one library folder. The archive is
|
|
3
|
+
* read in memory (store/deflate), every entry is path-checked, and name clashes
|
|
4
|
+
* follow the same merge/overwrite/skip policy as the migration import.
|
|
5
|
+
* @module dsh-pdf-workbench/book-import
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises'
|
|
9
|
+
import { basename, extname, join } from 'node:path'
|
|
10
|
+
|
|
11
|
+
import { readZip, safeZipName } from './zip.js'
|
|
12
|
+
|
|
13
|
+
/** Per-file ceiling for a book PDF. */
|
|
14
|
+
export const MAX_BOOK_PDF_BYTES = 2 * 1024 * 1024 * 1024
|
|
15
|
+
/** Total uncompressed ceiling for one archive. */
|
|
16
|
+
export const MAX_BOOK_ARCHIVE_BYTES = 4 * 1024 * 1024 * 1024
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Pick a free file name by appending `-1`, `-2`, ...
|
|
20
|
+
* @param {string} dir - destination folder.
|
|
21
|
+
* @param {string} name - wanted base name.
|
|
22
|
+
* @returns {Promise<string>} an unused name.
|
|
23
|
+
*/
|
|
24
|
+
async function freeName(dir, name) {
|
|
25
|
+
const extension = extname(name)
|
|
26
|
+
const stem = extension === '' ? name : name.slice(0, -extension.length)
|
|
27
|
+
let candidate = name
|
|
28
|
+
let counter = 0
|
|
29
|
+
while (await stat(join(dir, candidate)).catch(() => null) !== null) {
|
|
30
|
+
counter += 1
|
|
31
|
+
candidate = `${stem}-${counter}${extension}`
|
|
32
|
+
if (counter > 999) throw new Error(`同名文件太多:${name}`)
|
|
33
|
+
}
|
|
34
|
+
return candidate
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Import PDFs from a ZIP into `targetDir`.
|
|
39
|
+
* @param {{ archivePath: string, targetDir: string, strategy?: 'merge'|'overwrite'|'skip' }} options - source, destination and conflict policy.
|
|
40
|
+
* @returns {Promise<{ targetDir: string, imported: string[], renamed: string[], skipped: string[], warnings: string[] }>} the report.
|
|
41
|
+
*/
|
|
42
|
+
export async function importBookArchive(options) {
|
|
43
|
+
const strategy = options.strategy === 'overwrite' || options.strategy === 'skip' ? options.strategy : 'merge'
|
|
44
|
+
const bytes = await readFile(options.archivePath)
|
|
45
|
+
const entries = readZip(bytes)
|
|
46
|
+
const targetDir = options.targetDir
|
|
47
|
+
await mkdir(targetDir, { recursive: true })
|
|
48
|
+
const report = { targetDir, imported: [], renamed: [], skipped: [], warnings: [] }
|
|
49
|
+
let total = 0
|
|
50
|
+
for (const [name, data] of entries) {
|
|
51
|
+
const safe = safeZipName(name)
|
|
52
|
+
if (extname(safe).toLowerCase() !== '.pdf') {
|
|
53
|
+
report.warnings.push(`跳过非 PDF:${safe}`)
|
|
54
|
+
continue
|
|
55
|
+
}
|
|
56
|
+
if (data.length > MAX_BOOK_PDF_BYTES) {
|
|
57
|
+
report.warnings.push(`文件过大:${safe}`)
|
|
58
|
+
continue
|
|
59
|
+
}
|
|
60
|
+
total += data.length
|
|
61
|
+
if (total > MAX_BOOK_ARCHIVE_BYTES) {
|
|
62
|
+
report.warnings.push('压缩包总大小超过 4 GB,剩余文件未导入')
|
|
63
|
+
break
|
|
64
|
+
}
|
|
65
|
+
const wanted = basename(safe)
|
|
66
|
+
const target = join(targetDir, wanted)
|
|
67
|
+
const exists = await stat(target).catch(() => null)
|
|
68
|
+
if (exists !== null && strategy === 'skip') {
|
|
69
|
+
report.skipped.push(wanted)
|
|
70
|
+
continue
|
|
71
|
+
}
|
|
72
|
+
if (exists !== null && strategy === 'merge') {
|
|
73
|
+
const alternative = await freeName(targetDir, wanted)
|
|
74
|
+
await writeFile(join(targetDir, alternative), data)
|
|
75
|
+
report.renamed.push(`${wanted} → ${alternative}`)
|
|
76
|
+
continue
|
|
77
|
+
}
|
|
78
|
+
await writeFile(target, data)
|
|
79
|
+
report.imported.push(wanted)
|
|
80
|
+
}
|
|
81
|
+
return report
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* List the PDFs already in a folder (used by the UI to show a target summary).
|
|
86
|
+
* @param {string} dir - folder.
|
|
87
|
+
* @returns {Promise<number>} count of PDFs.
|
|
88
|
+
*/
|
|
89
|
+
export async function countPdfs(dir) {
|
|
90
|
+
const names = await readdir(dir).catch(() => [])
|
|
91
|
+
let count = 0
|
|
92
|
+
for (const name of names) {
|
|
93
|
+
if (extname(name).toLowerCase() !== '.pdf') continue
|
|
94
|
+
const info = await stat(join(dir, name)).catch(() => null)
|
|
95
|
+
if (info !== null && info.isFile()) count += 1
|
|
96
|
+
}
|
|
97
|
+
return count
|
|
98
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The chapter's shared-prefix session map: which hidden base session read the
|
|
3
|
+
* chapter once, at which turn boundary, and which branch each mode forked.
|
|
4
|
+
*
|
|
5
|
+
* Kept in `.pdfdesk/cache/<book>/<code>/sessions.json` beside `text.md`. It is
|
|
6
|
+
* derived data: deleting it only means reading the chapter again.
|
|
7
|
+
* @module dsh-pdf-workbench/chapter-sessions
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
|
|
13
|
+
/** The four conversation modes that can fork from the base session. */
|
|
14
|
+
export const SESSION_MODES = ['general', 'extract', 'qa', 'exercise']
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Where one chapter's session map lives.
|
|
18
|
+
* @param {string} libraryDir - the library root.
|
|
19
|
+
* @param {string} book - book id.
|
|
20
|
+
* @param {string} code - chapter code.
|
|
21
|
+
* @returns {string} the absolute `sessions.json` path.
|
|
22
|
+
*/
|
|
23
|
+
export function chapterSessionsPath(libraryDir, book, code) {
|
|
24
|
+
return join(libraryDir, '.pdfdesk', 'cache', book, code, 'sessions.json')
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {string} libraryDir - the library root.
|
|
29
|
+
* @param {string} book - book id.
|
|
30
|
+
* @param {string} code - chapter code.
|
|
31
|
+
* @returns {Promise<object | null>} the map, or null when this chapter never prepared one.
|
|
32
|
+
*/
|
|
33
|
+
export async function readChapterSessions(libraryDir, book, code) {
|
|
34
|
+
const raw = await readFile(chapterSessionsPath(libraryDir, book, code), 'utf8').catch(() => null)
|
|
35
|
+
if (raw === null) return null
|
|
36
|
+
try {
|
|
37
|
+
const parsed = JSON.parse(raw)
|
|
38
|
+
return parsed !== null && typeof parsed === 'object' ? parsed : null
|
|
39
|
+
} catch {
|
|
40
|
+
return null
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Write the map atomically (a half-written base id would make every branch point
|
|
46
|
+
* at a broken session).
|
|
47
|
+
* @param {string} libraryDir - the library root.
|
|
48
|
+
* @param {string} book - book id.
|
|
49
|
+
* @param {string} code - chapter code.
|
|
50
|
+
* @param {object} value - the map.
|
|
51
|
+
* @returns {Promise<string>} the path written.
|
|
52
|
+
*/
|
|
53
|
+
export async function writeChapterSessions(libraryDir, book, code, value) {
|
|
54
|
+
const path = chapterSessionsPath(libraryDir, book, code)
|
|
55
|
+
await mkdir(join(libraryDir, '.pdfdesk', 'cache', book, code), { recursive: true })
|
|
56
|
+
const temporary = `${path}.${process.pid}.tmp`
|
|
57
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
|
|
58
|
+
await rename(temporary, path)
|
|
59
|
+
return path
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Whether a recorded map still matches the PDF it was made from.
|
|
64
|
+
* @param {object | null} manifest - the stored map.
|
|
65
|
+
* @param {{ size: number, mtimeMs: number }} pdf - the PDF's current identity.
|
|
66
|
+
* @returns {boolean} true when the PDF changed (or the map is unusable).
|
|
67
|
+
*/
|
|
68
|
+
export function chapterSessionsStale(manifest, pdf) { if (manifest === null || typeof manifest !== 'object') return true
|
|
69
|
+
if (typeof manifest.base !== 'object' || manifest.base === null) return true
|
|
70
|
+
if (typeof manifest.base.id !== 'string' || manifest.base.id === '') return true
|
|
71
|
+
if (typeof manifest.base.atSeq !== 'number' || manifest.base.atSeq < 1) return true
|
|
72
|
+
const known = manifest.pdf
|
|
73
|
+
if (typeof known !== 'object' || known === null) return true
|
|
74
|
+
return known.size !== pdf.size || known.mtimeMs !== pdf.mtimeMs
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Move a stale map and its text aside instead of deleting anything the user
|
|
79
|
+
* might still want to inspect.
|
|
80
|
+
* @param {string} libraryDir - the library root.
|
|
81
|
+
* @param {string} book - book id.
|
|
82
|
+
* @param {string} code - chapter code.
|
|
83
|
+
* @returns {Promise<string>} the `.stale` folder the old data moved into.
|
|
84
|
+
*/
|
|
85
|
+
export async function staleChapterSessions(libraryDir, book, code) {
|
|
86
|
+
const at = join(libraryDir, '.pdfdesk', 'cache', '.stale', book, code, String(Date.now()))
|
|
87
|
+
await mkdir(at, { recursive: true })
|
|
88
|
+
for (const name of ['sessions.json', 'text.md', 'text.md.meta.json']) {
|
|
89
|
+
const from = join(libraryDir, '.pdfdesk', 'cache', book, code, name)
|
|
90
|
+
const to = join(at, name)
|
|
91
|
+
try {
|
|
92
|
+
await rename(from, to)
|
|
93
|
+
} catch {
|
|
94
|
+
// not present: nothing to move
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return at
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Record the hidden base session and the turn boundary that branches fork at.
|
|
102
|
+
* @param {object} manifest - the current map (or null).
|
|
103
|
+
* @param {{ id: string, atSeq: number }} base - the base session.
|
|
104
|
+
* @param {{ size: number, mtimeMs: number }} pdf - the PDF it read.
|
|
105
|
+
* @returns {object} the next map.
|
|
106
|
+
*/
|
|
107
|
+
export function withBaseSession(manifest, base, pdf) {
|
|
108
|
+
const current = manifest !== null && typeof manifest === 'object' ? manifest : {}
|
|
109
|
+
return { ...current, base: { id: base.id, atSeq: base.atSeq }, pdf: { size: pdf.size, mtimeMs: pdf.mtimeMs }, branches: current.branches ?? {} }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Remember which session serves one mode. Forking twice for the same mode would
|
|
114
|
+
* split its history, so the first branch wins.
|
|
115
|
+
* @param {object} manifest - the current map.
|
|
116
|
+
* @param {string} mode - one of `SESSION_MODES`.
|
|
117
|
+
* @param {string} sessionId - the branch session.
|
|
118
|
+
* @returns {object} the next map.
|
|
119
|
+
*/
|
|
120
|
+
export function withBranchSession(manifest, mode, sessionId) {
|
|
121
|
+
if (!SESSION_MODES.includes(mode)) throw new Error(`未知模式:${mode}`)
|
|
122
|
+
const branches = manifest !== null && typeof manifest.branches === 'object' && manifest.branches !== null ? manifest.branches : {}
|
|
123
|
+
return { ...manifest, branches: { ...branches, [mode]: String(sessionId) } }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* @param {object | null} manifest - the map.
|
|
128
|
+
* @param {string} mode - one of `SESSION_MODES`.
|
|
129
|
+
* @returns {string} the branch session id, or '' when the mode has not forked yet.
|
|
130
|
+
*/
|
|
131
|
+
export function branchSessionId(manifest, mode) {
|
|
132
|
+
const branches = manifest !== null && typeof manifest.branches === 'object' && manifest.branches !== null ? manifest.branches : {}
|
|
133
|
+
return typeof branches[mode] === 'string' ? branches[mode] : ''
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Forget every chapter's shared prefix: extracted text, base/branch maps and
|
|
138
|
+
* any stale leftovers under `.pdfdesk/cache`. User sessions, PDFs and
|
|
139
|
+
* annotations live elsewhere and are untouched.
|
|
140
|
+
* @param {string} libraryDir - the library root.
|
|
141
|
+
* @returns {Promise<{ removed: number }>} how many chapter folders were dropped.
|
|
142
|
+
*/
|
|
143
|
+
export async function clearSharedPrefixCache(libraryDir) {
|
|
144
|
+
const root = join(libraryDir, '.pdfdesk', 'cache')
|
|
145
|
+
let removed = 0
|
|
146
|
+
const books = await readdir(root, { withFileTypes: true }).catch(() => [])
|
|
147
|
+
for (const book of books) {
|
|
148
|
+
if (!book.isDirectory() || book.name === '.stale') continue
|
|
149
|
+
const chapters = await readdir(join(root, book.name), { withFileTypes: true }).catch(() => [])
|
|
150
|
+
removed += chapters.filter(chapter => chapter.isDirectory()).length
|
|
151
|
+
}
|
|
152
|
+
await rm(root, { recursive: true, force: true })
|
|
153
|
+
return { removed }
|
|
154
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One chapter's whole text, extracted once and kept beside the library.
|
|
3
|
+
*
|
|
4
|
+
* The hidden base session (stage 7.6) reads this file instead of the PDF, so a
|
|
5
|
+
* chapter is only parsed once and the four mode branches share that prefix.
|
|
6
|
+
* `text.md` is derived data: deleting it costs one extraction, never user
|
|
7
|
+
* content.
|
|
8
|
+
* @module dsh-pdf-workbench/chapter-text
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
12
|
+
import { join } from 'node:path'
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Where one chapter's extracted text lives.
|
|
16
|
+
* @param {string} libraryDir - the library root.
|
|
17
|
+
* @param {string} book - book id.
|
|
18
|
+
* @param {string} code - chapter code.
|
|
19
|
+
* @returns {string} the absolute `text.md` path.
|
|
20
|
+
*/
|
|
21
|
+
export function chapterTextPath(libraryDir, book, code) {
|
|
22
|
+
return join(libraryDir, '.pdfdesk', 'cache', book, code, 'text.md')
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Markdown with one section per page: the page number is what lets the model
|
|
27
|
+
* cite a position back to the reader.
|
|
28
|
+
* @param {{ page: number, text: string }[]} pages - the extracted pages.
|
|
29
|
+
* @returns {string} the markdown.
|
|
30
|
+
*/
|
|
31
|
+
export function formatChapterText(pages) {
|
|
32
|
+
return pages
|
|
33
|
+
.map(page => {
|
|
34
|
+
const body = typeof page.text === 'string' && page.text !== '' ? page.text : '(本页无文本,可能是扫描页)'
|
|
35
|
+
return `## 第 ${page.page} 页\n\n${body}`
|
|
36
|
+
})
|
|
37
|
+
.join('\n\n')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Extract the chapter's text (or reuse a cached one) and write `text.md`.
|
|
42
|
+
* @param {{ script: string, source: string, libraryDir: string, book: string, code: string,
|
|
43
|
+
* run: (script: string, args: string[]) => Promise<string>, refresh?: boolean }} options - the PDF, the tool runner and the cache location.
|
|
44
|
+
* @returns {Promise<{ path: string, chars: number, pageCount: number, cached: boolean }>} the file and its size.
|
|
45
|
+
*/
|
|
46
|
+
export async function prepareChapterText(options) {
|
|
47
|
+
const { script, source, libraryDir, book, code, run } = options
|
|
48
|
+
const path = chapterTextPath(libraryDir, book, code)
|
|
49
|
+
if (options.refresh !== true) {
|
|
50
|
+
const cached = await readFile(path, 'utf8').catch(() => null)
|
|
51
|
+
const meta = await readFile(`${path}.meta.json`, 'utf8').then(raw => JSON.parse(raw)).catch(() => null)
|
|
52
|
+
const samePdf = options.pdf === undefined
|
|
53
|
+
|| (meta !== null && meta.size === options.pdf.size && meta.mtimeMs === options.pdf.mtimeMs)
|
|
54
|
+
if (typeof cached === 'string' && cached !== '' && samePdf) {
|
|
55
|
+
return { path, chars: cached.length, pageCount: (cached.match(/^## 第 /gm) ?? []).length, cached: true }
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const stdout = await run(script, [source])
|
|
59
|
+
const parsed = JSON.parse(stdout)
|
|
60
|
+
const pages = Array.isArray(parsed.pages) ? parsed.pages : []
|
|
61
|
+
const chars = typeof parsed.chars === 'number' ? parsed.chars : 0
|
|
62
|
+
if (pages.length === 0 || chars === 0) {
|
|
63
|
+
throw Object.assign(new Error('这一章没有可提取的文本(可能是扫描件)'), { code: 'no-text' })
|
|
64
|
+
}
|
|
65
|
+
const text = formatChapterText(pages)
|
|
66
|
+
const dir = join(libraryDir, '.pdfdesk', 'cache', book, code)
|
|
67
|
+
await mkdir(dir, { recursive: true })
|
|
68
|
+
const temporary = `${path}.${process.pid}.tmp`
|
|
69
|
+
await writeFile(temporary, `${text}\n`, 'utf8')
|
|
70
|
+
await rename(temporary, path)
|
|
71
|
+
const meta = {
|
|
72
|
+
size: options.pdf === undefined ? null : options.pdf.size,
|
|
73
|
+
mtimeMs: options.pdf === undefined ? null : options.pdf.mtimeMs,
|
|
74
|
+
chars,
|
|
75
|
+
pageCount: pages.length,
|
|
76
|
+
}
|
|
77
|
+
await writeFile(`${path}.meta.json`, `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
|
|
78
|
+
return { path, chars, pageCount: pages.length, cached: false }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The cached text, or null when this chapter has not been extracted yet.
|
|
83
|
+
* @param {string} libraryDir - the library root.
|
|
84
|
+
* @param {string} book - book id.
|
|
85
|
+
* @param {string} code - chapter code.
|
|
86
|
+
* @returns {Promise<string | null>} the markdown.
|
|
87
|
+
*/
|
|
88
|
+
export async function readChapterText(libraryDir, book, code) {
|
|
89
|
+
const text = await readFile(chapterTextPath(libraryDir, book, code), 'utf8').catch(() => null)
|
|
90
|
+
return typeof text === 'string' && text !== '' ? text : null
|
|
91
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The optional Chinese handwriting face (Xiaolai). It used to ship inside the
|
|
3
|
+
* plugin (22 MB); it now lives in the user's data directory and is installed on
|
|
4
|
+
* demand from the settings page, either by download or by picking a local file.
|
|
5
|
+
* When it is absent the CSS falls back to the system Kai fonts.
|
|
6
|
+
* @module dsh-pdf-workbench/fonts
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
10
|
+
import { get } from 'node:https'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
|
|
13
|
+
/** Stable file name so the browser font URL never has to change. */
|
|
14
|
+
export const FONT_FILE = 'Xiaolai-Regular.ttf'
|
|
15
|
+
|
|
16
|
+
/** Sanity bounds for an installed handwriting font. */
|
|
17
|
+
export const MIN_FONT_BYTES = 1024 * 1024
|
|
18
|
+
export const MAX_FONT_BYTES = 60 * 1024 * 1024
|
|
19
|
+
|
|
20
|
+
/** Where the font is downloaded from (release asset, optional). */
|
|
21
|
+
export const FONT_DOWNLOAD_URL = 'https://github.com/lxgw/kose-font/releases/download/v3.126/Xiaolai-Regular.ttf'
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param {string} dataDir - the plugin data directory (`~/.dsh/pdfdesk`).
|
|
25
|
+
* @returns {string} the font directory.
|
|
26
|
+
*/
|
|
27
|
+
export function fontDir(dataDir) {
|
|
28
|
+
return join(dataDir, 'fonts')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param {string} dataDir - the plugin data directory.
|
|
33
|
+
* @returns {string} the installed font path.
|
|
34
|
+
*/
|
|
35
|
+
export function fontPath(dataDir) {
|
|
36
|
+
return join(fontDir(dataDir), FONT_FILE)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @param {string} dataDir - the plugin data directory.
|
|
41
|
+
* @returns {Promise<{ installed: boolean, bytes: number }>} font state.
|
|
42
|
+
*/
|
|
43
|
+
export async function fontStatus(dataDir) {
|
|
44
|
+
const info = await stat(fontPath(dataDir)).catch(() => null)
|
|
45
|
+
return info !== null && info.isFile() ? { installed: true, bytes: info.size } : { installed: false, bytes: 0 }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* TrueType/OpenType signature check: `00 01 00 00`, `true`, `ttcf` or `OTTO`.
|
|
50
|
+
* @param {Buffer} bytes - candidate file.
|
|
51
|
+
* @returns {boolean} whether it looks like a font.
|
|
52
|
+
*/
|
|
53
|
+
export function looksLikeFont(bytes) {
|
|
54
|
+
if (!Buffer.isBuffer(bytes) || bytes.length < 12) return false
|
|
55
|
+
const tag = bytes.subarray(0, 4).toString('latin1')
|
|
56
|
+
return tag === 'true' || tag === 'ttcf' || tag === 'OTTO' || (bytes[0] === 0 && bytes[1] === 1 && bytes[2] === 0 && bytes[3] === 0)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Install font bytes atomically.
|
|
61
|
+
* @param {{ dataDir: string, bytes: Buffer }} options - destination and payload.
|
|
62
|
+
* @returns {Promise<{ installed: boolean, bytes: number }>} the new state.
|
|
63
|
+
*/
|
|
64
|
+
export async function installFont(options) {
|
|
65
|
+
const bytes = options.bytes
|
|
66
|
+
if (!Buffer.isBuffer(bytes) || bytes.length < MIN_FONT_BYTES) {
|
|
67
|
+
throw Object.assign(new Error('字体文件太小或不是字体'), { code: 'bad-font' })
|
|
68
|
+
}
|
|
69
|
+
if (bytes.length > MAX_FONT_BYTES) {
|
|
70
|
+
throw Object.assign(new Error('字体文件超过 60 MB'), { code: 'too-large' })
|
|
71
|
+
}
|
|
72
|
+
if (!looksLikeFont(bytes)) {
|
|
73
|
+
throw Object.assign(new Error('不是有效的 TTF/OTF 字体'), { code: 'bad-font' })
|
|
74
|
+
}
|
|
75
|
+
const dir = fontDir(options.dataDir)
|
|
76
|
+
await mkdir(dir, { recursive: true })
|
|
77
|
+
const target = fontPath(options.dataDir)
|
|
78
|
+
const temporary = `${target}.${process.pid}.tmp`
|
|
79
|
+
await writeFile(temporary, bytes)
|
|
80
|
+
await rename(temporary, target)
|
|
81
|
+
return { installed: true, bytes: bytes.length }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Read the installed font bytes, or null.
|
|
86
|
+
* @param {string} dataDir - the plugin data directory.
|
|
87
|
+
* @returns {Promise<Buffer | null>} the bytes.
|
|
88
|
+
*/
|
|
89
|
+
export async function readFont(dataDir) {
|
|
90
|
+
return readFile(fontPath(dataDir)).catch(() => null)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Delete the installed font.
|
|
95
|
+
* @param {string} dataDir - the plugin data directory.
|
|
96
|
+
* @returns {Promise<{ removed: boolean }>} whether a file was deleted.
|
|
97
|
+
*/
|
|
98
|
+
export async function removeFont(dataDir) {
|
|
99
|
+
const info = await stat(fontPath(dataDir)).catch(() => null)
|
|
100
|
+
if (info === null) return { removed: false }
|
|
101
|
+
await rm(fontPath(dataDir), { force: true })
|
|
102
|
+
return { removed: true }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Download the release asset and install it.
|
|
107
|
+
* @param {{ dataDir: string, url?: string, fetchImpl?: Function }} options - destination, source and injectable fetch.
|
|
108
|
+
* @returns {Promise<{ installed: boolean, bytes: number }>} the new state.
|
|
109
|
+
*/
|
|
110
|
+
/**
|
|
111
|
+
* Plain HTTPS download used when the runtime's fetch fails (proxy/TLS quirks in
|
|
112
|
+
* some Electron builds). Follows redirects and enforces the font size ceiling.
|
|
113
|
+
* @param {string} url - https URL.
|
|
114
|
+
* @param {number} [redirects] - remaining redirect hops.
|
|
115
|
+
* @returns {Promise<Buffer>} the bytes.
|
|
116
|
+
*/
|
|
117
|
+
function httpsDownload(url, redirects = 5) {
|
|
118
|
+
return new Promise((resolve, reject) => {
|
|
119
|
+
if (redirects < 0) {
|
|
120
|
+
reject(new Error('重定向次数过多'))
|
|
121
|
+
return
|
|
122
|
+
}
|
|
123
|
+
get(url, response => {
|
|
124
|
+
const status = response.statusCode ?? 0
|
|
125
|
+
if (status >= 300 && status < 400 && typeof response.headers.location === 'string') {
|
|
126
|
+
response.resume()
|
|
127
|
+
const next = new URL(response.headers.location, url).toString()
|
|
128
|
+
resolve(httpsDownload(next, redirects - 1))
|
|
129
|
+
return
|
|
130
|
+
}
|
|
131
|
+
if (status !== 200) {
|
|
132
|
+
response.resume()
|
|
133
|
+
reject(new Error(`HTTP ${status}`))
|
|
134
|
+
return
|
|
135
|
+
}
|
|
136
|
+
const chunks = []
|
|
137
|
+
let total = 0
|
|
138
|
+
response.on('data', chunk => {
|
|
139
|
+
total += chunk.length
|
|
140
|
+
if (total > MAX_FONT_BYTES) {
|
|
141
|
+
reject(new Error('字体文件超过 60 MB'))
|
|
142
|
+
response.destroy()
|
|
143
|
+
return
|
|
144
|
+
}
|
|
145
|
+
chunks.push(chunk)
|
|
146
|
+
})
|
|
147
|
+
response.on('end', () => resolve(Buffer.concat(chunks)))
|
|
148
|
+
response.on('error', reject)
|
|
149
|
+
}).on('error', reject)
|
|
150
|
+
})
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Download the release asset and install it.
|
|
155
|
+
* @param {{ dataDir: string, url?: string, fetchImpl?: Function }} options - destination, source and injectable fetch.
|
|
156
|
+
* @returns {Promise<{ installed: boolean, bytes: number }>} the new state.
|
|
157
|
+
*/
|
|
158
|
+
export async function downloadFont(options) {
|
|
159
|
+
const url = typeof options.url === 'string' && options.url !== '' ? options.url : FONT_DOWNLOAD_URL
|
|
160
|
+
let bytes = null
|
|
161
|
+
const fetchImpl = typeof options.fetchImpl === 'function' ? options.fetchImpl : globalThis.fetch
|
|
162
|
+
if (typeof fetchImpl === 'function') {
|
|
163
|
+
try {
|
|
164
|
+
const response = await fetchImpl(url)
|
|
165
|
+
if (response !== null && response !== undefined && response.ok === true) {
|
|
166
|
+
bytes = Buffer.from(await response.arrayBuffer())
|
|
167
|
+
} else {
|
|
168
|
+
throw new Error(`HTTP ${response === undefined ? '?' : response.status}`)
|
|
169
|
+
}
|
|
170
|
+
} catch (error) {
|
|
171
|
+
// The runtime's fetch can fail where plain https works (proxy/cert setup);
|
|
172
|
+
// fall back once, and only for https URLs.
|
|
173
|
+
if (!url.startsWith('https://')) {
|
|
174
|
+
throw Object.assign(new Error(`下载字体失败(${String(error && error.message ? error.message : error)})`), { code: 'download-failed' })
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
bytes = await httpsDownload(url)
|
|
178
|
+
} catch (fallbackError) {
|
|
179
|
+
throw Object.assign(new Error(`下载字体失败(${String(fallbackError && fallbackError.message ? fallbackError.message : fallbackError)})。可在 GitHub Release 附带字体,或用“导入本地字体”。`), { code: 'download-failed' })
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
} else {
|
|
183
|
+
try {
|
|
184
|
+
bytes = await httpsDownload(url)
|
|
185
|
+
} catch (error) {
|
|
186
|
+
throw Object.assign(new Error(`下载字体失败(${String(error && error.message ? error.message : error)})。可在 GitHub Release 附带字体,或用“导入本地字体”。`), { code: 'download-failed' })
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return installFont({ dataDir: options.dataDir, bytes })
|
|
190
|
+
}
|