dsh-half-page 0.3.35 → 0.3.36

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 (3) hide show
  1. package/README.md +16 -0
  2. package/index.js +164 -15
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -40,6 +40,7 @@ dsh plugin add dsh-half-page
40
40
  ~/.dsh/reading/
41
41
  ├── books/ 书(.txt / .md)
42
42
  │ └── .trash/ 下架的书挪到这儿,可手工找回
43
+ ├── books/<id>.toc.json 章表:每章的字符偏移 + 字节偏移
43
44
  ├── 读后感.md 所有读后感,按 ## 书名 / ### 章名 分块
44
45
  ├── 作品/ 它自己写的东西
45
46
  └── state.json 读到哪了
@@ -57,6 +58,21 @@ dsh plugin add dsh-half-page
57
58
  | `reading_search` | 在书里搜词,返回第几章、哪一行 |
58
59
  | `reading_recap` | 已读部分压成一页 |
59
60
 
61
+ ## 章表(读一章不整本 decode)
62
+
63
+ 第一次打开某本书时扫一遍,把每章的位置换算成字节偏移,落成 `books/<id>.toc.json`:
64
+
65
+ ```json
66
+ { "version": 1, "encoding": "gb18030", "bytes": 9638898, "chars": 3123456,
67
+ "chapters": [{ "title": "第一章 小二上酒", "charStart": 0, "charEnd": 3201, "byteStart": 0, "byteEnd": 6430 }] }
68
+ ```
69
+
70
+ 以后 `reading_next` 只 `fs.open` + 读 `byteStart..byteEnd` 那一段,再单独解这一段的编码——14MB 的书读一章不再把整本读进内存。
71
+
72
+ - 章表过期(文件 mtime 或字节数变了)会自动重建;删掉也能自动重建。
73
+ - `reading_next` 的返回里带 `tocPath`,能看到表在哪。
74
+ - `reading_search` 还是要整本,它是搜全文的。
75
+
60
76
  ## License
61
77
 
62
78
  MIT
package/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // dsh-half-page · 半页(自己的读书与写字)
2
2
  // 宿主侧:书库、切章、读后感、进度;客户端面板读 HTTP 路由。
3
- import { readFile, writeFile, mkdir, readdir, stat, rename } from 'node:fs/promises'
3
+ import { readFile, writeFile, mkdir, readdir, stat, rename, open } from 'node:fs/promises'
4
4
  import { readFileSync } from 'node:fs'
5
5
  import { join, basename, dirname, extname, resolve } from 'node:path'
6
6
  import { homedir } from 'node:os'
@@ -104,6 +104,159 @@ export function chapterText(text, chapters, n) {
104
104
  return text.slice(c.start, c.end).trim()
105
105
  }
106
106
 
