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,132 @@
1
+ /**
2
+ * On-demand install of the Typst binary (DEC-0013).
3
+ *
4
+ * The 52 MB executable does not ship in the package: the settings page offers a
5
+ * one-click download into `%LOCALAPPDATA%\dsh-pdf-workbench\typst\`. The archive
6
+ * is pinned to one release and verified by SHA-256 before anything is extracted,
7
+ * and the extracted image is relabelled Medium so a sandboxed workspace's Low
8
+ * integrity label cannot follow it (a Low process cannot write Medium folders).
9
+ *
10
+ * @module dsh-pdf-workbench/typst-install
11
+ */
12
+ import { createHash } from 'node:crypto'
13
+ import { spawnSync } from 'node:child_process'
14
+ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
15
+ import { homedir } from 'node:os'
16
+ import { dirname, join } from 'node:path'
17
+
18
+ export const TYPST_VERSION = '0.15.1'
19
+ export const TYPST_ARCHIVE = 'typst-x86_64-pc-windows-msvc.zip'
20
+ export const TYPST_URL = `https://github.com/typst/typst/releases/download/v${TYPST_VERSION}/${TYPST_ARCHIVE}`
21
+ export const TYPST_SHA256 = '19ce3551153c2fe7ee9fa2f95208310c8f4d3209fedb699e0333faf8913f6736'
22
+
23
+ /** The directory engine.js also searches: `<LOCALAPPDATA>\dsh-pdf-workbench\typst`. */
24
+ export function installDir() {
25
+ const base = String(process.env.LOCALAPPDATA ?? '').trim()
26
+ return base === '' ? join(homedir(), 'AppData', 'Local', 'dsh-pdf-workbench', 'typst') : join(base, 'dsh-pdf-workbench', 'typst')
27
+ }
28
+
29
+ function fail(code, message) {
30
+ const error = new Error(message)
31
+ error.code = code
32
+ return error
33
+ }
34
+
35
+ /** True when a usable typst.exe already sits in the install directory. */
36
+ export function installed() {
37
+ return existsSync(join(installDir(), 'typst.exe'))
38
+ }
39
+
40
+ /** Raise a Low integrity label to Medium; best effort on non-Windows hosts. */
41
+ function relabel(path) {
42
+ if (process.platform !== 'win32') return
43
+ spawnSync('icacls', [path, '/setintegritylevel', 'Medium'], { windowsHide: true, timeout: 20000 })
44
+ }
45
+
46
+ /** The release zip nests the binary in a folder named after the asset. */
47
+ function findBinary(dir, depth) {
48
+ if (depth > 3) return ''
49
+ let entries
50
+ try {
51
+ entries = readdirSync(dir, { withFileTypes: true })
52
+ } catch {
53
+ return ''
54
+ }
55
+ for (const entry of entries) {
56
+ if (entry.isFile() && entry.name.toLowerCase() === 'typst.exe') return join(dir, entry.name)
57
+ }
58
+ for (const entry of entries) {
59
+ if (!entry.isDirectory()) continue
60
+ const nested = findBinary(join(dir, entry.name), depth + 1)
61
+ if (nested !== '') return nested
62
+ }
63
+ return ''
64
+ }
65
+
66
+ /**
67
+ * Download, verify, extract and label Typst. Idempotent: an existing binary wins.
68
+ * @returns {Promise<{ version: string, path: string, reused: boolean }>} the install.
69
+ */
70
+ export async function installTypst() {
71
+ if (process.platform !== 'win32') throw fail('unsupported', '按需安装目前只支持 Windows:请手动安装 Typst 并放到 PATH。')
72
+ const dir = installDir()
73
+ const target = join(dir, 'typst.exe')
74
+ if (existsSync(target)) return { version: TYPST_VERSION, path: target, reused: true }
75
+ // A previous attempt may have extracted the archive but failed to move the
76
+ // binary out of the release folder; recover it instead of downloading again.
77
+ const leftover = findBinary(dir, 0)
78
+ if (leftover !== '') {
79
+ if (leftover !== target) {
80
+ renameSync(leftover, target)
81
+ rmSync(dirname(leftover), { recursive: true, force: true })
82
+ }
83
+ relabel(target)
84
+ return { version: TYPST_VERSION, path: target, reused: false }
85
+ }
86
+ mkdirSync(dir, { recursive: true })
87
+ const archive = join(dir, TYPST_ARCHIVE)
88
+ const partial = `${archive}.part`
89
+ try {
90
+ let bytes
91
+ try {
92
+ const response = await fetch(TYPST_URL, { redirect: 'follow' })
93
+ if (!response.ok) throw fail('download-failed', `下载失败:HTTP ${response.status}`)
94
+ bytes = Buffer.from(await response.arrayBuffer())
95
+ } catch (error) {
96
+ if (error !== null && error !== undefined && error.code === 'download-failed') throw error
97
+ throw fail('download-failed', `下载失败:${String(error && error.message ? error.message : error)}`)
98
+ }
99
+ const digest = createHash('sha256').update(bytes).digest('hex')
100
+ if (digest !== TYPST_SHA256) throw fail('checksum-failed', '下载内容校验失败,已放弃安装')
101
+ writeFileSync(partial, bytes)
102
+ renameSync(partial, archive)
103
+ spawnSync('powershell', ['-NoProfile', '-Command', `Expand-Archive -LiteralPath '${archive}' -DestinationPath '${dir}' -Force`], {
104
+ windowsHide: true, timeout: 120000,
105
+ })
106
+ if (!existsSync(target)) {
107
+ const found = findBinary(dir, 0)
108
+ if (found === '') throw fail('extract-failed', '压缩包解压后没有找到 typst.exe')
109
+ if (found !== target) {
110
+ renameSync(found, target)
111
+ rmSync(dirname(found), { recursive: true, force: true })
112
+ }
113
+ }
114
+ relabel(target)
115
+ const size = statSync(target).size
116
+ if (size < 1024 * 1024) throw fail('extract-failed', `typst.exe 体积异常(${size} 字节)`)
117
+ return { version: TYPST_VERSION, path: target, reused: false }
118
+ } finally {
119
+ rmSync(partial, { force: true })
120
+ rmSync(archive, { force: true })
121
+ }
122
+ }
123
+
124
+ /** The binary's reported version, or '' when it cannot run. */
125
+ export function probeVersion(binary) {
126
+ if (binary === '' || !existsSync(binary)) return ''
127
+ const result = spawnSync(binary, ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 20000 })
128
+ const text = `${result.stdout ?? ''}${result.stderr ?? ''}`
129
+ const match = text.match(/\d+\.\d+\.\d+/)
130
+ return match === null ? '' : match[0]
131
+ }
132
+
package/src/host/zip.js CHANGED
@@ -1,11 +1,21 @@
1
1
  /**
2
- * Minimal ZIP writer/reader used by the data-migration backup. No external
3
- * dependency: store and deflate entries are supported in both directions, which
4
- * also lets the Host read archives produced by Python's `zipfile`.
2
+ * Minimal ZIP writer/reader. No external dependency: store and deflate entries
3
+ * are supported in both directions, which also lets the Host read archives
4
+ * produced by Python's `zipfile`.
5
+ *
6
+ * `readZip` buffers a whole archive and `writeZip` buffers every entry;
7
+ * `listZipEntries` + `pipeZipEntry` read one entry at a time and `writeZipFile`
8
+ * writes one, so a multi-gigabyte pack is never held in memory just to hand a
9
+ * single PDF over.
5
10
  * @module dsh-pdf-workbench/zip
6
11
  */
