dsh-pdf-workbench 1.3.4 → 1.4.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.
package/src/host/state.js CHANGED
@@ -23,7 +23,7 @@ const MAX_BOOKS = 400
23
23
  /** A safe chapter code: `c` plus digits, or a plain short token. */
24
24
  const SAFE_CODE = /^[\w-]{1,16}$/
25
25
 
26
- /** Reading modes the reader offers. */
26
+ /** Reading modes the reader offers. `canvas` (one release) reads back as `single`. */
27
27
  const MODES = new Set(['single', 'continuous'])
28
28
 
29
29
  /**
@@ -0,0 +1,186 @@
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`.
5
+ * @module dsh-pdf-workbench/zip
6
+ */
7
+
8
+ import { deflateRawSync, inflateRawSync } from 'node:zlib'
9
+
10
+ /** Signature constants from the ZIP specification. */
11
+ const LOCAL_SIG = 0x04034b50
12
+ const CENTRAL_SIG = 0x02014b50
13
+ const END_SIG = 0x06054b50
14
+
15
+ /**
16
+ * Normalize one archive path: forward slashes, no leading slash, no `..`.
17
+ * @param {string} value - proposed entry name.
18
+ * @returns {string} safe name.
19
+ */
20
+ export function safeZipName(value) {
21
+ const name = String(value ?? '').replace(/\\/g, '/')
22
+ if (name === '' || name.startsWith('/') || /^[A-Za-z]:/.test(name)) throw new Error(`不安全的压缩包路径:${name}`)
23
+ const parts = name.split('/').filter(part => part !== '' && part !== '.')
24
+ if (parts.some(part => part === '..')) throw new Error(`不安全的压缩包路径:${name}`)
25
+ return parts.join('/')
26
+ }
27
+
28
+ /** CRC32 table, built once. */
29
+ const CRC_TABLE = (() => {
30
+ const table = new Uint32Array(256)
31
+ for (let index = 0; index < 256; index += 1) {
32
+ let value = index
33
+ for (let bit = 0; bit < 8; bit += 1) value = value & 1 ? (value >>> 1) ^ 0xedb88320 : value >>> 1
34
+ table[index] = value >>> 0
35
+ }
36
+ return table
37
+ })()
38
+
39
+ /**
40
+ * @param {Buffer} buffer - bytes.
41
+ * @returns {number} CRC32.
42
+ */
43
+ export function crc32(buffer) {
44
+ let value = 0xffffffff
45
+ for (const byte of buffer) value = CRC_TABLE[(value ^ byte) & 0xff] ^ (value >>> 8)
46
+ return (value ^ 0xffffffff) >>> 0
47
+ }
48
+
49
+ /**
50
+ * DOS date/time words for the current local clock.
51
+ * @param {Date} [date] - timestamp.
52
+ * @returns {{ time: number, date: number }} the two words.
53
+ */
54
+ function dosDateTime(date = new Date()) {
55
+ const time = (date.getHours() << 11) | (date.getMinutes() << 5) | Math.floor(date.getSeconds() / 2)
56
+ const day = ((date.getFullYear() - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate()
57
+ return { time, date: day }
58
+ }
59
+
60
+ /**
61
+ * Write a ZIP archive. Entries are stored by default; `compress` switches to
62
+ * raw deflate per entry.
63
+ * @param {{ entries: { name: string, data: Buffer }[], compress?: boolean }} options - files to archive.
64
+ * @returns {Buffer} the ZIP bytes.
65
+ */
66
+ export function writeZip(options) {
67
+ const entries = Array.isArray(options.entries) ? options.entries : []
68
+ const compress = options.compress === true
69
+ const { time, date } = dosDateTime()
70
+ const locals = []
71
+ const centrals = []
72
+ let offset = 0
73
+ for (const entry of entries) {
74
+ const name = safeZipName(entry.name)
75
+ const nameBytes = Buffer.from(name, 'utf8')
76
+ const raw = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data)
77
+ const data = compress ? deflateRawSync(raw) : raw
78
+ const method = compress ? 8 : 0
79
+ const checksum = crc32(raw)
80
+
81
+ const local = Buffer.alloc(30)
82
+ local.writeUInt32LE(LOCAL_SIG, 0)
83
+ local.writeUInt16LE(20, 4)
84
+ local.writeUInt16LE(0x0800, 6)
85
+ local.writeUInt16LE(method, 8)
86
+ local.writeUInt16LE(time, 10)
87
+ local.writeUInt16LE(date, 12)
88
+ local.writeUInt32LE(checksum, 14)
89
+ local.writeUInt32LE(data.length, 18)
90
+ local.writeUInt32LE(raw.length, 22)
91
+ local.writeUInt16LE(nameBytes.length, 26)
92
+ local.writeUInt16LE(0, 28)
93
+ locals.push(local, nameBytes, data)
94
+
95
+ const central = Buffer.alloc(46)
96
+ central.writeUInt32LE(CENTRAL_SIG, 0)
97
+ central.writeUInt16LE(20, 4)
98
+ central.writeUInt16LE(20, 6)
99
+ central.writeUInt16LE(0x0800, 8)
100
+ central.writeUInt16LE(method, 10)
101
+ central.writeUInt16LE(time, 12)
102
+ central.writeUInt16LE(date, 14)
103
+ central.writeUInt32LE(checksum, 16)
104
+ central.writeUInt32LE(data.length, 20)
105
+ central.writeUInt32LE(raw.length, 24)
106
+ central.writeUInt16LE(nameBytes.length, 28)
107
+ central.writeUInt16LE(0, 30)
108
+ central.writeUInt16LE(0, 32)
109
+ central.writeUInt16LE(0, 34)
110
+ central.writeUInt16LE(0, 36)
111
+ central.writeUInt32LE(0, 38)
112
+ central.writeUInt32LE(offset, 42)
113
+ centrals.push(central, nameBytes)
114
+
115
+ offset += local.length + nameBytes.length + data.length
116
+ }
117
+ const centralStart = offset
118
+ const centralBytes = Buffer.concat(centrals)
119
+ const end = Buffer.alloc(22)
120
+ end.writeUInt32LE(END_SIG, 0)
121
+ end.writeUInt16LE(0, 4)
122
+ end.writeUInt16LE(0, 6)
123
+ end.writeUInt16LE(entries.length, 8)
124
+ end.writeUInt16LE(entries.length, 10)
125
+ end.writeUInt32LE(centralBytes.length, 12)
126
+ end.writeUInt32LE(centralStart, 16)
127
+ end.writeUInt16LE(0, 20)
128
+ return Buffer.concat([...locals, centralBytes, end])
129
+ }
130
+
131
+ /**
132
+ * Find the end-of-central-directory record.
133
+ * @param {Buffer} buffer - archive bytes.
134
+ * @returns {number} the record offset.
135
+ */
136
+ function findEnd(buffer) {
137
+ const earliest = Math.max(0, buffer.length - 22 - 0xffff)
138
+ for (let offset = buffer.length - 22; offset >= earliest; offset -= 1) {
139
+ if (buffer.readUInt32LE(offset) === END_SIG) return offset
140
+ }
141
+ throw new Error('不是有效的 ZIP:找不到目录结尾')
142
+ }
143
+
144
+ /**
145
+ * Read a ZIP archive (store and deflate).
146
+ * @param {Buffer} buffer - archive bytes.
147
+ * @returns {Map<string, Buffer>} entries by name.
148
+ */
149
+ export function readZip(buffer) {
150
+ if (!Buffer.isBuffer(buffer) || buffer.length < 22) throw new Error('不是有效的 ZIP')
151
+ const end = findEnd(buffer)
152
+ const count = buffer.readUInt16LE(end + 10)
153
+ const centralOffset = buffer.readUInt32LE(end + 16)
154
+ if (count === 0) return new Map()
155
+ if (centralOffset + 46 > buffer.length) throw new Error('不是有效的 ZIP:目录偏移越界')
156
+ const entries = new Map()
157
+ let offset = centralOffset
158
+ for (let index = 0; index < count; index += 1) {
159
+ if (offset + 46 > buffer.length) throw new Error('不是有效的 ZIP:目录被截断')
160
+ if (buffer.readUInt32LE(offset) !== CENTRAL_SIG) throw new Error('ZIP 目录损坏')
161
+ const method = buffer.readUInt16LE(offset + 10)
162
+ const compressedSize = buffer.readUInt32LE(offset + 20)
163
+ const uncompressedSize = buffer.readUInt32LE(offset + 24)
164
+ const nameLength = buffer.readUInt16LE(offset + 28)
165
+ const extraLength = buffer.readUInt16LE(offset + 30)
166
+ const commentLength = buffer.readUInt16LE(offset + 32)
167
+ const localOffset = buffer.readUInt32LE(offset + 42)
168
+ if (localOffset + 30 > buffer.length) throw new Error('不是有效的 ZIP:条目偏移越界')
169
+ const name = safeZipName(buffer.subarray(offset + 46, offset + 46 + nameLength).toString('utf8'))
170
+ if (buffer.readUInt32LE(localOffset) !== LOCAL_SIG) throw new Error(`ZIP 条目损坏:${name}`)
171
+ const localNameLength = buffer.readUInt16LE(localOffset + 26)
172
+ const localExtraLength = buffer.readUInt16LE(localOffset + 28)
173
+ const dataStart = localOffset + 30 + localNameLength + localExtraLength
174
+ if (dataStart > buffer.length || dataStart + compressedSize > buffer.length) throw new Error('不是有效的 ZIP:条目数据越界')
175
+ const raw = buffer.subarray(dataStart, dataStart + compressedSize)
176
+ if (raw.length !== compressedSize) throw new Error(`ZIP 条目被截断:${name}`)
177
+ let data
178
+ if (method === 0) data = Buffer.from(raw)
179
+ else if (method === 8) data = inflateRawSync(raw)
180
+ else throw new Error(`不支持的 ZIP 压缩方式 ${method}:${name}`)
181
+ if (data.length !== uncompressedSize) throw new Error(`ZIP 条目大小不符:${name}`)
182
+ entries.set(name, data)
183
+ offset += 46 + nameLength + extraLength + commentLength
184
+ }
185
+ return entries
186
+ }
@@ -0,0 +1,34 @@
1
+ """Whole PDF text as one markdown file (PyMuPDF).
2
+
3
+ Usage:
4
+ python pdf_text.py <input.pdf>
5
+
6
+ Prints JSON:
7
+ {"pages": [{"page": 1, "text": "..."}, ...], "chars": 12345, "pageCount": 42}
8
+
9
+ The Host keeps the result in `.pdfdesk/cache/<book>/<chapter>/text.md` so the
10
+ hidden base session can read a chapter once instead of re-reading the PDF for
11
+ every mode.
12
+ """
13
+ import json
14
+ import sys
15
+
16
+ import fitz
17
+
18
+
19
+ def whole_text(pdf_path):
20
+ document = fitz.open(pdf_path)
21
+ pages = []
22
+ chars = 0
23
+ for index, page in enumerate(document, start=1):
24
+ text = page.get_text("text").strip()
25
+ chars += len(text)
26
+ pages.append({"page": index, "text": text})
27
+ return {"pages": pages, "chars": chars, "pageCount": len(pages)}
28
+
29
+
30
+ if __name__ == "__main__":
31
+ if len(sys.argv) < 2:
32
+ print("usage: pdf_text.py <input.pdf>", file=sys.stderr)
33
+ sys.exit(2)
34
+ print(json.dumps(whole_text(sys.argv[1]), ensure_ascii=False))