107
+ /* ------------------------------------------------------------------ 章表
108
+ * 读一章不再整本 decode:第一次打开某本书时扫一遍,把每章的字符偏移换算成
109
+ * 字节偏移,落盘成 books/<id>.toc.json;以后按 byteStart..byteEnd 只读这一段。
110
+ */
111
+
112
+ const TOC_VERSION = 1
113
+
114
+ export function tocPath(dir, id) {
115
+ return join(dir, 'books', id + '.toc.json')
116
+ }
117
+
118
+ async function bookFile(dir, id) {
119
+ for (const ext of ['.txt', '.md']) {
120
+ const p = join(dir, 'books', id + ext)
121
+ try {
122
+ const st = await stat(p)
123
+ return { path: p, size: st.size, mtimeMs: st.mtimeMs }
124
+ } catch {}
125
+ }
126
+ throw new Error(`没有这本书:${id}`)
127
+ }
128
+
129
+ function utf8Width(cp) {
130
+ return cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4
131
+ }
132
+
133
+ /** GB18030 的字节宽度:ASCII 1;0x81–0xFE + 0x30–0x39 是四字节;其余两字节 */
134
+ function gbWidth(buf, i) {
135
+ const b = buf[i]
136
+ if (b < 0x80) return 1
137
+ if (b >= 0x81 && b <= 0xfe && i + 1 < buf.length && buf[i + 1] >= 0x30 && buf[i + 1] <= 0x39) return 4
138
+ return 2
139
+ }
140
+
141
+ /** 认编码(顺带认出 BOM 长度) */
142
+ export function sniffEncoding(buf) {
143
+ try {
144
+ new TextDecoder('utf-8', { fatal: true }).decode(buf)
145
+ const bom = buf.length >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf ? 3 : 0
146
+ return { encoding: 'utf-8', bom }
147
+ } catch {
148
+ return { encoding: 'gb18030', bom: 0 }
149
+ }
150
+ }
151
+
152
+ /**
153
+ * 扫一遍整本,产出章表。字符偏移 → 字节偏移走一遍累加,不建大数组。
154
+ * 返回 null 表示宽度累加对不上(文件坏了或怪编码),调用方退回整本方案。
155
+ */
156
+ export function buildToc(buffer, id) {
157
+ const { encoding, bom } = sniffEncoding(buffer)
158
+ const body = bom ? buffer.subarray(bom) : buffer
159
+ const text = stripBom(new TextDecoder(encoding).decode(body))
160
+ const chapters = splitChapters(text)
161
+ const starts = chapters.map((c) => c.start)
162
+ let ci = 0
163
+ let bi = bom
164
+ let k = 0
165
+ for (const ch of text) {
166
+ while (k < chapters.length && starts[k] === ci) {
167
+ chapters[k].byteStart = bi
168
+ k += 1
169
+ }
170
+ const cp = ch.codePointAt(0)
171
+ bi += encoding === 'utf-8' ? utf8Width(cp) : gbWidth(body, bi)
172
+ ci += ch.length
173
+ }
174
+ while (k < chapters.length) {
175
+ chapters[k].byteStart = bi
176
+ k += 1
177
+ }
178
+ for (let i = 0; i < chapters.length; i += 1) {
179
+ chapters[i].byteEnd = i + 1 < chapters.length ? chapters[i + 1].byteStart : buffer.length
180
+ }
181
+ if (bi !== buffer.length) return null
182
+ return {
183
+ version: TOC_VERSION,
184
+ id,
185
+ encoding,
186
+ bom,
187
+ bytes: buffer.length,
188
+ chars: text.length,
189
+ chapters,
190
+ }
191
+ }
192
+
193
+ /** 取章表:有且没过期就用,否则整本扫一次并重写 */
194
+ export async function tocFor(dir, id, opts = {}) {
195
+ const file = await bookFile(dir, id)
196
+ const tp = tocPath(dir, id)
197
+ if (!opts.force) {
198
+ try {
199
+ const saved = JSON.parse(stripBom(await readFile(tp, 'utf8')))
200
+ const fresh = saved
201
+ && saved.version === TOC_VERSION
202
+ && saved.bytes === file.size
203
+ && Number(saved.mtimeMs) === Math.round(file.mtimeMs)
204
+ && Array.isArray(saved.chapters)
205
+ && saved.chapters.length > 0
206
+ && saved.chapters.every((c) => Number.isInteger(c.byteStart) && Number.isInteger(c.byteEnd))
207
+ if (fresh) return { ...saved, file: file.path, tocPath: tp }
208
+ } catch {}
209
+ }
210
+ const buffer = await readFile(file.path)
211
+ const built = buildToc(buffer, id)
212
+ if (!built) return null
213
+ const rec = { ...built, file: basename(file.path), mtimeMs: Math.round(file.mtimeMs) }
214
+ await writeJson(tp, rec)
215
+ return { ...rec, file: file.path, tocPath: tp }
216
+ }
217
+
218
+ /** 只按偏移读那一章,不碰整本 */
219
+ export async function readChapterByOffset(dir, id, n) {
220
+ const toc = await tocFor(dir, id)
221
+ if (!toc) return null
222
+ const c = toc.chapters[n - 1]
223
+ if (!c) return { text: '', chapter: null, toc }
224
+ const len = c.byteEnd - c.byteStart
225
+ const buf = Buffer.alloc(len)
226
+ let off = 0
227
+ const fh = await open(toc.file, 'r')
228
+ try {
229
+ while (off < len) {
230
+ const { bytesRead } = await fh.read(buf, off, len - off, c.byteStart + off)
231
+ if (!bytesRead) break
232
+ off += bytesRead
233
+ }
234
+ } finally {
235
+ await fh.close()
236
+ }
237
+ const text = stripBom(new TextDecoder(toc.encoding).decode(buf.subarray(0, off)))
238
+ return { text: text.trim(), chapter: c, toc, tocPath: toc.tocPath }
239
+ }
240
+
241
+ /** 一章正文:先走章表,实在没有才退回整本切 */
242
+ export async function chapterBody(dir, id, info, n) {
243
+ try {
244
+ const got = await readChapterByOffset(dir, id, n)
245
+ if (got) return got.text
246
+ } catch {}
247
+ if (typeof info?.text === 'string') return chapterText(info.text, info.chapters, n)
248
+ const file = await bookFile(dir, id)
249
+ const text = await readTextSmart(await readFile(file.path))
250
+ return chapterText(text, splitChapters(text), n)
251
+ }
252
+
253
+ /** 搜东西这种确实要整本的,才整本读 */
254
+ export async function fullTextOf(dir, id) {
255
+ const file = await bookFile(dir, id)
256
+ const text = await readTextSmart(await readFile(file.path))
257
+ return { text, chapters: splitChapters(text) }
258
+ }
259
+
107
260
  /** 书库:books/*.txt */
