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
@@ -7,15 +7,23 @@
7
7
 
8
8
  import { execFile } from 'node:child_process'
9
9
  import { createHash, randomUUID } from 'node:crypto'
10
- import { promisify } from 'node:util'
10
+ import { createWriteStream } from 'node:fs'
11
11
  import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
12
+ import { Writable } from 'node:stream'
13
+ import { promisify } from 'node:util'
12
14
  import { dirname, join } from 'node:path'
13
15
 
14
- import { readZip, safeZipName, writeZip } from './zip.js'
16
+ import { listZipEntries, pipeZipEntry, readZipEntryBuffer, safeZipName, writeZipFile, ZipError } from './zip.js'
15
17
 
16
18
  /** Version of the manifest schema. */
17
19
  export const BACKUP_FORMAT = 1
18
20
 
21
+ /**
22
+ * Largest single entry a migration package may carry when it is read into
23
+ * memory; anything bigger is refused instead of buffered.
24
+ */
25
+ export const MAX_BACKUP_ENTRY_BYTES = 512 * 1024 * 1024
26
+
19
27
  /** Plugin-state files that travel with a backup (never credentials). */
20
28
  export const PLUGIN_STATE_FILES = ['libraries.json', 'state.json', 'pending.json', 'links.json', 'pressure.json', 'shelves.json', 'qa-persona.md']
21
29
 
@@ -33,6 +41,27 @@ async function copyIfExists(source, target) {
33
41
  return true
34
42
  }
35
43
 
44
+ /**
45
+ * Copy one library's `.pdfdesk` without its translation cache: per-page caches
46
+ * are rebuildable and can be large, so a migration package never carries them
47
+ * (they now live inside the library, see DEC-0014 §5).
48
+ * @param {string} source - the library's `.pdfdesk` folder.
49
+ * @param {string} target - the staging destination.
50
+ * @returns {Promise<boolean>} whether anything was copied.
51
+ */
52
+ async function copyLibraryData(source, target) {
53
+ const info = await stat(source).catch(() => null)
54
+ if (info === null || !info.isDirectory()) return false
55
+ await mkdir(target, { recursive: true })
56
+ let copied = false
57
+ for (const name of await readdir(source).catch(() => [])) {
58
+ if (name === 'translation') continue
59
+ await cp(join(source, name), join(target, name), { recursive: true })
60
+ copied = true
61
+ }
62
+ return copied
63
+ }
64
+
36
65
  /**
37
66
  * Copy the selected sources into a staging tree.
38
67
  * @param {{ dataDir: string, dshHome?: string, libraries?: object[], include?: object, root?: string }} options - source locations and selection.
@@ -76,7 +105,7 @@ export async function collectBackup(options) {
76
105
  for (const library of libraries) {
77
106
  if (library === null || typeof library !== 'object' || typeof library.libraryDir !== 'string') continue
78
107
  const id = safeZipName(String(library.id ?? 'library'))
79
- const ok = await copyIfExists(join(library.libraryDir, '.pdfdesk'), join(root, 'libraries', id, '.pdfdesk'))
108
+ const ok = await copyLibraryData(join(library.libraryDir, '.pdfdesk'), join(root, 'libraries', id, '.pdfdesk'))
80
109
  if (ok) {
81
110
  included.libraryData.push(id)
82
111
  copied.push(`libraries/${id}/.pdfdesk`)
@@ -161,7 +190,7 @@ export async function walkFiles(root, base = '') {
161
190
 
162
191
  /**
163
192
  * Write `manifest.json` for a staging tree and return it.
164
- * @param {{ root: string, meta?: object }} options - staging root and extra fields (plugin version, machine, included items).
193
+ * @param {{ root: string, meta?: object, format?: number | string }} options - staging root, extra fields, and an optional format label (defaults to the migration backup format).
165
194
  * @returns {Promise<object>} the manifest.
166
195
  */
