dsh-pdf-workbench 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +29 -7
  2. package/client.js +4106 -469
  3. package/docs/LAYOUT.md +56 -0
  4. package/docs/RELEASE.md +8 -0
  5. package/docs/TESTING.md +16 -0
  6. package/docs/ci.md +18 -13
  7. package/docs/copy/templates.md +4 -4
  8. package/docs/decisions.md +119 -0
  9. package/docs/features.md +14 -8
  10. package/docs/requirements/2026-11-25-v1.5/346/224/271/350/277/233/351/234/200/346/261/202.md +622 -0
  11. package/docs/roles/{release-manager.md → ci.md} +37 -47
  12. package/docs/roles/programmer.md +45 -59
  13. package/docs/roles/requirements.md +68 -0
  14. package/docs/todo.md +590 -32
  15. package/index.js +337 -1
  16. package/package.json +1 -1
  17. package/src/host/backup.js +172 -33
  18. package/src/host/book-wizard.js +454 -0
  19. package/src/host/digest.js +4 -0
  20. package/src/host/engine.js +88 -0
  21. package/src/host/exports.js +159 -0
  22. package/src/host/http.js +28 -1
  23. package/src/host/imports.js +650 -0
  24. package/src/host/index-source.js +117 -11
  25. package/src/host/library-export.js +162 -0
  26. package/src/host/pdf-source.js +6 -2
  27. package/src/host/routes.js +1020 -120
  28. package/src/host/shortcut.js +238 -0
  29. package/src/host/storage.js +421 -0
  30. package/src/host/translate-blocks.js +49 -45
  31. package/src/host/translate-job.js +37 -10
  32. package/src/host/translate.js +19 -45
  33. package/src/host/translation-cache.js +209 -0
  34. package/src/host/typst-install.js +132 -0
  35. package/src/host/zip.js +486 -4
  36. package/tools/latex_to_typst.py +1353 -0
  37. package/tools/md2overlay.py +147 -152
  38. package/tools/md2overlay_typst.py +312 -0
  39. package/tools/md2typst.py +818 -0
  40. package/tools/overlay_layout.py +332 -0
  41. package/tools/pdf_blocks.py +82 -10
  42. package/tools/realign_overlay.py +4 -1
  43. package/tools/rebuild_overlay.py +3 -1
  44. package/tools/split_pdf.py +158 -0
  45. package/tools/typst_runtime.py +98 -0
  46. package/vendor/katex/LICENSE +21 -0
  47. package/vendor/katex/fonts/KaTeX_AMS-Regular.woff2 +0 -0
  48. package/vendor/katex/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  49. package/vendor/katex/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  50. package/vendor/katex/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
  51. package/vendor/katex/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  52. package/vendor/katex/fonts/KaTeX_Main-Bold.woff2 +0 -0
  53. package/vendor/katex/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  54. package/vendor/katex/fonts/KaTeX_Main-Italic.woff2 +0 -0
  55. package/vendor/katex/fonts/KaTeX_Main-Regular.woff2 +0 -0
  56. package/vendor/katex/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  57. package/vendor/katex/fonts/KaTeX_Math-Italic.woff2 +0 -0
  58. package/vendor/katex/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  59. package/vendor/katex/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  60. package/vendor/katex/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  61. package/vendor/katex/fonts/KaTeX_Script-Regular.woff2 +0 -0
  62. package/vendor/katex/fonts/KaTeX_Size1-Regular.woff2 +0 -0
  63. package/vendor/katex/fonts/KaTeX_Size2-Regular.woff2 +0 -0
  64. package/vendor/katex/fonts/KaTeX_Size3-Regular.woff2 +0 -0
  65. package/vendor/katex/fonts/KaTeX_Size4-Regular.woff2 +0 -0
  66. package/vendor/katex/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  67. package/vendor/katex/katex.min.css +1 -0
  68. package/vendor/katex/katex.min.js +1 -0
  69. package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +9 -1
  70. package/docs/boss-handover.md +0 -84
  71. package/docs/roles/auditor.md +0 -123
  72. package/docs/roles/boss.md +0 -162
  73. package/docs/roles/code-reviewer.md +0 -132
  74. package/docs/roles/feature-inventory.md +0 -119
  75. package/docs/roles/feedback-collector.md +0 -105
  76. package/docs/roles/tester.md +0 -140
  77. package/docs/roles/ui-copywriter.md +0 -122
  78. package/src/host/book-import.js +0 -98