108
261
  export async function listBooks(dir) {
109
262
  const out = []
@@ -119,18 +272,13 @@ export async function listBooks(dir) {
119
272
  return out
120
273
  }
121
274
 
122
- /** 打开某本书并缓存它有多少章 */
275
+ /** 打开某本书:优先用章表(不整本 decode),没有章表才扫一遍并落盘 */
123
276
  export async function bookInfo(dir, id) {
124
- const p = join(dir, 'books', id + '.txt')
125
- let text
126
- try {
127
- text = await readTextSmart(await readFile(p))
128
- } catch {
129
- const p2 = join(dir, 'books', id + '.md')
130
- text = await readTextSmart(await readFile(p2))
131
- }
132
- const chapters = splitChapters(text)
133
- return { text, chapters }
277
+ const toc = await tocFor(dir, id)
278
+ if (toc) return { chapters: toc.chapters, toc, tocPath: toc.tocPath, text: null }
279
+ const file = await bookFile(dir, id)
280
+ const text = await readTextSmart(await readFile(file.path))
281
+ return { text, chapters: splitChapters(text), toc: null, tocPath: '' }
134
282
  }
135
283
 
136
284
  export async function importBook(dir, srcPath) {
@@ -318,7 +466,7 @@ export function apply(ctx) {
318
466
  const ch = n > 0 ? Math.min(Math.max(1, n), info.chapters.length) : (rec.readThrough || 1)
319
467
  res.end(JSON.stringify({
320
468
  ok: true, book: id, chapter: ch, total: info.chapters.length,
321
- title: info.chapters[ch - 1]?.title || '', text: chapterText(info.text, info.chapters, ch),
469
+ title: info.chapters[ch - 1]?.title || '', text: await chapterBody(dir, id, info, ch),
322
470
  }))
323
471
  } catch (e) {
324
472
  res.end(JSON.stringify({ ok: false, error: String(e && e.message || e) }))
@@ -891,7 +1039,7 @@ async function signWork(rel, who) {
891
1039
  rec.chapters = info.chapters.length
892
1040
  const n = Number(args?.chapter) > 0 ? Math.floor(Number(args.chapter)) : rec.next || 1
893
1041
  if (n < 1 || n > info.chapters.length) throw new Error(`章号超出范围:1–${info.chapters.length}`)
894
- const body = chapterText(info.text, info.chapters, n)
1042
+ const body = await chapterBody(dir, id, info, n)
895
1043
  rec.readThrough = Math.max(rec.readThrough || 0, n)
896
1044
  rec.next = Math.min(info.chapters.length, n + 1)
897
1045
  rec.lastReadAt = new Date().toISOString()
@@ -906,6 +1054,7 @@ async function signWork(rel, who) {
906
1054
  chapter: n,
907
1055
  title: info.chapters[n - 1].title,
908
1056
  chapters: info.chapters.length,
1057
+ tocPath: info.tocPath || '',
909
1058
  chars: body.length,
910
1059
  next: rec.next,
911
1060
  perDay,
@@ -997,7 +1146,7 @@ async function signWork(rel, who) {
997
1146
  const { dir, st } = await stateOf()
998
1147
  const id = args?.book || st.current
999
1148
  if (!id) throw new Error('还没有正在读的书')
1000
- const { text, chapters } = await bookInfo(dir, id)
1149
+ const { text, chapters } = await fullTextOf(dir, id)
1001
1150
  const hits = []
1002
1151
  let at = text.indexOf(q)
1003
1152
  while (at >= 0 && hits.length < limit) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-half-page",
3
- "version": "0.3.35",
3
+ "version": "0.3.36",
4
4
  "private": false,
5
5
  "author": "鹿野 <luye@dsh.local>",
6
6
  "license": "MIT",
@@ -45,4 +45,4 @@
45
45
  "engines": {
46
46
  "dsh": ">=0.2.1-rc.0 <0.3.0-0"
47
47
  }
48
- }
48
+ }