167
196
  export async function buildManifest(options) {
@@ -172,7 +201,7 @@ export async function buildManifest(options) {
172
201
  files.push({ path: name, bytes: bytes.length, sha256: sha256(bytes) })
173
202
  }
174
203
  const manifest = {
175
- format: BACKUP_FORMAT,
204
+ format: options.format === undefined ? BACKUP_FORMAT : options.format,
176
205
  createdAt: Date.now(),
177
206
  ...(options.meta === undefined ? {} : options.meta),
178
207
  files,
@@ -231,38 +260,51 @@ async function packWithPython(options) {
231
260
 
232
261
  /**
233
262
  * Pack a staging tree into a ZIP, manifest first.
234
- * @param {{ root: string, outPath: string, compress?: boolean, meta?: object }} options - source tree and destination.
263
+ *
264
+ * Entries are described by path, never by bytes: Python's `zipfile` reads them
265
+ * from disk when it is available, and the Node fallback streams them through
266
+ * `writeZipFile`, so packing a staging tree never holds it in memory.
267
+ *
268
+ * @param {{ root: string, outPath: string, compress?: boolean, meta?: object, format?: number | string }} options - source tree, destination and the optional manifest format.
235
269
  * @returns {Promise<{ outPath: string, bytes: number, files: number }>} the archive.
236
270
  */
237
271
  export async function packDirectory(options) {
238
- const manifest = await buildManifest({ root: options.root, meta: options.meta })
272
+ const manifest = await buildManifest({ root: options.root, meta: options.meta, format: options.format })
239
273
  const entries = [{ name: 'manifest.json', data: Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`, 'utf8') }]
240
- for (const file of manifest.files) {
241
- entries.push({ name: file.path, data: await readFile(join(options.root, file.path)) })
242
- }
274
+ for (const file of manifest.files) entries.push({ name: file.path, path: join(options.root, file.path) })
243
275
  const python = await packWithPython({ root: options.root, outPath: options.outPath, compress: options.compress })
244
276
  if (python !== null) return { outPath: options.outPath, bytes: python.bytes, files: entries.length }
245
- const bytes = writeZip({ entries, compress: options.compress !== false })
246
277
  await mkdir(dirname(options.outPath), { recursive: true })
247
278
  const temporary = `${options.outPath}.${process.pid}.tmp`
248
- await writeFile(temporary, bytes)
249
- await rename(temporary, options.outPath)
250
- return { outPath: options.outPath, bytes: bytes.length, files: entries.length }
279
+ try {
280
+ const packed = await writeZipFile(temporary, { entries, compress: options.compress !== false })
281
+ await rename(temporary, options.outPath)
282
+ return { outPath: options.outPath, bytes: packed.bytes, files: packed.files }
283
+ } catch (error) {
284
+ await rm(temporary, { force: true }).catch(() => {})
285
+ throw error
286
+ }
287
+ }
288
+
289
+ /** A writable that keeps nothing; used to checksum an entry without buffering it. */
290
+ function nullSink() {
291
+ return new Writable({ write(_chunk, _encoding, callback) { callback() } })
251
292
  }
252
293
 
253
294
  /**
254
- * Read a backup archive and verify every checksum before the caller touches it.
295
+ * List the archive and parse its manifest without buffering any file.
255
296
  * @param {string} archivePath - zip path.
256
- * @returns {Promise<{ manifest: object, entries: Map<string, Buffer> }>} verified content.
297
+ * @returns {Promise<{ manifest: object, listing: Array<object>, byName: Map<string, object> }>} the manifest and entry lookup.
257
298
  */
258
- export async function readBackup(archivePath) {
259
- const bytes = await readFile(archivePath)
260
- const entries = readZip(bytes)
261
- const manifestBytes = entries.get('manifest.json')
262
- if (manifestBytes === undefined) throw new Error('迁移包缺少 manifest.json')
299
+ async function inspectBackup(archivePath) {
300
+ const listing = await listZipEntries(archivePath)
301
+ const byName = new Map(listing.map(entry => [entry.name, entry]))
302
+ const manifestEntry = byName.get('manifest.json')
303
+ if (manifestEntry === undefined) throw new Error('迁移包缺少 manifest.json')
304
+ const bytes = await readZipEntryBuffer(archivePath, manifestEntry, MAX_BACKUP_ENTRY_BYTES)
263
305
  let manifest
264
306
  try {
265
- manifest = JSON.parse(manifestBytes.toString('utf8'))
307
+ manifest = JSON.parse(bytes.toString('utf8'))
266
308
  } catch {
267
309
  throw new Error('迁移包的 manifest.json 不是有效 JSON')
268
310
  }
@@ -270,18 +312,60 @@ export async function readBackup(archivePath) {
270
312
  throw new Error(`不支持的迁移包版本:${manifest === null ? '?' : manifest.format}`)
271
313
  }
272
314
  if (!Array.isArray(manifest.files)) throw new Error('迁移包 manifest 缺少文件清单')
315
+ return { manifest, listing, byName }
316
+ }
317
+
318
+ /**
319
+ * Compare every manifest record with what the archive actually contains.
320
+ * @param {object} manifest - parsed manifest.
321
+ * @param {Map<string, object>} byName - archive entries by name.
322
+ * @param {(name: string, entry: object) => Promise<{ sha256: string, bytes: number }>} measure - reads one entry, buffered or streamed.
323
+ * @returns {Promise<string[]>} one problem per mismatch, in manifest order.
324
+ */
325
+ async function verifyManifestFiles(manifest, byName, measure) {
273
326
  const problems = []
274
327
  for (const file of manifest.files) {
275
328
  const name = safeZipName(file.path)
276
- const data = entries.get(name)
277
- if (data === undefined) {
329
+ const entry = byName.get(name)
330
+ if (entry === undefined) {
278
331
  problems.push(`缺少文件:${name}`)
279
332
  continue
280
333
  }
281
- const actual = sha256(data)
282
- if (file.sha256 !== undefined && actual !== file.sha256) problems.push(`校验失败:${name}`)
283
- if (file.bytes !== undefined && data.length !== file.bytes) problems.push(`大小不符:${name}`)
334
+ let actual
335
+ try {
336
+ actual = await measure(name, entry)
337
+ } catch (error) {
338
+ if (!(error instanceof ZipError)) throw error
339
+ problems.push(`读取失败:${error.message}`)
340
+ continue
341
+ }
342
+ if (file.sha256 !== undefined && actual.sha256 !== file.sha256) problems.push(`校验失败:${name}`)
343
+ if (file.bytes !== undefined && actual.bytes !== file.bytes) problems.push(`大小不符:${name}`)
284
344
  }
345
+ return problems
346
+ }
347
+
348
+ /**
349
+ * Read a backup archive and verify every checksum before the caller touches it.
350
+ *
351
+ * The package is listed once and then read entry by entry through
352
+ * `readZipEntryBuffer`, so it is never held as a single buffer; a single entry
353
+ * above `MAX_BACKUP_ENTRY_BYTES` is refused with `ZipError` `too-large`. The
354
+ * returned shape stays the map-of-buffers callers already rely on.
355
+ *
356
+ * @param {string} archivePath - zip path.
357
+ * @returns {Promise<{ manifest: object, entries: Map<string, Buffer> }>} verified content.
358
+ */
359
+ export async function readBackup(archivePath) {
360
+ const { manifest, listing, byName } = await inspectBackup(archivePath)
361
+ const entries = new Map()
362
+ for (const entry of listing) {
363
+ entries.set(entry.name, await readZipEntryBuffer(archivePath, entry, MAX_BACKUP_ENTRY_BYTES))
364
+ }
365
+ const problems = await verifyManifestFiles(manifest, byName, async name => {
366
+ const data = entries.get(name)
367
+ return { sha256: sha256(data), bytes: data.length }
368
+ })
285
369
  if (problems.length > 0) throw new Error(`迁移包校验失败:${problems.slice(0, 5).join(';')}`)
286
370
  return { manifest, entries }
287
371
  }
@@ -394,12 +478,44 @@ async function prunePreImports(backupDir, keep = 3) {
394
478
  * Import a verified archive with explicit conflict strategies. `merge` never
395
479
  * overwrites: an existing file keeps its place and the imported copy becomes
396
480
  * `<name>.imported-<ts>`. `overwrite` replaces after a pre-import snapshot.
481
+ *
482
+ * Every checksum is checked first through `pipeZipEntry` into a null sink, so a
483
+ * damaged package still changes nothing on disk; the write pass then streams one
484
+ * entry at a time into a temporary file beside its destination and renames it,
485
+ * comparing the streamed sha256 with the manifest again.
486
+ *
397
487
  * @param {{ archivePath: string, dataDir: string, dshHome?: string,
398
488
  * libraryRoots?: Record<string, string>, strategy?: 'merge'|'overwrite'|'skip' }} options - archive and destinations.
399
489
  * @returns {Promise<object>} the import report.
400
490
  */
401
491
  export async function importBackup(options) {
402
- const { manifest, entries } = await readBackup(options.archivePath)
492
+ const archivePath = options.archivePath
493
+ const { manifest, listing, byName } = await inspectBackup(archivePath)
494
+ // One ceiling for both sides: `readBackup` refuses an entry above this, so the
495
+ // import must refuse it too instead of streaming something inspect would reject.
496
+ const oversized = listing.find(entry => entry.size > MAX_BACKUP_ENTRY_BYTES || entry.compressedSize > MAX_BACKUP_ENTRY_BYTES)
497
+ if (oversized !== undefined) {
498
+ throw new ZipError('too-large', `迁移包里有超过 ${Math.round(MAX_BACKUP_ENTRY_BYTES / 1048576)} MB 的文件:${oversized.name}`)
499
+ }
500
+ const verified = new Set()
501
+ const problems = await verifyManifestFiles(manifest, byName, async (name, entry) => {
502
+ verified.add(name)
503
+ return pipeZipEntry(archivePath, entry, nullSink())
504
+ })
505
+ // The buffered reader inflated every entry before touching the disk, so a
506
+ // damaged extra entry aborted the import too. Keep that guarantee: entries the
507
+ // manifest never mentions are streamed once for integrity, not remembered.
508
+ for (const entry of listing) {
509
+ if (entry.name === 'manifest.json' || verified.has(entry.name)) continue
510
+ try {
511
+ await pipeZipEntry(archivePath, entry, nullSink())
512
+ } catch (error) {
513
+ if (!(error instanceof ZipError)) throw error
514
+ problems.push(`读取失败:${error.message}`)
515
+ }
516
+ }
517
+ if (problems.length > 0) throw new Error(`迁移包校验失败:${problems.slice(0, 5).join(';')}`)
518
+ const declared = new Map(manifest.files.map(file => [safeZipName(file.path), file]))
403
519
  const dataDir = options.dataDir
404
520
  const dshHome = typeof options.dshHome === 'string' && options.dshHome !== '' ? options.dshHome : dirname(dataDir)
405
521
  const libraryRoots = options.libraryRoots !== null && typeof options.libraryRoots === 'object' ? options.libraryRoots : {}
@@ -424,7 +540,32 @@ export async function importBackup(options) {
424
540
  await mkdir(dirname(copy), { recursive: true })
425
541
  await cp(target, copy, { recursive: true }).catch(() => {})
426
542
  }
427
- for (const [name, bytes] of entries) {
543
+ /**
544
+ * Stream one entry to its final path: temporary sibling, checksum check
545
+ * against the manifest, then an atomic rename. The temporary file is always
546
+ * removed when anything goes wrong.
547
+ */
548
+ const place = async (entry, finalPath) => {
549
+ const directory = dirname(finalPath)
550
+ await mkdir(directory, { recursive: true })
551
+ const temporary = join(directory, `.import-${randomUUID()}.tmp`)
552
+ try {
553
+ const streamed = await pipeZipEntry(archivePath, entry, createWriteStream(temporary))
554
+ const expected = declared.get(entry.name)
555
+ if (expected !== undefined && expected.sha256 !== undefined && streamed.sha256 !== expected.sha256) {
556
+ throw new Error(`迁移包校验失败:${entry.name}(写入后 sha256 不符)`)
557
+ }
558
+ if (expected !== undefined && expected.bytes !== undefined && streamed.bytes !== expected.bytes) {
559
+ throw new Error(`迁移包校验失败:${entry.name}(写入后大小不符)`)
560
+ }
561
+ await rename(temporary, finalPath)
562
+ } catch (error) {
563
+ await rm(temporary, { force: true }).catch(() => {})
564
+ throw error
565
+ }
566
+ }
567
+ for (const entry of listing) {
568
+ const name = entry.name
428
569
  if (name === 'manifest.json') continue
429
570
  const target = destinationOf(name, { dataDir, dshHome, libraryRoots })
430
571
  if (target === null) {
@@ -438,14 +579,12 @@ export async function importBackup(options) {
438
579
  }
439
580
  if (exists !== null && strategy === 'merge') {
440
581
  const alternative = `${target}.imported-${stamp}`
441
- await mkdir(dirname(alternative), { recursive: true })
442
- await writeFile(alternative, bytes)
582
+ await place(entry, alternative)
443
583
  report.renamed.push(`${name} → ${alternative}`)
444
584
  continue
445
585
  }
446
586
  if (exists !== null && strategy === 'overwrite') await snapshot(target)
447
- await mkdir(dirname(target), { recursive: true })
448
- await writeFile(target, bytes)
587
+ await place(entry, target)
449
588
  report.imported.push(name)
450
589
  }
451
590
  const rewritten = await rewriteLibraryRoots({ dataDir, manifest, libraryRoots })