7
12
 
8
- import { deflateRawSync, inflateRawSync } from 'node:zlib'
13
+ import { createHash } from 'node:crypto'
14
+ import { createReadStream, createWriteStream } from 'node:fs'
15
+ import { open, rm } from 'node:fs/promises'
16
+ import { Readable, Transform } from 'node:stream'
17
+ import { pipeline } from 'node:stream/promises'
18
+ import { createDeflateRaw, createInflateRaw, deflateRawSync, inflateRawSync } from 'node:zlib'
9
19
 
10
20
  /** Signature constants from the ZIP specification. */
11
21
  const LOCAL_SIG = 0x04034b50
@@ -184,3 +194,475 @@ export function readZip(buffer) {
184
194
  }
185
195
  return entries
186
196
  }
197
+
198
+ /**
199
+ * A readable failure from the streaming reader. `code` is stable, so callers can
200
+ * tell "the package is damaged" from "this package shape is unsupported".
201
+ */
202
+ export class ZipError extends Error {
203
+ /**
204
+ * @param {'bad-zip'|'zip64'|'encrypted'|'truncated'|'unsupported-method'|'size-mismatch'|'crc-mismatch'|'too-large'} code - stable machine code.
205
+ * @param {string} message - user-facing reason, already localized.
206
+ */
207
+ constructor(code, message) {
208
+ super(message)
209
+ this.name = 'ZipError'
210
+ this.code = code
211
+ }
212
+ }
213
+
214
+ /** EOCD record plus the longest possible archive comment. */
215
+ const END_WINDOW = 22 + 0xffff
216
+
217
+ /** ZIP64 sentinels: the real value would live in a zip64 record. */
218
+ const ZIP64_32 = 0xffffffff
219
+ const ZIP64_16 = 0xffff
220
+
221
+ /**
222
+ * Read exactly `length` bytes at `position`; a short read means a truncated file.
223
+ * @param {import('node:fs/promises').FileHandle} handle - open archive.
224
+ * @param {number} position - byte offset.
225
+ * @param {number} length - bytes wanted.
226
+ * @returns {Promise<Buffer>} the bytes actually present.
227
+ */
228
+ async function readAt(handle, position, length) {
229
+ const buffer = Buffer.alloc(length)
230
+ let done = 0
231
+ while (done < length) {
232
+ const { bytesRead } = await handle.read(buffer, done, length - done, position + done)
233
+ if (bytesRead === 0) break
234
+ done += bytesRead
235
+ }
236
+ return done === length ? buffer : buffer.subarray(0, done)
237
+ }
238
+
239
+ /**
240
+ * Update a running CRC32 with more bytes.
241
+ * @param {number} state - the register after the previous chunk.
242
+ * @param {Buffer} chunk - more bytes.
243
+ * @returns {number} the new register.
244
+ */
245
+ function crc32Update(state, chunk) {
246
+ let value = state
247
+ for (const byte of chunk) value = CRC_TABLE[(value ^ byte) & 0xff] ^ (value >>> 8)
248
+ return value
249
+ }
250
+
251
+ /** ZIP32 ceilings: one entry, the whole archive, and the entry count. */
252
+ const ZIP32_MAX_BYTES = 0xffffffff
253
+ const ZIP32_MAX_ENTRIES = 0xffff
254
+
255
+ /**
256
+ * Feed one chunk to a write stream and wait until the operating system has it.
257
+ * @param {import('node:fs').WriteStream} stream - open output.
258
+ * @param {Buffer} chunk - bytes to append.
259
+ * @returns {Promise<void>} completion.
260
+ */
261
+ function writeChunk(stream, chunk) {
262
+ if (chunk.length === 0) return Promise.resolve()
263
+ return new Promise((resolve, reject) => {
264
+ stream.write(chunk, error => (error ? reject(error) : resolve()))
265
+ })
266
+ }
267
+
268
+ /**
269
+ * Write a ZIP archive in one streaming pass: only the current chunk is held in
270
+ * memory, so a pack bigger than RAM still works.
271
+ *
272
+ * Entries are appended in order (local file header → data → …), then the
273
+ * central directory and the EOCD record. A local header needs its entry's CRC
274
+ * and sizes, which are only known after the bytes went by, so those three
275
+ * fields are filled in with a positional write once the data is on disk. The
276
+ * result is an ordinary ZIP32 archive — no data descriptor — that `readZip`,
277
+ * `listZipEntries` and Python's `zipfile` read like one from `writeZip`.
278
+ *
279
+ * @param {string} outPath - file to create (its directory must already exist).
280
+ * @param {{ entries: { name: string, data?: Buffer, path?: string }[], compress?: boolean }} options - entries given by bytes or by file path; `compress` raw-deflates each one.
281
+ * @returns {Promise<{ bytes: number, files: number }>} archive size and entry count.
282
+ * @throws {ZipError} `bad-name` for an unsafe entry name, `bad-entry` for an entry with neither `data` nor `path`, `zip64` beyond the ZIP32 limits; file-system errors pass through.
283
+ */
284
+ export async function writeZipFile(outPath, options) {
285
+ const entries = Array.isArray(options?.entries) ? options.entries : []
286
+ const compress = options?.compress === true
287
+ // 0xffff entries and 0xffffffff sizes/offsets are the ZIP64 sentinels: a
288
+ // package carrying them would be refused by `listZipEntries`, so refuse to
289
+ // write them in the first place.
290
+ if (entries.length >= ZIP32_MAX_ENTRIES) {
291
+ throw new ZipError('zip64', `条目数超过 ${ZIP32_MAX_ENTRIES - 1},暂不支持 ZIP64 压缩包`)
292
+ }
293
+ const { time, date } = dosDateTime()
294
+ const out = createWriteStream(outPath)
295
+ let failure = null
296
+ out.on('error', error => { failure = error })
297
+ /** Append bytes; rejects as soon as the file stream fails. */
298
+ const write = async chunk => {
299
+ if (failure !== null) throw failure
300
+ await writeChunk(out, chunk)
301
+ if (failure !== null) throw failure
302
+ }
303
+ let position = 0
304
+ const patches = []
305
+ const centralRecords = []
306
+ try {
307
+ for (const entry of entries) {
308
+ let name
309
+ try {
310
+ name = safeZipName(entry?.name)
311
+ } catch (error) {
312
+ throw new ZipError('bad-name', String(error && error.message ? error.message : error))
313
+ }
314
+ const nameBytes = Buffer.from(name, 'utf8')
315
+ const method = compress ? 8 : 0
316
+ const headerOffset = position
317
+ const local = Buffer.alloc(30)
318
+ local.writeUInt32LE(LOCAL_SIG, 0)
319
+ local.writeUInt16LE(20, 4)
320
+ local.writeUInt16LE(0x0800, 6)
321
+ local.writeUInt16LE(method, 8)
322
+ local.writeUInt16LE(time, 10)
323
+ local.writeUInt16LE(date, 12)
324
+ local.writeUInt16LE(nameBytes.length, 26)
325
+ local.writeUInt16LE(0, 28)
326
+ await write(local)
327
+ await write(nameBytes)
328
+ position += local.length + nameBytes.length
329
+
330
+ let rawSize = 0
331
+ let crcState = 0xffffffff
332
+ const meter = new Transform({
333
+ transform(chunk, _encoding, callback) {
334
+ rawSize += chunk.length
335
+ crcState = crc32Update(crcState, chunk)
336
+ callback(null, chunk)
337
+ },
338
+ })
339
+ let source
340
+ if (Buffer.isBuffer(entry?.data)) source = Readable.from([entry.data])
341
+ else if (typeof entry?.path === 'string' && entry.path !== '') source = createReadStream(entry.path)
342
+ else throw new ZipError('bad-entry', `ZIP 条目既没有 data 也没有 path:${name}`)
343
+ const stages = [source, meter]
344
+ if (compress) stages.push(createDeflateRaw())
345
+ for (let index = 0; index < stages.length - 1; index += 1) {
346
+ const next = stages[index + 1]
347
+ stages[index].on('error', error => next.destroy(error))
348
+ }
349
+ const tail = stages.slice(1).reduce((upstream, next) => upstream.pipe(next), source)
350
+ let storedSize = 0
351
+ try {
352
+ for await (const chunk of tail) {
353
+ storedSize += chunk.length
354
+ await write(chunk)
355
+ }
356
+ } catch (error) {
357
+ for (const stage of stages) stage.destroy()
358
+ throw error
359
+ }
360
+ const checksum = (crcState ^ 0xffffffff) >>> 0
361
+ if (rawSize >= ZIP32_MAX_BYTES || storedSize >= ZIP32_MAX_BYTES) {
362
+ throw new ZipError('zip64', `文件接近 4 GB,暂不支持 ZIP64 压缩包:${name}`)
363
+ }
364
+ patches.push({ offset: headerOffset + 14, checksum, storedSize, rawSize })
365
+ position += storedSize
366
+
367
+ const central = Buffer.alloc(46)
368
+ central.writeUInt32LE(CENTRAL_SIG, 0)
369
+ central.writeUInt16LE(20, 4)
370
+ central.writeUInt16LE(20, 6)
371
+ central.writeUInt16LE(0x0800, 8)
372
+ central.writeUInt16LE(method, 10)
373
+ central.writeUInt16LE(time, 12)
374
+ central.writeUInt16LE(date, 14)
375
+ central.writeUInt32LE(checksum, 16)
376
+ central.writeUInt32LE(storedSize, 20)
377
+ central.writeUInt32LE(rawSize, 24)
378
+ central.writeUInt16LE(nameBytes.length, 28)
379
+ central.writeUInt16LE(0, 30)
380
+ central.writeUInt16LE(0, 32)
381
+ central.writeUInt16LE(0, 34)
382
+ central.writeUInt16LE(0, 36)
383
+ central.writeUInt32LE(0, 38)
384
+ central.writeUInt32LE(headerOffset, 42)
385
+ centralRecords.push(central, nameBytes)
386
+ }
387
+ if (position >= ZIP32_MAX_BYTES) throw new ZipError('zip64', '压缩包超过 4 GB,暂不支持 ZIP64 压缩包')
388
+ const centralStart = position
389
+ const centralBytes = Buffer.concat(centralRecords)
390
+ await write(centralBytes)
391
+ position += centralBytes.length
392
+ if (centralBytes.length >= ZIP32_MAX_BYTES || centralStart >= ZIP32_MAX_BYTES) {
393
+ throw new ZipError('zip64', '压缩包超过 4 GB,暂不支持 ZIP64 压缩包')
394
+ }
395
+ const end = Buffer.alloc(22)
396
+ end.writeUInt32LE(END_SIG, 0)
397
+ end.writeUInt16LE(0, 4)
398
+ end.writeUInt16LE(0, 6)
399
+ end.writeUInt16LE(entries.length, 8)
400
+ end.writeUInt16LE(entries.length, 10)
401
+ end.writeUInt32LE(centralBytes.length, 12)
402
+ end.writeUInt32LE(centralStart, 16)
403
+ end.writeUInt16LE(0, 20)
404
+ await write(end)
405
+ position += end.length
406
+ await new Promise((resolve, reject) => {
407
+ out.once('error', reject)
408
+ out.end(resolve)
409
+ })
410
+ // The data is flushed and the writer closed its descriptor, so the three
411
+ // deferred local-header fields can be written where they belong.
412
+ if (patches.length > 0) {
413
+ const handle = await open(outPath, 'r+')
414
+ try {
415
+ for (const patch of patches) {
416
+ const fields = Buffer.alloc(12)
417
+ fields.writeUInt32LE(patch.checksum, 0)
418
+ fields.writeUInt32LE(patch.storedSize, 4)
419
+ fields.writeUInt32LE(patch.rawSize, 8)
420
+ await handle.write(fields, 0, fields.length, patch.offset)
421
+ }
422
+ } finally {
423
+ await handle.close()
424
+ }
425
+ }
426
+ return { bytes: position, files: entries.length }
427
+ } catch (error) {
428
+ out.destroy()
429
+ await rm(outPath, { force: true }).catch(() => {})
430
+ throw error
431
+ }
432
+ }
433
+
434
+ /**
435
+ * List the entries of a ZIP archive without reading their data.
436
+ *
437
+ * Reads the tail for the end-of-central-directory record, then the central
438
+ * directory, then each local file header to work out where the entry's data
439
+ * starts. Names are normalized exactly like `readZip` does (forward slashes, no
440
+ * `..`), and duplicate names keep the last occurrence, matching `readZip`'s Map.
441
+ *
442
+ * @param {string} archivePath - archive on disk.
443
+ * @returns {Promise<Array<{ name: string, method: number, compressedSize: number, size: number, crc32: number, dataStart: number }>>} the entries, in directory order.
444
+ * @throws {ZipError} when the archive is invalid, truncated, zip64 or encrypted.
445
+ */
446
+ export async function listZipEntries(archivePath) {
447
+ const handle = await open(archivePath, 'r')
448
+ try {
449
+ const info = await handle.stat()
450
+ if (!info.isFile()) throw new ZipError('bad-zip', '不是有效的 ZIP:不是普通文件')
451
+ if (info.size < 22) throw new ZipError('bad-zip', '不是有效的 ZIP:文件太小')
452
+ const tailLength = Math.min(info.size, END_WINDOW)
453
+ const tail = await readAt(handle, info.size - tailLength, tailLength)
454
+ if (tail.length < 22) throw new ZipError('bad-zip', '不是有效的 ZIP:文件太小')
455
+ let end = -1
456
+ for (let offset = tail.length - 22; offset >= 0; offset -= 1) {
457
+ if (tail.readUInt32LE(offset) !== END_SIG) continue
458
+ // A comment that does not fit the tail is a stray signature, not the EOCD.
459
+ if (offset + 22 + tail.readUInt16LE(offset + 20) > tail.length) continue
460
+ end = offset
461
+ break
462
+ }
463
+ if (end < 0) throw new ZipError('bad-zip', '不是有效的 ZIP:找不到目录结尾')
464
+ const diskNumber = tail.readUInt16LE(end + 4)
465
+ const centralDisk = tail.readUInt16LE(end + 6)
466
+ const countOnDisk = tail.readUInt16LE(end + 8)
467
+ const count = tail.readUInt16LE(end + 10)
468
+ const centralSize = tail.readUInt32LE(end + 12)
469
+ const centralOffset = tail.readUInt32LE(end + 16)
470
+ if (count === ZIP64_16 || countOnDisk === ZIP64_16 || centralSize === ZIP64_32 || centralOffset === ZIP64_32) {
471
+ throw new ZipError('zip64', '暂不支持 ZIP64 压缩包(条目数或单文件超过 4 GB)')
472
+ }
473
+ if (diskNumber !== 0 || centralDisk !== 0 || countOnDisk !== count) {
474
+ throw new ZipError('bad-zip', '不是有效的 ZIP:不支持分卷压缩包')
475
+ }
476
+ if (count === 0) return []
477
+ if (centralOffset + centralSize > info.size) throw new ZipError('truncated', '不是有效的 ZIP:中央目录被截断')
478
+ const central = await readAt(handle, centralOffset, centralSize)
479
+ if (central.length !== centralSize) throw new ZipError('truncated', '不是有效的 ZIP:中央目录被截断')
480
+ const entries = new Map()
481
+ let cursor = 0
482
+ for (let index = 0; index < count; index += 1) {
483
+ if (cursor + 46 > central.length) throw new ZipError('truncated', '不是有效的 ZIP:目录被截断')
484
+ if (central.readUInt32LE(cursor) !== CENTRAL_SIG) throw new ZipError('bad-zip', 'ZIP 目录损坏')
485
+ const flags = central.readUInt16LE(cursor + 8)
486
+ const method = central.readUInt16LE(cursor + 10)
487
+ const checksum = central.readUInt32LE(cursor + 16)
488
+ const compressedSize = central.readUInt32LE(cursor + 20)
489
+ const size = central.readUInt32LE(cursor + 24)
490
+ const nameLength = central.readUInt16LE(cursor + 28)
491
+ const extraLength = central.readUInt16LE(cursor + 30)
492
+ const commentLength = central.readUInt16LE(cursor + 32)
493
+ const localOffset = central.readUInt32LE(cursor + 42)
494
+ if (cursor + 46 + nameLength + extraLength + commentLength > central.length) {
495
+ throw new ZipError('truncated', '不是有效的 ZIP:目录被截断')
496
+ }
497
+ const rawName = central.subarray(cursor + 46, cursor + 46 + nameLength).toString('utf8')
498
+ let name
499
+ try {
500
+ name = safeZipName(rawName)
501
+ } catch (error) {
502
+ throw new ZipError('bad-zip', String(error && error.message ? error.message : error))
503
+ }
504
+ if (compressedSize === ZIP64_32 || size === ZIP64_32 || localOffset === ZIP64_32) {
505
+ throw new ZipError('zip64', `暂不支持 ZIP64 压缩包:${name}`)
506
+ }
507
+ if ((flags & 0x1) !== 0 || method === 99) throw new ZipError('encrypted', `加密 ZIP 暂不支持:${name}`)
508
+ if (method !== 0 && method !== 8) throw new ZipError('unsupported-method', `不支持的 ZIP 压缩方式 ${method}:${name}`)
509
+ if (localOffset + 30 > info.size) throw new ZipError('truncated', `不是有效的 ZIP:条目偏移越界:${name}`)
510
+ const local = await readAt(handle, localOffset, 30)
511
+ if (local.length !== 30) throw new ZipError('truncated', `不是有效的 ZIP:条目头被截断:${name}`)
512
+ if (local.readUInt32LE(0) !== LOCAL_SIG) throw new ZipError('bad-zip', `ZIP 条目损坏:${name}`)
513
+ const dataStart = localOffset + 30 + local.readUInt16LE(26) + local.readUInt16LE(28)
514
+ if (dataStart > info.size || dataStart + compressedSize > info.size) {
515
+ throw new ZipError('truncated', `ZIP 条目被截断:${name}`)
516
+ }
517
+ entries.set(name, { name, method, compressedSize, size, crc32: checksum, dataStart })
518
+ cursor += 46 + nameLength + extraLength + commentLength
519
+ }
520
+ return [...entries.values()]
521
+ } finally {
522
+ await handle.close()
523
+ }
524
+ }
525
+
526
+ /**
527
+ * Stream one entry's decompressed bytes into `writable`, hashing them on the way.
528
+ *
529
+ * `method 0` is copied straight from its data range; `method 8` is inflated
530
+ * through `createInflateRaw`. Nothing larger than a stream chunk is buffered.
531
+ * The byte count and CRC32 are checked against the directory afterwards, so a
532
+ * damaged package is refused instead of imported.
533
+ *
534
+ * @param {string} archivePath - archive on disk.
535
+ * @param {{ name: string, method: number, compressedSize: number, size: number, crc32: number, dataStart: number }} entry - one `listZipEntries` entry.
536
+ * @param {import('node:stream').Writable} writable - destination; the pipeline ends it.
537
+ * @returns {Promise<{ bytes: number, crc32: number, sha256: string }>} what was written.
538
+ * @throws {ZipError} on an unsupported method, damaged data or a size/CRC mismatch.
539
+ */
540
+ export async function pipeZipEntry(archivePath, entry, writable) {
541
+ if (entry === null || typeof entry !== 'object') throw new ZipError('bad-zip', 'ZIP 条目为空')
542
+ const name = String(entry.name ?? '')
543
+ const method = entry.method
544
+ if (method !== 0 && method !== 8) throw new ZipError('unsupported-method', `不支持的 ZIP 压缩方式 ${method}:${name}`)
545
+ const dataStart = Number(entry.dataStart)
546
+ const compressedSize = Number(entry.compressedSize)
547
+ if (!Number.isSafeInteger(dataStart) || dataStart < 0 || !Number.isSafeInteger(compressedSize) || compressedSize < 0) {
548
+ throw new ZipError('bad-zip', `ZIP 条目偏移无效:${name}`)
549
+ }
550
+ const source = compressedSize === 0
551
+ ? Readable.from([])
552
+ : createReadStream(archivePath, { start: dataStart, end: dataStart + compressedSize - 1 })
553
+ const hash = createHash('sha256')
554
+ let bytes = 0
555
+ let state = 0xffffffff
556
+ const meter = new Transform({
557
+ transform(chunk, _encoding, callback) {
558
+ bytes += chunk.length
559
+ state = crc32Update(state, chunk)
560
+ hash.update(chunk)
561
+ callback(null, chunk)
562
+ },
563
+ })
564
+ const stages = [source]
565
+ if (method === 8) stages.push(createInflateRaw())
566
+ stages.push(meter, writable)
567
+ try {
568
+ await pipeline(...stages)
569
+ } catch (error) {
570
+ if (error instanceof ZipError) throw error
571
+ // File-system errors (EACCES, ENOSPC…) are the Host's problem, not the
572
+ // package's; only compressed-data errors get the ZIP label.
573
+ if (typeof error?.code === 'string' && /^E[A-Z]+$/.test(error.code)) throw error
574
+ throw new ZipError('bad-zip', `ZIP 条目读取失败:${name}(${String(error && error.message ? error.message : error)})`)
575
+ }
576
+ const actual = (state ^ 0xffffffff) >>> 0
577
+ const declaredSize = Number(entry.size)
578
+ if (bytes !== declaredSize) {
579
+ throw new ZipError('size-mismatch', `ZIP 条目大小不符:${name}(目录声明 ${declaredSize} 字节,实际 ${bytes} 字节)`)
580
+ }
581
+ if (actual !== Number(entry.crc32) >>> 0) {
582
+ throw new ZipError('crc-mismatch', `ZIP 条目校验失败(CRC32 不符):${name}`)
583
+ }
584
+ return { bytes, crc32: actual, sha256: hash.digest('hex') }
585
+ }
586
+
587
+ /**
588
+ * Read the first bytes of one entry's decompressed content.
589
+ *
590
+ * Used to check a `%PDF-` header without inflating a whole book. A stored entry
591
+ * is a direct read; a deflated one stops inflating as soon as enough output
592
+ * exists.
593
+ *
594
+ * @param {string} archivePath - archive on disk.
595
+ * @param {{ name: string, method: number, compressedSize: number, size: number, dataStart: number }} entry - one `listZipEntries` entry.
596
+ * @param {number} length - how many bytes to peek at.
597
+ * @returns {Promise<Buffer>} up to `length` bytes (fewer only at the entry's end).
598
+ * @throws {ZipError} when the data cannot be read.
599
+ */
600
+ export async function readZipEntryHead(archivePath, entry, length) {
601
+ const wanted = Math.max(0, Math.floor(Number(length) || 0))
602
+ if (entry === null || typeof entry !== 'object') throw new ZipError('bad-zip', 'ZIP 条目为空')
603
+ if (wanted === 0) return Buffer.alloc(0)
604
+ const name = String(entry.name ?? '')
605
+ const compressedSize = Number(entry.compressedSize)
606
+ if (entry.method === 0) {
607
+ const count = Math.min(wanted, compressedSize)
608
+ if (count <= 0) return Buffer.alloc(0)
609
+ const handle = await open(archivePath, 'r')
610
+ try {
611
+ const head = await readAt(handle, Number(entry.dataStart), count)
612
+ return head.subarray(0, Math.min(head.length, Number(entry.size)))
613
+ } finally {
614
+ await handle.close()
615
+ }
616
+ }
617
+ if (entry.method !== 8) throw new ZipError('unsupported-method', `不支持的 ZIP 压缩方式 ${entry.method}:${name}`)
618
+ if (compressedSize <= 0) return Buffer.alloc(0)
619
+ const dataStart = Number(entry.dataStart)
620
+ const source = createReadStream(archivePath, { start: dataStart, end: dataStart + compressedSize - 1 })
621
+ const inflate = source.pipe(createInflateRaw())
622
+ const chunks = []
623
+ let total = 0
624
+ try {
625
+ for await (const chunk of inflate) {
626
+ chunks.push(chunk)
627
+ total += chunk.length
628
+ if (total >= wanted) break
629
+ }
630
+ } catch (error) {
631
+ throw new ZipError('bad-zip', `ZIP 条目读取失败:${name}(${String(error && error.message ? error.message : error)})`)
632
+ } finally {
633
+ inflate.destroy()
634
+ source.destroy()
635
+ }
636
+ return Buffer.concat(chunks, total).subarray(0, Math.min(wanted, total))
637
+ }
638
+
639
+ /**
640
+ * Read one small entry into memory, refusing anything above `maxBytes`.
641
+ * @param {string} archivePath - archive on disk.
642
+ * @param {{ name: string, method: number, compressedSize: number, size: number, crc32: number, dataStart: number }} entry - one `listZipEntries` entry.
643
+ * @param {number} maxBytes - ceiling for this entry.
644
+ * @returns {Promise<Buffer>} the entry's bytes.
645
+ * @throws {ZipError} when the entry is larger than `maxBytes` or its data is damaged.
646
+ */
647
+ export async function readZipEntryBuffer(archivePath, entry, maxBytes) {
648
+ const limit = Number(maxBytes)
649
+ if (!Number.isFinite(limit) || limit < 0) throw new ZipError('too-large', '没有为这条 ZIP 条目设置读取上限')
650
+ if (Number(entry?.size) > limit) {
651
+ throw new ZipError('too-large', `ZIP 条目光过大小:${String(entry?.name ?? '')}(${Number(entry?.size)} 字节 > ${limit} 字节)`)
652
+ }
653
+ const chunks = []
654
+ let total = 0
655
+ const sink = new Transform({
656
+ transform(chunk, _encoding, callback) {
657
+ total += chunk.length
658
+ if (total > limit) {
659
+ callback(new ZipError('too-large', `ZIP 条目光过大小:${String(entry?.name ?? '')}(超过 ${limit} 字节)`))
660
+ return
661
+ }
662
+ chunks.push(chunk)
663
+ callback()
664
+ },
665
+ })
666
+ await pipeZipEntry(archivePath, entry, sink)
667
+ return Buffer.concat(chunks, total)
668
+ }