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,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serve one PDF file with the HTTP semantics pdf.js relies on.
|
|
3
|
+
*
|
|
4
|
+
* The reader used to answer every `/pdfdesk/pdf` request with the whole file,
|
|
5
|
+
* `accept-ranges: none` and `cache-control: no-store`. That has two costs the
|
|
6
|
+
* workbench pays on every open: pdf.js cannot fetch the cross-reference table
|
|
7
|
+
* out of band and cannot reuse bytes the browser already has, and the Host
|
|
8
|
+
* holds a full copy in memory while writing it. The reader and the right-hand
|
|
9
|
+
* preview open the same chapter, so the second open paid the whole price again.
|
|
10
|
+
*
|
|
11
|
+
* This module answers single byte ranges (206), refuses unsatisfiable ones
|
|
12
|
+
* (416), streams from disk, and keeps a strong validator so a re-open costs a
|
|
13
|
+
* `304` instead of the file. `HEAD` answers headers only, like a browser asks
|
|
14
|
+
* before it decides to download.
|
|
15
|
+
*
|
|
16
|
+
* @module dsh-pdf-workbench/pdf-stream
|
|
17
|
+
*/
|
|
18
|
+
import { createReadStream } from 'node:fs'
|
|
19
|
+
import { stat } from 'node:fs/promises'
|
|
20
|
+
|
|
21
|
+
import { MAX_PDF_BYTES } from './pdf-source.js'
|
|
22
|
+
|
|
23
|
+
/** One range, possibly open-ended: `bytes=0-1023`, `bytes=500-`, `bytes=-4000`. */
|
|
24
|
+
const SINGLE_RANGE = /^bytes=(\d*)-(\d*)$/
|
|
25
|
+
|
|
26
|
+
/** How long a browser may keep a PDF without asking again; it revalidates after. */
|
|
27
|
+
const PDF_CACHE_CONTROL = 'private, max-age=0, must-revalidate'
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Parse one `Range` header against a known file size.
|
|
31
|
+
*
|
|
32
|
+
* A header a server must ignore (several ranges, another unit, garbage) returns
|
|
33
|
+
* `null`, which means "answer with the whole file". A syntactically valid but
|
|
34
|
+
* unsatisfiable range returns `{ unsatisfiable: true }` so the caller can send
|
|
35
|
+
* 416 with the real size, which is what tells a client to stop asking.
|
|
36
|
+
* @param {unknown} header - the `Range` header value.
|
|
37
|
+
* @param {number} size - the file's size in bytes.
|
|
38
|
+
* @returns {{ start: number, end: number } | { unsatisfiable: true } | null} the byte range to send, or why not.
|
|
39
|
+
*/
|
|
40
|
+
export function parseByteRange(header, size) {
|
|
41
|
+
if (typeof header !== 'string' || size <= 0) return null
|
|
42
|
+
const match = SINGLE_RANGE.exec(header.trim())
|
|
43
|
+
if (match === null) return null
|
|
44
|
+
const fromText = match[1]
|
|
45
|
+
const toText = match[2]
|
|
46
|
+
if (fromText === '' && toText === '') return null
|
|
47
|
+
if (fromText === '') {
|
|
48
|
+
// A suffix range: the last N bytes, which is how pdf.js asks for a trailer.
|
|
49
|
+
const length = Number(toText)
|
|
50
|
+
if (!Number.isFinite(length) || length <= 0) return null
|
|
51
|
+
return { start: Math.max(0, size - length), end: size - 1 }
|
|
52
|
+
}
|
|
53
|
+
const start = Number(fromText)
|
|
54
|
+
if (!Number.isFinite(start)) return null
|
|
55
|
+
if (start >= size) return { unsatisfiable: true }
|
|
56
|
+
const end = toText === '' ? size - 1 : Number(toText)
|
|
57
|
+
if (!Number.isFinite(end) || end < start) return null
|
|
58
|
+
return { start, end: Math.min(end, size - 1) }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* A strong validator for one file version: size and modification time.
|
|
63
|
+
* @param {{ size: number, mtimeMs: number }} info - `fs.Stats` (or anything with those fields).
|
|
64
|
+
* @returns {string} a quoted entity tag.
|
|
65
|
+
*/
|
|
66
|
+
export function fileEtag(info) {
|
|
67
|
+
return `"${info.size.toString(36)}-${Math.floor(info.mtimeMs).toString(36)}"`
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Whether an `If-None-Match` header names this entity tag.
|
|
72
|
+
* @param {unknown} header - the header value.
|
|
73
|
+
* @param {string} etag - the current entity tag.
|
|
74
|
+
* @returns {boolean} true when the client already has this version.
|
|
75
|
+
*/
|
|
76
|
+
export function matchesEtag(header, etag) {
|
|
77
|
+
if (typeof header !== 'string' || header === '') return false
|
|
78
|
+
const wanted = header.trim()
|
|
79
|
+
if (wanted === '*') return true
|
|
80
|
+
return wanted.split(',').some(part => part.trim() === etag)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Pipe one file range to the response, tearing the read down when the client
|
|
85
|
+
* goes away (pdf.js aborts loads on every page-flip in continuous mode).
|
|
86
|
+
* @param {import('node:http').ServerResponse} response - the outbound response.
|
|
87
|
+
* @param {string} path - absolute file path.
|
|
88
|
+
* @param {{ start: number, end: number } | undefined} range - bytes to send, or undefined for all.
|
|
89
|
+
* @returns {void}
|
|
90
|
+
*/
|
|
91
|
+
function pipeFile(response, path, range) {
|
|
92
|
+
const stream = range === undefined
|
|
93
|
+
? createReadStream(path)
|
|
94
|
+
: createReadStream(path, { start: range.start, end: range.end })
|
|
95
|
+
let finished = false
|
|
96
|
+
const cleanup = () => {
|
|
97
|
+
if (finished) return
|
|
98
|
+
finished = true
|
|
99
|
+
stream.destroy()
|
|
100
|
+
}
|
|
101
|
+
stream.on('error', () => {
|
|
102
|
+
cleanup()
|
|
103
|
+
try { response.destroy() } catch { /* already gone */ }
|
|
104
|
+
})
|
|
105
|
+
response.on('close', cleanup)
|
|
106
|
+
stream.pipe(response)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Answer one PDF request from disk.
|
|
111
|
+
*
|
|
112
|
+
* Never throws for a missing file: the caller decides the envelope (the reader
|
|
113
|
+
* shows "找不到这个 PDF", a missing translation says so instead).
|
|
114
|
+
* @param {import('node:http').IncomingMessage} request - the inbound request.
|
|
115
|
+
* @param {import('node:http').ServerResponse} response - the outbound response.
|
|
116
|
+
* @param {string} path - absolute path of the PDF.
|
|
117
|
+
* @returns {Promise<{ ok: true, status: number } | { ok: false, reason: 'not-found' | 'too-large' }>} what was answered.
|
|
118
|
+
*/
|
|
119
|
+
export async function sendPdfFile(request, response, path) {
|
|
120
|
+
let info
|
|
121
|
+
try {
|
|
122
|
+
info = await stat(path)
|
|
123
|
+
} catch {
|
|
124
|
+
return { ok: false, reason: 'not-found' }
|
|
125
|
+
}
|
|
126
|
+
if (info.isFile() !== true) return { ok: false, reason: 'not-found' }
|
|
127
|
+
if (info.size > MAX_PDF_BYTES) return { ok: false, reason: 'too-large' }
|
|
128
|
+
const etag = fileEtag(info)
|
|
129
|
+
const base = {
|
|
130
|
+
'content-type': 'application/pdf',
|
|
131
|
+
'cache-control': PDF_CACHE_CONTROL,
|
|
132
|
+
'accept-ranges': 'bytes',
|
|
133
|
+
etag,
|
|
134
|
+
'last-modified': info.mtime.toUTCString(),
|
|
135
|
+
}
|
|
136
|
+
if (matchesEtag(request.headers['if-none-match'], etag)) {
|
|
137
|
+
response.writeHead(304, { 'cache-control': PDF_CACHE_CONTROL, etag, 'last-modified': base['last-modified'] })
|
|
138
|
+
response.end()
|
|
139
|
+
return { ok: true, status: 304 }
|
|
140
|
+
}
|
|
141
|
+
const range = parseByteRange(request.headers.range, info.size)
|
|
142
|
+
if (range !== null && range.unsatisfiable === true) {
|
|
143
|
+
response.writeHead(416, {
|
|
144
|
+
'content-type': 'application/pdf',
|
|
145
|
+
'cache-control': PDF_CACHE_CONTROL,
|
|
146
|
+
'accept-ranges': 'bytes',
|
|
147
|
+
'content-range': `bytes */${info.size}`,
|
|
148
|
+
etag,
|
|
149
|
+
})
|
|
150
|
+
response.end()
|
|
151
|
+
return { ok: true, status: 416 }
|
|
152
|
+
}
|
|
153
|
+
const headers = { ...base }
|
|
154
|
+
if (range === null) {
|
|
155
|
+
headers['content-length'] = info.size
|
|
156
|
+
} else {
|
|
157
|
+
headers['content-range'] = `bytes ${range.start}-${range.end}/${info.size}`
|
|
158
|
+
headers['content-length'] = range.end - range.start + 1
|
|
159
|
+
}
|
|
160
|
+
const status = range === null ? 200 : 206
|
|
161
|
+
response.writeHead(status, headers)
|
|
162
|
+
if (request.method === 'HEAD') {
|
|
163
|
+
response.end()
|
|
164
|
+
return { ok: true, status }
|
|
165
|
+
}
|
|
166
|
+
pipeFile(response, path, range ?? undefined)
|
|
167
|
+
return { ok: true, status }
|
|
168
|
+
}
|
package/src/host/ppt.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PPT/PPTX → PDF for chapter attachments. Windows with PowerPoint uses COM
|
|
3
|
+
* (keeps theme fonts and animations flattened as PowerPoint does); other
|
|
4
|
+
* machines fall back to LibreOffice. Both paths are optional: when neither
|
|
5
|
+
* exists the caller gets a clear `no-converter` error instead of a half-copied
|
|
6
|
+
* file.
|
|
7
|
+
* @module dsh-pdf-workbench/ppt
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { execFile } from 'node:child_process'
|
|
11
|
+
import { stat, readdir, rename, rm } from 'node:fs/promises'
|
|
12
|
+
import { mkdtemp } from 'node:fs/promises'
|
|
13
|
+
import { tmpdir } from 'node:os'
|
|
14
|
+
import { basename, dirname, extname, join } from 'node:path'
|
|
15
|
+
|
|
16
|
+
/** Extensions this module can convert. */
|
|
17
|
+
export const PPT_EXTENSIONS = new Set(['ppt', 'pptx'])
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {string} source - a file path.
|
|
21
|
+
* @returns {boolean} whether it is a presentation this module handles.
|
|
22
|
+
*/
|
|
23
|
+
export function isPptPath(source) {
|
|
24
|
+
return PPT_EXTENSIONS.has(extname(String(source ?? '')).slice(1).toLowerCase())
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Run one executable and resolve stdout.
|
|
29
|
+
* @param {string} command - executable.
|
|
30
|
+
* @param {string[]} args - arguments.
|
|
31
|
+
* @returns {Promise<string>} stdout.
|
|
32
|
+
*/
|
|
33
|
+
function runCommand(command, args) {
|
|
34
|
+
return new Promise((resolve, reject) => {
|
|
35
|
+
execFile(command, args, { timeout: 180000, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (error, stdout) => {
|
|
36
|
+
if (error === null) resolve(stdout)
|
|
37
|
+
else reject(error)
|
|
38
|
+
})
|
|
39
|
+
})
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The PowerShell that drives PowerPoint's COM automation. `SaveAs(..., 32)` is
|
|
44
|
+
* `ppSaveAsPDF`; the presentation opens without a window.
|
|
45
|
+
* @param {string} source - absolute ppt/pptx path.
|
|
46
|
+
* @param {string} outPath - absolute pdf path.
|
|
47
|
+
* @returns {string} the script.
|
|
48
|
+
*/
|
|
49
|
+
export function powerPointScript(source, outPath) {
|
|
50
|
+
const quote = value => `'${String(value).replace(/'/g, "''")}'`
|
|
51
|
+
return [
|
|
52
|
+
"$ErrorActionPreference = 'Stop'",
|
|
53
|
+
'$app = New-Object -ComObject PowerPoint.Application',
|
|
54
|
+
'try {',
|
|
55
|
+
` $pres = $app.Presentations.Open(${quote(source)}, $true, $false, $false)`,
|
|
56
|
+
' try {',
|
|
57
|
+
` $pres.SaveAs(${quote(outPath)}, 32)`,
|
|
58
|
+
' } finally {',
|
|
59
|
+
' $pres.Close()',
|
|
60
|
+
' }',
|
|
61
|
+
'} finally {',
|
|
62
|
+
' $app.Quit()',
|
|
63
|
+
'}',
|
|
64
|
+
].join('\n')
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* PowerPoint through COM (Windows only).
|
|
69
|
+
* @param {string} source - ppt/pptx path.
|
|
70
|
+
* @param {string} outPath - target pdf path.
|
|
71
|
+
* @returns {Promise<void>} completion.
|
|
72
|
+
*/
|
|
73
|
+
export async function convertWithPowerPoint(source, outPath) {
|
|
74
|
+
await runCommand('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', powerPointScript(source, outPath)])
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* LibreOffice fallback: convert into a private folder, then move the produced
|
|
79
|
+
* pdf to the caller's exact path.
|
|
80
|
+
* @param {string} source - ppt/pptx path.
|
|
81
|
+
* @param {string} outPath - target pdf path.
|
|
82
|
+
* @returns {Promise<void>} completion.
|
|
83
|
+
*/
|
|
84
|
+
export async function convertWithLibreOffice(source, outPath) {
|
|
85
|
+
const work = await mkdtemp(join(tmpdir(), 'pdfdesk-ppt-'))
|
|
86
|
+
try {
|
|
87
|
+
const binaries = process.platform === 'win32' ? ['soffice.exe', 'soffice'] : ['soffice', 'libreoffice']
|
|
88
|
+
let lastError = null
|
|
89
|
+
for (const binary of binaries) {
|
|
90
|
+
try {
|
|
91
|
+
await runCommand(binary, ['--headless', '--convert-to', 'pdf', '--outdir', work, source])
|
|
92
|
+
lastError = null
|
|
93
|
+
break
|
|
94
|
+
} catch (error) {
|
|
95
|
+
lastError = error
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (lastError !== null) throw lastError
|
|
99
|
+
const produced = (await readdir(work)).find(name => extname(name).toLowerCase() === '.pdf')
|
|
100
|
+
if (produced === undefined) throw new Error('LibreOffice 没有生成 PDF')
|
|
101
|
+
await rename(join(work, produced), outPath)
|
|
102
|
+
} finally {
|
|
103
|
+
await rm(work, { recursive: true, force: true })
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The converters to try, in order, for this platform.
|
|
109
|
+
* @param {string} [platform] - Node platform string.
|
|
110
|
+
* @returns {Function[]} converter functions.
|
|
111
|
+
*/
|
|
112
|
+
export function defaultConverters(platform = process.platform) {
|
|
113
|
+
return platform === 'win32'
|
|
114
|
+
? [convertWithPowerPoint, convertWithLibreOffice]
|
|
115
|
+
: [convertWithLibreOffice]
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Convert one presentation and verify a non-empty PDF appeared.
|
|
120
|
+
* @param {{ source: string, outPath: string, converters?: Function[] }} options - input, output and optional converter chain.
|
|
121
|
+
* @returns {Promise<{ outPath: string, bytes: number }>} the produced pdf.
|
|
122
|
+
*/
|
|
123
|
+
export async function convertPptToPdf(options) {
|
|
124
|
+
const source = String(options.source ?? '')
|
|
125
|
+
const outPath = String(options.outPath ?? '')
|
|
126
|
+
if (!isPptPath(source)) throw Object.assign(new Error('只支持 .ppt / .pptx'), { code: 'bad-type' })
|
|
127
|
+
if (outPath === '' || dirname(outPath) === '') throw Object.assign(new Error('缺少输出路径'), { code: 'bad-output' })
|
|
128
|
+
const converters = Array.isArray(options.converters) ? options.converters : defaultConverters()
|
|
129
|
+
const failures = []
|
|
130
|
+
for (const convert of converters) {
|
|
131
|
+
try {
|
|
132
|
+
await convert(source, outPath)
|
|
133
|
+
const info = await stat(outPath).catch(() => null)
|
|
134
|
+
if (info !== null && info.isFile() && info.size > 0) return { outPath, bytes: info.size }
|
|
135
|
+
failures.push('未生成有效 PDF')
|
|
136
|
+
} catch (error) {
|
|
137
|
+
failures.push(String(error && error.message ? error.message : error).split('\n')[0])
|
|
138
|
+
}
|
|
139
|
+
await rm(outPath, { force: true }).catch(() => {})
|
|
140
|
+
}
|
|
141
|
+
throw Object.assign(new Error(`PPT 转 PDF 失败:${failures.join(';') || '没有可用的转换器'}`), { code: 'no-converter' })
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* The default output name for a converted presentation.
|
|
146
|
+
* @param {string} name - original file name.
|
|
147
|
+
* @returns {string} `<stem>.pdf`.
|
|
148
|
+
*/
|
|
149
|
+
export function pdfNameForPpt(name) {
|
|
150
|
+
const base = basename(String(name ?? ''))
|
|
151
|
+
const extension = extname(base)
|
|
152
|
+
return `${extension === '' ? base : base.slice(0, -extension.length)}.pdf`
|
|
153
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTML print path: Markdown to a self-contained printable page.
|
|
3
|
+
*
|
|
4
|
+
* TeX is not required. The page uses the browser's own print dialog (no
|
|
5
|
+
* temporary PDF), and formula rendering is an optional online enhancement:
|
|
6
|
+
* KaTeX is fetched from a CDN when the network allows it, and the source TeX
|
|
7
|
+
* stays readable when it does not.
|
|
8
|
+
*
|
|
9
|
+
* @module dsh-pdf-workbench/print
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Escape text for HTML body content.
|
|
14
|
+
* @param {string} text - raw text.
|
|
15
|
+
* @returns {string} escaped text.
|
|
16
|
+
*/
|
|
17
|
+
function escapeHtml(text) {
|
|
18
|
+
return String(text)
|
|
19
|
+
.replaceAll('&', '&')
|
|
20
|
+
.replaceAll('<', '<')
|
|
21
|
+
.replaceAll('>', '>')
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Escape one attribute value.
|
|
26
|
+
* @param {string} text - raw text.
|
|
27
|
+
* @returns {string} escaped value.
|
|
28
|
+
*/
|
|
29
|
+
function escapeAttr(text) {
|
|
30
|
+
return escapeHtml(text).replaceAll('"', '"')
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Inline Markdown: code spans, emphasis, links and images. Everything is
|
|
35
|
+
* escaped first, so a Markdown file cannot inject markup.
|
|
36
|
+
* @param {string} raw - one line of Markdown.
|
|
37
|
+
* @returns {string} inline HTML.
|
|
38
|
+
*/
|
|
39
|
+
function inline(raw) {
|
|
40
|
+
let text = escapeHtml(raw)
|
|
41
|
+
text = text.replace(/`([^`]+)`/g, (_, code) => `<code>${code}</code>`)
|
|
42
|
+
text = text.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
|
|
43
|
+
text = text.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>')
|
|
44
|
+
text = text.replace(/~~([^~]+)~~/g, '<del>$1</del>')
|
|
45
|
+
text = text.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, '<img alt="$1" src="$2">')
|
|
46
|
+
text = text.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '<a href="$2">$1</a>')
|
|
47
|
+
return text
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Convert Markdown to the simple HTML the print page needs. It deliberately
|
|
52
|
+
* covers headings, paragraphs, lists, quotes, code, rules and inline styles;
|
|
53
|
+
* anything fancier prints as plain text rather than being dropped.
|
|
54
|
+
* @param {string} markdown - the file's text.
|
|
55
|
+
* @returns {string} the article body.
|
|
56
|
+
*/
|
|
57
|
+
export function markdownToHtml(markdown) {
|
|
58
|
+
const lines = String(markdown ?? '').replace(/\r\n?/g, '\n').split('\n')
|
|
59
|
+
const out = []
|
|
60
|
+
let list = ''
|
|
61
|
+
const closeList = () => {
|
|
62
|
+
if (list === '') return
|
|
63
|
+
out.push(`</${list}>`)
|
|
64
|
+
list = ''
|
|
65
|
+
}
|
|
66
|
+
const startsBlock = line => /^\s*(#{1,6}\s|```|>|[-*+]\s|\d+[.)]\s)/.test(line)
|
|
67
|
+
let index = 0
|
|
68
|
+
while (index < lines.length) {
|
|
69
|
+
const line = lines[index]
|
|
70
|
+
const fence = /^\s*```(\S*)\s*$/.exec(line)
|
|
71
|
+
if (fence !== null) {
|
|
72
|
+
closeList()
|
|
73
|
+
const language = fence[1]
|
|
74
|
+
index += 1
|
|
75
|
+
const code = []
|
|
76
|
+
while (index < lines.length && !/^\s*```\s*$/.test(lines[index])) {
|
|
77
|
+
code.push(lines[index])
|
|
78
|
+
index += 1
|
|
79
|
+
}
|
|
80
|
+
index += 1
|
|
81
|
+
out.push(`<pre><code${language === '' ? '' : ` class="language-${escapeAttr(language)}"`}>${escapeHtml(code.join('\n'))}</code></pre>`)
|
|
82
|
+
continue
|
|
83
|
+
}
|
|
84
|
+
const heading = /^(#{1,6})\s+(.*)$/.exec(line)
|
|
85
|
+
if (heading !== null) {
|
|
86
|
+
closeList()
|
|
87
|
+
const level = heading[1].length
|
|
88
|
+
out.push(`<h${level}>${inline(heading[2])}</h${level}>`)
|
|
89
|
+
index += 1
|
|
90
|
+
continue
|
|
91
|
+
}
|
|
92
|
+
if (/^\s*([-*_])\s*\1\s*\1[\s\-_*]*$/.test(line)) {
|
|
93
|
+
closeList()
|
|
94
|
+
out.push('<hr>')
|
|
95
|
+
index += 1
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
const quote = /^\s*>\s?(.*)$/.exec(line)
|
|
99
|
+
if (quote !== null) {
|
|
100
|
+
closeList()
|
|
101
|
+
const body = []
|
|
102
|
+
while (index < lines.length) {
|
|
103
|
+
const inner = /^\s*>\s?(.*)$/.exec(lines[index])
|
|
104
|
+
if (inner === null) break
|
|
105
|
+
body.push(inline(inner[1]))
|
|
106
|
+
index += 1
|
|
107
|
+
}
|
|
108
|
+
out.push(`<blockquote>${body.join('<br>')}</blockquote>`)
|
|
109
|
+
continue
|
|
110
|
+
}
|
|
111
|
+
const bullet = /^\s*[-*+]\s+(.*)$/.exec(line)
|
|
112
|
+
const ordered = /^\s*\d+[.)]\s+(.*)$/.exec(line)
|
|
113
|
+
if (bullet !== null || ordered !== null) {
|
|
114
|
+
const tag = bullet !== null ? 'ul' : 'ol'
|
|
115
|
+
if (list !== tag) {
|
|
116
|
+
closeList()
|
|
117
|
+
out.push(`<${tag}>`)
|
|
118
|
+
list = tag
|
|
119
|
+
}
|
|
120
|
+
out.push(`<li>${inline((bullet ?? ordered)[1])}</li>`)
|
|
121
|
+
index += 1
|
|
122
|
+
continue
|
|
123
|
+
}
|
|
124
|
+
if (/^\s*$/.test(line)) {
|
|
125
|
+
closeList()
|
|
126
|
+
index += 1
|
|
127
|
+
continue
|
|
128
|
+
}
|
|
129
|
+
closeList()
|
|
130
|
+
const paragraph = []
|
|
131
|
+
while (index < lines.length && !/^\s*$/.test(lines[index]) && !startsBlock(lines[index])) {
|
|
132
|
+
paragraph.push(lines[index])
|
|
133
|
+
index += 1
|
|
134
|
+
}
|
|
135
|
+
out.push(`<p>${paragraph.map(inline).join('\n')}</p>`)
|
|
136
|
+
}
|
|
137
|
+
closeList()
|
|
138
|
+
return out.join('\n')
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Wrap a rendered body in the printable page.
|
|
143
|
+
* @param {string} title - document title shown in the print header.
|
|
144
|
+
* @param {string} body - rendered article HTML.
|
|
145
|
+
* @returns {string} a complete HTML document.
|
|
146
|
+
*/
|
|
147
|
+
export function printPageHtml(title, body) {
|
|
148
|
+
const safeTitle = escapeHtml(title)
|
|
149
|
+
return `<!doctype html>
|
|
150
|
+
<html lang="zh">
|
|
151
|
+
<head>
|
|
152
|
+
<meta charset="utf-8">
|
|
153
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
154
|
+
<title>${safeTitle}</title>
|
|
155
|
+
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css">
|
|
156
|
+
<style>
|
|
157
|
+
@page { size: A4; margin: 18mm 16mm; }
|
|
158
|
+
* { box-sizing: border-box; }
|
|
159
|
+
body { margin: 0; padding: 32px 40px; color: #1f1f1f; background: #fff;
|
|
160
|
+
font: 15px/1.75 system-ui, -apple-system, "Segoe UI", "Microsoft YaHei", "PingFang SC", sans-serif; }
|
|
161
|
+
article { max-width: 860px; margin: 0 auto; }
|
|
162
|
+
h1, h2, h3, h4, h5, h6 { line-height: 1.3; margin: 1.2em 0 .5em; page-break-after: avoid; }
|
|
163
|
+
h1 { font-size: 1.7em; } h2 { font-size: 1.4em; } h3 { font-size: 1.2em; }
|
|
164
|
+
p { margin: .6em 0; }
|
|
165
|
+
a { color: #2f6df6; text-decoration: underline; }
|
|
166
|
+
img { max-width: 100%; height: auto; }
|
|
167
|
+
code { padding: 1px 5px; border-radius: 4px; background: #f3f4f6; font-size: .92em;
|
|
168
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
|
169
|
+
pre { padding: 12px 14px; overflow-x: auto; background: #f7f8fa; border: 1px solid #e5e7eb;
|
|
170
|
+
border-radius: 8px; page-break-inside: avoid; }
|
|
171
|
+
pre code { padding: 0; background: none; }
|
|
172
|
+
blockquote { margin: .8em 0; padding: .2em 0 .2em 14px; border-left: 3px solid #d1d5db; color: #4b5563; }
|
|
173
|
+
ul, ol { margin: .6em 0; padding-left: 1.6em; }
|
|
174
|
+
li { margin: .2em 0; }
|
|
175
|
+
hr { border: none; border-top: 1px solid #e5e7eb; margin: 1.4em 0; }
|
|
176
|
+
table { border-collapse: collapse; width: 100%; }
|
|
177
|
+
th, td { border: 1px solid #e5e7eb; padding: 6px 8px; text-align: left; }
|
|
178
|
+
@media print { body { padding: 0; } a { color: inherit; } }
|
|
179
|
+
</style>
|
|
180
|
+
</head>
|
|
181
|
+
<body>
|
|
182
|
+
<article>
|
|
183
|
+
${body}
|
|
184
|
+
</article>
|
|
185
|
+
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js"></script>
|
|
186
|
+
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js"
|
|
187
|
+
onload="try{renderMathInElement(document.body,{delimiters:[{left:'$$',right:'$$',display:true},{left:'$',right:'$',display:false}],throwOnError:false})}catch(e){}"></script>
|
|
188
|
+
</body>
|
|
189
|
+
</html>
|
|
190
|
+
`
|
|
191
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chapter questions: thin-bordered **position markers** on a page, not text.
|
|
3
|
+
*
|
|
4
|
+
* A question is a rectangle on one page plus a name. It stores no excerpt and no
|
|
5
|
+
* question body: the name only locates the place, the reader jumps there, and a
|
|
6
|
+
* conversation (when the user asks for help) receives one line about it.
|
|
7
|
+
*
|
|
8
|
+
* Stored inside the library so it travels with the books:
|
|
9
|
+
*
|
|
10
|
+
* <库根>/.pdfdesk/questions/<书>/<章>.json
|
|
11
|
+
* { format, next, questions: [{ id, name, page, rect, createdAt }] }
|
|
12
|
+
*
|
|
13
|
+
* `next` is the number the next default name (`疑问 N`) takes. Deleting a
|
|
14
|
+
* question does not give its number back, and `next` only ever moves forward.
|
|
15
|
+
*
|
|
16
|
+
* @module dsh-pdf-workbench/questions
|
|
17
|
+
*/
|
|
18
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
19
|
+
import { dirname, join } from 'node:path'
|
|
20
|
+
|
|
21
|
+
/** On-disk schema version. */
|
|
22
|
+
export const QUESTIONS_FORMAT = 1
|
|
23
|
+
|
|
24
|
+
/** Questions kept per chapter: a page mark should stay a mark, not a database. */
|
|
25
|
+
export const MAX_QUESTIONS = 500
|
|
26
|
+
|
|
27
|
+
/** Longest accepted name. */
|
|
28
|
+
const MAX_NAME = 80
|
|
29
|
+
|
|
30
|
+
/** A question id, generated by the browser. */
|
|
31
|
+
const ID = /^q-[A-Za-z0-9._-]{1,64}$/
|
|
32
|
+
|
|
33
|
+
/** A chapter code, canonical form. */
|
|
34
|
+
const CODE = /^c\d{2,3}$/
|
|
35
|
+
|
|
36
|
+
/** One path segment: no separators, no traversal, no drive colon. */
|
|
37
|
+
const SEGMENT = /^[^\\/:*?"<>|]{1,200}$/
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Whether a value can be one directory segment.
|
|
41
|
+
* @param {unknown} value - candidate.
|
|
42
|
+
* @returns {boolean} true when safe.
|
|
43
|
+
*/
|
|
44
|
+
function isSegment(value) {
|
|
45
|
+
return typeof value === 'string' && SEGMENT.test(value) && value !== '.' && value !== '..'
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* One chapter's questions file.
|
|
50
|
+
* @param {string} libraryDir - library root.
|
|
51
|
+
* @param {string} book - book id.
|
|
52
|
+
* @param {string} code - chapter code.
|
|
53
|
+
* @returns {string} absolute path.
|
|
54
|
+
*/
|
|
55
|
+
export function questionsFile(libraryDir, book, code) {
|
|
56
|
+
return join(libraryDir, '.pdfdesk', 'questions', book, `${code}.json`)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Clamp one rect into the page. A hand-edited file or a stale layout must not
|
|
61
|
+
* put a mark outside the page.
|
|
62
|
+
* @param {unknown} value - candidate rect.
|
|
63
|
+
* @returns {{ x: number, y: number, w: number, h: number } | null} the rect, or null.
|
|
64
|
+
*/
|
|
65
|
+
function sanitizeRect(value) {
|
|
66
|
+
if (value === null || typeof value !== 'object') return null
|
|
67
|
+
const x = Number(value.x)
|
|
68
|
+
const y = Number(value.y)
|
|
69
|
+
const w = Number(value.w)
|
|
70
|
+
const h = Number(value.h)
|
|
71
|
+
if (![x, y, w, h].every(item => Number.isFinite(item))) return null
|
|
72
|
+
// A mark with no area is not a mark: the browser never creates one, and a
|
|
73
|
+
// hand-edited file should not smuggle a point in as a rectangle.
|
|
74
|
+
if (w <= 0 || h <= 0) return null
|
|
75
|
+
const left = Math.min(1, Math.max(0, x))
|
|
76
|
+
const top = Math.min(1, Math.max(0, y))
|
|
77
|
+
const width = Math.min(1 - left, Math.max(0.002, w))
|
|
78
|
+
const height = Math.min(1 - top, Math.max(0.002, h))
|
|
79
|
+
const round = number => Math.round(number * 1e6) / 1e6
|
|
80
|
+
return { x: round(left), y: round(top), w: round(width), h: round(height) }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Keep one stored question if it is usable.
|
|
85
|
+
* @param {unknown} value - stored entry.
|
|
86
|
+
* @param {number} index - its position, for a missing name.
|
|
87
|
+
* @returns {object | null} the question, or null when unusable.
|
|
88
|
+
*/
|
|
89
|
+
function sanitizeQuestion(value, index) {
|
|
90
|
+
if (value === null || typeof value !== 'object') return null
|
|
91
|
+
const id = typeof value.id === 'string' && ID.test(value.id) ? value.id : ''
|
|
92
|
+
const rect = sanitizeRect(value.rect)
|
|
93
|
+
const page = Math.round(Number(value.page))
|
|
94
|
+
if (id === '' || rect === null || !Number.isFinite(page) || page < 1) return null
|
|
95
|
+
const name = typeof value.name === 'string' && value.name.trim() !== ''
|
|
96
|
+
? value.name.trim().slice(0, MAX_NAME)
|
|
97
|
+
: `疑问 ${index + 1}`
|
|
98
|
+
const stamp = Number(value.createdAt)
|
|
99
|
+
return {
|
|
100
|
+
id,
|
|
101
|
+
name,
|
|
102
|
+
page,
|
|
103
|
+
rect,
|
|
104
|
+
createdAt: Number.isFinite(stamp) && stamp > 0 ? stamp : Date.now(),
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The number inside a `疑问 N` name, for keeping `next` ahead of hand-edited
|
|
110
|
+
* names.
|
|
111
|
+
* @param {string} name - question name.
|
|
112
|
+
* @returns {number} the number, or 0.
|
|
113
|
+
*/
|
|
114
|
+
function numberOfName(name) {
|
|
115
|
+
const match = /^疑问\s*(\d+)$/.exec(name)
|
|
116
|
+
return match === null ? 0 : Number(match[1])
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Read one chapter's questions.
|
|
121
|
+
* @param {string} libraryDir - library root.
|
|
122
|
+
* @param {string} book - book id.
|
|
123
|
+
* @param {string} code - chapter code.
|
|
124
|
+
* @returns {Promise<{ format: number, next: number, questions: object[] }>} the stored list (empty when absent).
|
|
125
|
+
*/
|
|
126
|
+
export async function readQuestions(libraryDir, book, code) {
|
|
127
|
+
if (!isSegment(book) || !CODE.test(code)) return { format: QUESTIONS_FORMAT, next: 1, questions: [] }
|
|
128
|
+
let parsed = null
|
|
129
|
+
try {
|
|
130
|
+
parsed = JSON.parse(await readFile(questionsFile(libraryDir, book, code), 'utf8'))
|
|
131
|
+
} catch {
|
|
132
|
+
return { format: QUESTIONS_FORMAT, next: 1, questions: [] }
|
|
133
|
+
}
|
|
134
|
+
const raw = parsed !== null && typeof parsed === 'object' && Array.isArray(parsed.questions) ? parsed.questions : []
|
|
135
|
+
const questions = []
|
|
136
|
+
const seen = new Set()
|
|
137
|
+
for (const value of raw) {
|
|
138
|
+
const entry = sanitizeQuestion(value, questions.length)
|
|
139
|
+
if (entry === null || seen.has(entry.id)) continue
|
|
140
|
+
seen.add(entry.id)
|
|
141
|
+
questions.push(entry)
|
|
142
|
+
if (questions.length >= MAX_QUESTIONS) break
|
|
143
|
+
}
|
|
144
|
+
const storedNext = Number(parsed !== null && typeof parsed === 'object' ? parsed.next : NaN)
|
|
145
|
+
const next = Math.max(
|
|
146
|
+
Number.isFinite(storedNext) && storedNext > 0 ? Math.round(storedNext) : 1,
|
|
147
|
+
questions.reduce((max, entry) => Math.max(max, numberOfName(entry.name) + 1), 1),
|
|
148
|
+
questions.length + 1,
|
|
149
|
+
)
|
|
150
|
+
return { format: QUESTIONS_FORMAT, next, questions }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Replace one chapter's questions atomically.
|
|
155
|
+
* @param {string} libraryDir - library root.
|
|
156
|
+
* @param {string} book - book id.
|
|
157
|
+
* @param {string} code - chapter code.
|
|
158
|
+
* @param {unknown} body - `{ questions, next }` from the browser.
|
|
159
|
+
* @returns {Promise<{ format: number, next: number, questions: object[] }>} what was stored.
|
|
160
|
+
*/
|
|
161
|
+
export async function writeQuestions(libraryDir, book, code, body) {
|
|
162
|
+
if (!isSegment(book) || !CODE.test(code)) throw new Error('书或章不合法')
|
|
163
|
+
const record = body !== null && typeof body === 'object' ? body : {}
|
|
164
|
+
const raw = Array.isArray(record.questions) ? record.questions : []
|
|
165
|
+
const questions = []
|
|
166
|
+
const seen = new Set()
|
|
167
|
+
for (const value of raw) {
|
|
168
|
+
const entry = sanitizeQuestion(value, questions.length)
|
|
169
|
+
if (entry === null || seen.has(entry.id)) continue
|
|
170
|
+
seen.add(entry.id)
|
|
171
|
+
questions.push(entry)
|
|
172
|
+
if (questions.length >= MAX_QUESTIONS) break
|
|
173
|
+
}
|
|
174
|
+
const wantedNext = Number(record.next)
|
|
175
|
+
const next = Math.max(
|
|
176
|
+
Number.isFinite(wantedNext) && wantedNext > 0 ? Math.round(wantedNext) : 1,
|
|
177
|
+
questions.reduce((max, entry) => Math.max(max, numberOfName(entry.name) + 1), 1),
|
|
178
|
+
questions.length + 1,
|
|
179
|
+
)
|
|
180
|
+
const target = questionsFile(libraryDir, book, code)
|
|
181
|
+
await mkdir(dirname(target), { recursive: true })
|
|
182
|
+
const temporary = `${target}.${process.pid}.tmp`
|
|
183
|
+
await writeFile(temporary, `${JSON.stringify({ format: QUESTIONS_FORMAT, book, code, next, questions }, null, 2)}\n`, 'utf8')
|
|
184
|
+
await rename(temporary, target)
|
|
185
|
+
return { format: QUESTIONS_FORMAT, next, questions }
|
|
186
|
+
}
|