@@ -0,0 +1,650 @@
1
+ /**
2
+ * The one import pipeline.
3
+ *
4
+ * Every file that enters the plugin from outside — a browser upload, a book
5
+ * pack, a migration package — passes the same checks in the same order:
6
+ * file-name whitelist, magic bytes, size ceiling, staged file, atomic rename.
7
+ * Identical content already in the destination counts as a duplicate and never
8
+ * lands twice; a name clash gets the unified `-2, -3…` suffix.
9
+ *
10
+ * Nothing here decides *where* a file goes: the caller resolves the library
11
+ * folder and passes it as `targetDir`, which keeps `/pdfdesk/*` policy in
12
+ * `routes.js` and the checks in one testable module.
13
+ *
14
+ * @module dsh-pdf-workbench/imports
15
+ */
16
+ import { createHash, randomUUID } from 'node:crypto'
17
+ import { createReadStream, createWriteStream } from 'node:fs'
18
+ import { copyFile, lstat, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
19
+ import { tmpdir } from 'node:os'
20
+ import { basename, extname, join } from 'node:path'
21
+
22
+ import { resolveShortcutTarget } from './shortcut.js'
23
+ import { listZipEntries, pipeZipEntry, safeZipName, ZipError } from './zip.js'
24
+
25
+ /** One PDF / markdown / text upload, in bytes (64 MB). */
26
+ export const MAX_UPLOAD_BYTES = 64 * 1024 * 1024
27
+
28
+ /** One file inside a book pack (2 GB). */
29
+ export const MAX_ARCHIVE_FILE_BYTES = 2 * 1024 * 1024 * 1024
30
+
31
+ /** Uncompressed total of one book pack (4 GB). */
32
+ export const MAX_ARCHIVE_TOTAL_BYTES = 4 * 1024 * 1024 * 1024
33
+
34
+ /** Extensions each import kind accepts. */
35
+ const ALLOWED = {
36
+ pdf: ['.pdf'],
37
+ md: ['.md', '.markdown', '.txt'],
38
+ archive: ['.zip'],
39
+ }
40
+
41
+ /** Shortcut containers Windows produces; never importable, whatever their bytes say. */
42
+ const SHORTCUT_EXTENSIONS = ['.lnk', '.url', '.desktop', '.appref-ms', '.pif', '.scr', '.website']
43
+
44
+ /** Explorer's own files, which users sometimes drag in by accident. */
45
+ const SYSTEM_NAMES = ['desktop.ini', 'thumbs.db', '.ds_store']
46
+
47
+ /** Names Windows refuses to create, so a library copy would fail later. */
48
+ const DEVICE_NAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i
49
+
50
+ /** Characters Windows forbids in a file name. */
51
+ const ILLEGAL = /[\\/:*?"<>|\u0000-\u001f]/g
52
+
53
+ /** The library shows names in a single line; 160 keeps the extension visible. */
54
+ const MAX_NAME_LENGTH = 160
55
+
56
+ /** PDF header, per ISO 32000. */
57
+ const PDF_SIGNATURE = Buffer.from('%PDF-', 'latin1')
58
+
59
+ /**
60
+ * A refusal the caller can turn into a 4xx without inspecting messages.
61
+ */
62
+ export class RejectError extends Error {
63
+ /**
64
+ * @param {string} code - stable machine code (`fake-pdf`, `too-large`, ...).
65
+ * @param {string} message - user-facing reason, already localized.
66
+ */
67
+ constructor(code, message) {
68
+ super(message)
69
+ this.name = 'RejectError'
70
+ this.code = code
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Turn a proposed name into the name that may be written, or refuse it.
76
+ * Directory parts are dropped: an import lands in one folder by design.
77
+ * @param {string} rawName - the browser's or archive entry's name.
78
+ * @param {string[]} allowed - extensions this kind accepts, e.g. `['.pdf']`.
79
+ * @param {string} [label] - noun used in refusals ("书籍包").
80
+ * @returns {string} the safe file name.
81
+ */
82
+ export function sanitizeName(rawName, allowed, label = '文件') {
83
+ const leaf = String(rawName ?? '').split(/[\\/]/).pop() ?? ''
84
+ const trimmed = leaf.trim()
85
+ if (trimmed === '' || trimmed === '.' || trimmed === '..') {
86
+ throw new RejectError('bad-name', `文件名不合法:${trimmed === '' ? '(空)' : trimmed}`)
87
+ }
88
+ const lowered = trimmed.toLowerCase()
89
+ const extension = extname(lowered)
90
+ if (SYSTEM_NAMES.includes(lowered)) throw new RejectError('blocked-name', `系统文件不能导入:${trimmed}`)
91
+ if (trimmed.startsWith('.') || trimmed.startsWith('~$')) throw new RejectError('blocked-name', `隐藏文件不能导入:${trimmed}`)
92
+ if (SHORTCUT_EXTENSIONS.includes(extension)) throw new RejectError('shortcut', `不允许导入快捷方式:${trimmed}`)
93
+ if (!allowed.includes(extension)) throw new RejectError('bad-extension', `只接受 ${allowed.join(' / ')} ${label}:${trimmed}`)
94
+ const replaced = trimmed.replace(ILLEGAL, '_').replace(/[. ]+$/, '')
95
+ const safeExtension = extname(replaced)
96
+ const stem = replaced.slice(0, replaced.length - safeExtension.length).slice(0, MAX_NAME_LENGTH - safeExtension.length).trim()
97
+ if (stem === '') throw new RejectError('bad-name', `文件名不合法:${trimmed}`)
98
+ if (DEVICE_NAME.test(stem)) throw new RejectError('reserved-name', `Windows 保留名不能用作文件名:${replaced}`)
99
+ return `${stem}${safeExtension}`
100
+ }
101
+
102
+ /**
103
+ * Refuse bytes that do not match their claimed kind.
104
+ * @param {'pdf'|'md'|'archive'} kind - what the caller says the bytes are.
105
+ * @param {Buffer} bytes - the content.
106
+ * @returns {void}
107
+ */
108
+ export function checkMagic(kind, bytes) {
109
+ if (kind === 'pdf') {
110
+ if (bytes.length < PDF_SIGNATURE.length || !bytes.subarray(0, PDF_SIGNATURE.length).equals(PDF_SIGNATURE)) {
111
+ throw new RejectError('fake-pdf', '不是有效的 PDF(文件头不是 %PDF-)')
112
+ }
113
+ return
114
+ }
115
+ if (kind === 'archive') {
116
+ const zip = bytes.length >= 4
117
+ && bytes[0] === 0x50
118
+ && bytes[1] === 0x4b
119
+ && ((bytes[2] === 0x03 && bytes[3] === 0x04) || (bytes[2] === 0x05 && bytes[3] === 0x06))
120
+ if (!zip) throw new RejectError('bad-archive', '不是有效的 ZIP(文件头不是 PK)')
121
+ return
122
+ }
123
+ if (kind === 'md') {
124
+ try {
125
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes)
126
+ } catch {
127
+ throw new RejectError('bad-encoding', '文本不是 UTF-8 编码')
128
+ }
129
+ if (bytes.includes(0)) throw new RejectError('bad-encoding', '文件里有二进制内容')
130
+ return
131
+ }
132
+ throw new RejectError('bad-kind', `未知的导入类型:${kind}`)
133
+ }
134
+
135
+ /**
136
+ * Human-readable ceiling for error messages ("64 MB", "4 GB").
137
+ * @param {number} bytes - a limit.
138
+ * @returns {string} the label.
139
+ */
140
+ export function formatLimit(bytes) {
141
+ if (bytes >= 1024 * 1024 * 1024) return `${Math.round(bytes / (1024 * 1024 * 1024))} GB`
142
+ return `${Math.round(bytes / (1024 * 1024))} MB`
143
+ }
144
+
145
+ /**
146
+ * One empty report; every import returns this shape.
147
+ * @param {string} targetDir - the folder the report describes.
148
+ * @returns {{ targetDir: string, imported: object[], duplicates: object[], renamed: object[], skipped: object[], rejected: object[] }} the report.
149
+ */
150
+ function emptyReport(targetDir) {
151
+ return { targetDir, imported: [], duplicates: [], renamed: [], skipped: [], rejected: [] }
152
+ }
153
+
154
+ /**
155
+ * @param {string} path - file.
156
+ * @returns {Promise<string>} hex sha256 of the file's bytes.
157
+ */
158
+ function hashFile(path) {
159
+ return new Promise((resolve, reject) => {
160
+ const hash = createHash('sha256')
161
+ const stream = createReadStream(path)
162
+ stream.on('data', chunk => hash.update(chunk))
163
+ stream.on('error', reject)
164
+ stream.on('end', () => resolve(hash.digest('hex')))
165
+ })
166
+ }
167
+
168
+ /**
169
+ * The first bytes of a file on disk, without reading the rest of it.
170
+ * @param {string} path - file.
171
+ * @param {number} length - how many bytes to read.
172
+ * @returns {Promise<Buffer>} up to `length` bytes.
173
+ */
174
+ async function fileHead(path, length) {
175
+ const handle = await open(path, 'r')
176
+ try {
177
+ const head = Buffer.alloc(length)
178
+ const { bytesRead } = await handle.read(head, 0, length, 0)
179
+ return head.subarray(0, bytesRead)
180
+ } finally {
181
+ await handle.close()
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Files already in one folder, grouped by size so only same-size files are hashed.
187
+ * @param {string} dir - destination folder.
188
+ * @returns {Promise<Map<number, string[]>>} size → names.
189
+ */
190
+ async function buildSizeIndex(dir) {
191
+ const index = new Map()
192
+ const names = await readdir(dir).catch(() => [])
193
+ for (const name of names) {
194
+ const info = await lstat(join(dir, name)).catch(() => null)
195
+ if (info === null || !info.isFile()) continue
196
+ if (!index.has(info.size)) index.set(info.size, [])
197
+ index.get(info.size).push(name)
198
+ }
199
+ return index
200
+ }
201
+
202
+ /**
203
+ * The existing file with the same content, if any.
204
+ * @param {string} dir - destination folder.
205
+ * @param {Map<number, string[]>} index - size index of `dir`.
206
+ * @param {number} size - candidate size.
207
+ * @param {string} hash - candidate sha256.
208
+ * @returns {Promise<string|null>} the existing name, or null.
209
+ */
210
+ async function duplicateIn(dir, index, size, hash) {
211
+ const candidates = index.get(size)
212
+ if (candidates === undefined) return null
213
+ for (const name of candidates) {
214
+ if (await hashFile(join(dir, name)).catch(() => null) === hash) return name
215
+ }
216
+ return null
217
+ }
218
+
219
+ /**
220
+ * Pick the first free name, starting the suffix at `-2` everywhere.
221
+ * @param {string} dir - destination folder.
222
+ * @param {string} name - wanted name.
223
+ * @returns {Promise<string>} a name no file in `dir` uses.
224
+ */
225
+ async function freeName(dir, name) {
226
+ if (await lstat(join(dir, name)).catch(() => null) === null) return name
227
+ const extension = extname(name)
228
+ const stem = extension === '' ? name : name.slice(0, -extension.length)
229
+ for (let counter = 2; counter < 1000; counter += 1) {
230
+ const candidate = `${stem}-${counter}${extension}`
231
+ if (await lstat(join(dir, candidate)).catch(() => null) === null) return candidate
232
+ }
233
+ throw new RejectError('too-many-names', `同名文件太多:${name}`)
234
+ }
235
+
236
+ /**
237
+ * Refuse a destination that is a link or reparse point.
238
+ * @param {string} path - destination.
239
+ * @returns {Promise<void>}
240
+ */
241
+ async function rejectSymlink(path) {
242
+ const info = await lstat(path).catch(() => null)
243
+ if (info !== null && info.isSymbolicLink()) throw new RejectError('symlink', `拒绝写入符号链接:${basename(path)}`)
244
+ }
245
+
246
+ /**
247
+ * Move a staged file into place; `rename` stays atomic on one volume, and the
248
+ * copy fallback keeps the destination folder's own temp file so a reader never
249
+ * sees a half-written PDF.
250
+ * @param {string} targetDir - destination folder.
251
+ * @param {string} name - final name.
252
+ * @param {string} stagedPath - complete file to move.
253
+ * @returns {Promise<string>} the final absolute path.
254
+ */
255
+ async function moveInto(targetDir, name, stagedPath) {
256
+ const target = join(targetDir, name)
257
+ try {
258
+ await rename(stagedPath, target)
259
+ } catch (error) {
260
+ if (error === null || error.code !== 'EXDEV') throw error
261
+ const temporary = join(targetDir, `.${name}.${process.pid}.importing`)
262
+ await copyFile(stagedPath, temporary)
263
+ await rename(temporary, target)
264
+ await rm(stagedPath, { force: true })
265
+ }
266
+ return target
267
+ }
268
+
269
+ /**
270
+ * Check only the ZIP signature of a file on disk (archives may be too large to
271
+ * read just to look at four bytes).
272
+ * @param {string} path - the archive to inspect.
273
+ * @returns {Promise<void>}
274
+ */
275
+ export async function checkArchiveFile(path) {
276
+ const handle = await open(path, 'r')
277
+ try {
278
+ const header = Buffer.alloc(4)
279
+ const { bytesRead } = await handle.read(header, 0, 4, 0)
280
+ checkMagic('archive', header.subarray(0, bytesRead))
281
+ } finally {
282
+ await handle.close()
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Read a request body into a temp file, enforcing the ceiling while streaming.
288
+ * The caller owns the returned path and must delete it.
289
+ * @param {import('node:http').IncomingMessage} request - inbound request.
290
+ * @param {{ dataDir: string, limit: number, extension?: string }} options - destination folder, ceiling and suffix.
291
+ * @returns {Promise<{ path: string, bytes: number }>} the staged file.
292
+ */
293
+ export async function receiveUpload(request, options) {
294
+ const tmpDir = join(options.dataDir, 'tmp')
295
+ await mkdir(tmpDir, { recursive: true })
296
+ const file = join(tmpDir, `import-${randomUUID()}${options.extension ?? ''}`)
297
+ const handle = await open(file, 'w')
298
+ let total = 0
299
+ try {
300
+ for await (const chunk of request) {
301
+ total += chunk.length
302
+ if (total > options.limit) throw new RejectError('too-large', `上传内容超过 ${formatLimit(options.limit)}`)
303
+ await handle.write(chunk)
304
+ }
305
+ } catch (error) {
306
+ await handle.close().catch(() => {})
307
+ await rm(file, { force: true }).catch(() => {})
308
+ throw error
309
+ }
310
+ await handle.close()
311
+ if (total === 0) {
312
+ await rm(file, { force: true }).catch(() => {})
313
+ throw new RejectError('empty', '上传内容为空')
314
+ }
315
+ return { path: file, bytes: total }
316
+ }
317
+
318
+ /** One queue per destination folder, so two imports cannot pick the same free name. */
319
+ const queues = new Map()
320
+
321
+ /**
322
+ * Run one import action after every earlier action on the same folder.
323
+ * @param {string} dir - destination folder.
324
+ * @param {() => Promise<unknown>} action - the work.
325
+ * @returns {Promise<unknown>} the action's result.
326
+ */
327
+ function withDirLock(dir, action) {
328
+ const previous = queues.get(dir) ?? Promise.resolve()
329
+ const run = previous.then(action, action)
330
+ const tail = run.then(() => {}, () => {})
331
+ queues.set(dir, tail)
332
+ tail.then(() => {
333
+ if (queues.get(dir) === tail) queues.delete(dir)
334
+ })
335
+ return run
336
+ }
337
+
338
+ /**
339
+ * Import one already-staged PDF, markdown or text file.
340
+ *
341
+ * Markdown and text are rendered to PDF first; the rendered PDF is what the
342
+ * duplicate check and naming see, so re-importing the same text stays a
343
+ * duplicate. The staged source is consumed or deleted either way.
344
+ *
345
+ * @param {{ targetDir: string, dataDir: string, name: string, kind: 'pdf'|'md', sourcePath: string, render?: (source: string, outPath: string) => Promise<string> }} options - destination, staged upload and renderer.
346
+ * @returns {Promise<{ targetDir: string, imported: object[], duplicates: object[], renamed: object[], skipped: object[], rejected: object[] }>} the report.
347
+ */
348
+ export async function importSingle(options) {
349
+ return withDirLock(options.targetDir, () => importSingleLocked(options))
350
+ }
351
+
352
+ /**
353
+ * @param {{ targetDir: string, dataDir: string, name: string, kind: 'pdf'|'md', sourcePath: string, maxBytes?: number, render?: (source: string, outPath: string) => Promise<string> }} options - destination, staged upload, optional size ceiling and renderer.
354
+ * @returns {Promise<{ targetDir: string, imported: object[], duplicates: object[], renamed: object[], skipped: object[], rejected: object[] }>} the report.
355
+ */
356
+ async function importSingleLocked(options) {
357
+ const allowed = ALLOWED[options.kind]
358
+ if (allowed === undefined) throw new RejectError('bad-kind', `未知的导入类型:${options.kind}`)
359
+ const limit = Number.isFinite(options.maxBytes) && options.maxBytes > 0 ? options.maxBytes : MAX_UPLOAD_BYTES
360
+ const report = emptyReport(options.targetDir)
361
+ await mkdir(options.targetDir, { recursive: true })
362
+ // A Windows shortcut is never stored: the PDF behind it is imported instead.
363
+ // Only the PDF channel resolves one; md/txt uploads keep the old refusal.
364
+ if (options.kind === 'pdf' && isShortcutUpload(options.name)) {
365
+ try {
366
+ await importShortcutTarget({
367
+ stagedPath: options.sourcePath,
368
+ targetDir: options.targetDir,
369
+ dataDir: options.dataDir,
370
+ limit,
371
+ report,
372
+ })
373
+ return report
374
+ } finally {
375
+ await rm(options.sourcePath, { force: true }).catch(() => {})
376
+ }
377
+ }
378
+ const name = sanitizeName(options.name, allowed)
379
+ let stagedPath = options.sourcePath
380
+ let stagedOwned = false
381
+ try {
382
+ const info = await stat(stagedPath)
383
+ if (info.size === 0) throw new RejectError('empty', `文件是空的:${name}`)
384
+ if (info.size > limit) throw new RejectError('too-large', `单个文件不能超过 ${formatLimit(limit)}:${name}`)
385
+ checkMagic(options.kind, await readFile(stagedPath))
386
+ let storedName = name
387
+ if (options.kind === 'md') {
388
+ if (typeof options.render !== 'function') {
389
+ throw new RejectError('render-unavailable', '导入 md/txt 需要 Python 与 TeX Live(xelatex)')
390
+ }
391
+ const extension = extname(name)
392
+ storedName = `${name.slice(0, name.length - extension.length)}.pdf`
393
+ stagedPath = join(options.dataDir, 'tmp', `import-${randomUUID()}.pdf`)
394
+ stagedOwned = true
395
+ await options.render(options.sourcePath, stagedPath)
396
+ const rendered = await stat(stagedPath).catch(() => null)
397
+ if (rendered === null || rendered.size === 0) throw new RejectError('render-failed', '渲染没有生成 PDF')
398
+ }
399
+ const stagedInfo = await stat(stagedPath)
400
+ const hash = await hashFile(stagedPath)
401
+ const index = await buildSizeIndex(options.targetDir)
402
+ const duplicate = await duplicateIn(options.targetDir, index, stagedInfo.size, hash)
403
+ if (duplicate !== null) {
404
+ report.duplicates.push({ name: storedName, existing: duplicate })
405
+ return report
406
+ }
407
+ const finalName = await freeName(options.targetDir, storedName)
408
+ await rejectSymlink(join(options.targetDir, finalName))
409
+ const target = await moveInto(options.targetDir, finalName, stagedPath)
410
+ report.imported.push({ name: finalName, path: target, bytes: stagedInfo.size })
411
+ if (finalName !== storedName) report.renamed.push({ from: storedName, to: finalName })
412
+ return report
413
+ } finally {
414
+ await rm(options.sourcePath, { force: true }).catch(() => {})
415
+ if (stagedOwned) await rm(stagedPath, { force: true }).catch(() => {})
416
+ }
417
+ }
418
+
419
+ /**
420
+ * Whether an upload is a Windows shortcut whose target should be imported.
421
+ * Only `.lnk` is resolved; every other shortcut container stays refused.
422
+ * @param {string} rawName - the browser's file name.
423
+ * @returns {boolean} true when the PDF behind the shortcut is what to import.
424
+ */
425
+ function isShortcutUpload(rawName) {
426
+ const leaf = String(rawName ?? '').split(/[\\/]/).pop() ?? ''
427
+ const trimmed = leaf.trim()
428
+ return trimmed.length > '.lnk'.length && trimmed.toLowerCase().endsWith('.lnk')
429
+ }
430
+
431
+ /**
432
+ * Classify a shortcut's target path, so a network location keeps its own reason
433
+ * instead of a generic "unreadable".
434
+ * @param {string} path - the path the shortcut stores.
435
+ * @returns {'local'|'network'|'other'} the kind.
436
+ */
437
+ function shortcutPathKind(path) {
438
+ const text = String(path)
439
+ if (/^[\\/]{2}\?[\\/]UNC[\\/]/i.test(text)) return 'network'
440
+ if (/^[\\/]{2}[.?][\\/]/.test(text)) {
441
+ // `\\?\C:\…` is still a local file; other device namespaces are not.
442
+ return /^[\\/]{2}\?[\\/][A-Za-z]:[\\/]/.test(text) ? 'local' : 'other'
443
+ }
444
+ if (/^[\\/]{2}/.test(text)) return 'network'
445
+ return /^[A-Za-z]:[\\/]/.test(text) ? 'local' : 'other'
446
+ }
447
+
448
+ /**
449
+ * Import the PDF a shortcut points at.
450
+ *
451
+ * The `.lnk` itself never enters the library: its target is copied into the
452
+ * staging folder and then runs through the normal PDF checks, de-duplication,
453
+ * `-2` naming and atomic move, so the stored name is the target's own name. The
454
+ * copy is what gets moved, never the user's file.
455
+ *
456
+ * @param {{ stagedPath: string, targetDir: string, dataDir: string, limit: number, report: object }} options - staged shortcut, destination, ceiling and the report to fill.
457
+ * @returns {Promise<void>}
458
+ */
459
+ async function importShortcutTarget(options) {
460
+ const resolved = resolveShortcutTarget(await readFile(options.stagedPath))
461
+ if (resolved === null) {
462
+ throw new RejectError('shortcut-bad', '这个快捷方式读不出目标路径(可能已损坏)。请直接拖原 PDF 到书库。')
463
+ }
464
+ const targetPath = resolved.path
465
+ const kind = shortcutPathKind(targetPath)
466
+ if (kind === 'network') {
467
+ throw new RejectError('shortcut-network', `快捷方式指向网络位置:${targetPath}。请先把 PDF 复制到本机再拖进书库。`)
468
+ }
469
+ if (kind !== 'local') {
470
+ throw new RejectError('shortcut-bad', `无法使用快捷方式的目标路径:${targetPath}。请直接拖原 PDF 到书库。`)
471
+ }
472
+ const info = await stat(targetPath).catch(() => null)
473
+ if (info === null) {
474
+ throw new RejectError('shortcut-missing', `快捷方式的目标不存在:${targetPath}。请直接拖原 PDF 到书库。`)
475
+ }
476
+ if (!info.isFile() || extname(targetPath).toLowerCase() !== '.pdf') {
477
+ throw new RejectError('shortcut-type', `快捷方式的目标不是 PDF 文件:${targetPath}。请直接拖原 PDF 到书库。`)
478
+ }
479
+ if (info.size > options.limit) {
480
+ throw new RejectError('too-large', `快捷方式的目标超过 ${formatLimit(options.limit)}:${targetPath}。请直接拖原 PDF 到书库。`)
481
+ }
482
+ const tmpDir = join(options.dataDir, 'tmp')
483
+ await mkdir(tmpDir, { recursive: true })
484
+ const stagedPath = join(tmpDir, `import-${randomUUID()}.pdf`)
485
+ try {
486
+ await copyFile(targetPath, stagedPath)
487
+ } catch {
488
+ await rm(stagedPath, { force: true }).catch(() => {})
489
+ throw new RejectError('shortcut-missing', `读不到快捷方式的目标:${targetPath}。请直接拖原 PDF 到书库。`)
490
+ }
491
+ try {
492
+ const imported = await importSingleLocked({
493
+ targetDir: options.targetDir,
494
+ dataDir: options.dataDir,
495
+ name: basename(targetPath),
496
+ kind: 'pdf',
497
+ sourcePath: stagedPath,
498
+ maxBytes: options.limit,
499
+ })
500
+ for (const item of imported.imported) {
501
+ options.report.imported.push({ ...item, source: 'shortcut', target: targetPath })
502
+ }
503
+ for (const item of imported.duplicates) {
504
+ options.report.duplicates.push({ ...item, source: 'shortcut', target: targetPath })
505
+ }
506
+ options.report.renamed.push(...imported.renamed)
507
+ } finally {
508
+ // The pipeline moves the copy into the library, so this only matters when it
509
+ // refuses the target's name before staging: no temp file is left behind.
510
+ await rm(stagedPath, { force: true }).catch(() => {})
511
+ }
512
+ }
513
+
514
+ /**
515
+ * Import a book pack: every PDF entry goes through the same checks as an
516
+ * upload, and identical content is skipped even in `overwrite` mode.
517
+ *
518
+ * The archive is unpacked entry by entry (streamed through a temp file in the
519
+ * destination), never read into memory as a whole.
520
+ *
521
+ * @param {{ archivePath?: string, bytes?: Buffer, dataDir?: string, targetDir: string, strategy?: 'merge'|'overwrite'|'skip' }} options - archive, destination and clash policy.
522
+ * @returns {Promise<{ targetDir: string, imported: object[], duplicates: object[], renamed: object[], skipped: object[], rejected: object[] }>} the report.
523
+ */
524
+ export async function importArchive(options) {
525
+ return withDirLock(options.targetDir, () => importArchiveLocked(options))
526
+ }
527
+
528
+ /**
529
+ * Write caller-supplied archive bytes to a temp file, so an in-memory archive
530
+ * still takes the streaming path. The caller owns the file it gets back.
531
+ * @param {{ bytes: Buffer, dataDir?: string }} options - the archive bytes and the plugin data folder, if known.
532
+ * @returns {Promise<string>} path of the staged archive.
533
+ */
534
+ async function stageArchiveBytes(options) {
535
+ const base = typeof options.dataDir === 'string' && options.dataDir !== '' ? join(options.dataDir, 'tmp') : tmpdir()
536
+ await mkdir(base, { recursive: true })
537
+ const path = join(base, `import-${randomUUID()}.zip`)
538
+ await writeFile(path, options.bytes)
539
+ return path
540
+ }
541
+
542
+ /**
543
+ * @param {{ archivePath?: string, bytes?: Buffer, dataDir?: string, targetDir: string, strategy?: 'merge'|'overwrite'|'skip' }} options - archive, destination and clash policy.
544
+ * @returns {Promise<{ targetDir: string, imported: object[], duplicates: object[], renamed: object[], skipped: object[], rejected: object[] }>} the report.
545
+ */
546
+ async function importArchiveLocked(options) {
547
+ const strategy = options.strategy === 'overwrite' || options.strategy === 'skip' ? options.strategy : 'merge'
548
+ const targetDir = options.targetDir
549
+ // A caller may still hand the archive over as bytes; stage it and stream from
550
+ // disk like every other archive, so no import path buffers a whole pack.
551
+ let archivePath = typeof options.archivePath === 'string' ? options.archivePath : ''
552
+ let stagedArchive = null
553
+ if (options.bytes !== undefined) {
554
+ checkMagic('archive', options.bytes)
555
+ stagedArchive = await stageArchiveBytes(options)
556
+ archivePath = stagedArchive
557
+ }
558
+ try {
559
+ if (stagedArchive === null) await checkArchiveFile(archivePath)
560
+ let entries
561
+ try {
562
+ entries = await listZipEntries(archivePath)
563
+ } catch (error) {
564
+ // A damaged or path-traversing archive is the user's file being unusable,
565
+ // not a Host failure.
566
+ throw new RejectError('bad-archive', String(error && error.message ? error.message : error))
567
+ }
568
+ await mkdir(targetDir, { recursive: true })
569
+ const report = emptyReport(targetDir)
570
+ const index = await buildSizeIndex(targetDir)
571
+ let total = 0
572
+ for (const entry of entries) {
573
+ const entryName = entry.name
574
+ // Directory entries carry no file.
575
+ if (entryName.endsWith('/')) continue
576
+ let name
577
+ try {
578
+ const safe = safeZipName(entryName)
579
+ name = basename(safe)
580
+ name = sanitizeName(name, ALLOWED.pdf, '书籍包')
581
+ } catch (error) {
582
+ report.rejected.push({
583
+ name: entryName,
584
+ reason: error instanceof RejectError ? error.message : String(error && error.message ? error.message : error),
585
+ })
586
+ continue
587
+ }
588
+ if (entry.size === 0) {
589
+ report.rejected.push({ name, reason: '文件是空的' })
590
+ continue
591
+ }
592
+ if (entry.size > MAX_ARCHIVE_FILE_BYTES) {
593
+ report.rejected.push({ name, reason: `单个文件超过 ${formatLimit(MAX_ARCHIVE_FILE_BYTES)}` })
594
+ continue
595
+ }
596
+ total += entry.size
597
+ if (total > MAX_ARCHIVE_TOTAL_BYTES) {
598
+ report.rejected.push({ name, reason: `压缩包总量超过 ${formatLimit(MAX_ARCHIVE_TOTAL_BYTES)},其余文件未导入` })
599
+ break
600
+ }
601
+ // Unpack one entry into the destination folder: the temp file is on the
602
+ // same volume as its final name, so the last step is an atomic rename.
603
+ const stagedPath = join(targetDir, `.import-${randomUUID()}.pdf`)
604
+ let streamed
605
+ try {
606
+ streamed = await pipeZipEntry(archivePath, entry, createWriteStream(stagedPath))
607
+ checkMagic('pdf', await fileHead(stagedPath, PDF_SIGNATURE.length))
608
+ } catch (error) {
609
+ await rm(stagedPath, { force: true }).catch(() => {})
610
+ if (error instanceof RejectError) {
611
+ report.rejected.push({ name, reason: error.message })
612
+ continue
613
+ }
614
+ if (error instanceof ZipError) {
615
+ report.rejected.push({ name, reason: `压缩包数据损坏:${error.message}` })
616
+ continue
617
+ }
618
+ throw error
619
+ }
620
+ const hash = streamed.sha256
621
+ let moved = false
622
+ try {
623
+ const duplicate = await duplicateIn(targetDir, index, streamed.bytes, hash)
624
+ if (duplicate !== null) {
625
+ report.duplicates.push({ name, existing: duplicate })
626
+ continue
627
+ }
628
+ const exists = await lstat(join(targetDir, name)).catch(() => null)
629
+ let finalName = name
630
+ if (exists !== null && strategy === 'skip') {
631
+ report.skipped.push({ name, reason: '目标目录已有同名文件' })
632
+ continue
633
+ }
634
+ if (exists !== null && strategy === 'merge') finalName = await freeName(targetDir, name)
635
+ if (exists !== null && strategy === 'overwrite') await rejectSymlink(join(targetDir, name))
636
+ await rename(stagedPath, join(targetDir, finalName))
637
+ moved = true
638
+ if (!index.has(streamed.bytes)) index.set(streamed.bytes, [])
639
+ index.get(streamed.bytes).push(finalName)
640
+ report.imported.push({ name: finalName, path: join(targetDir, finalName), bytes: streamed.bytes })
641
+ if (finalName !== name) report.renamed.push({ from: name, to: finalName })
642
+ } finally {
643
+ if (!moved) await rm(stagedPath, { force: true }).catch(() => {})
644
+ }
645
+ }
646
+ return report
647
+ } finally {
648
+ if (stagedArchive !== null) await rm(stagedArchive, { force: true }).catch(() => {})
649
+ }
650
+ }