dsh-lamplit 0.0.0-stage → 0.1.2

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/lib/epub.js ADDED
@@ -0,0 +1,209 @@
1
+ /**
2
+ * EPUB 解析(零依赖):ZIP 目录 → container.xml → OPF → spine → XHTML → blocks。
3
+ *
4
+ * 这就是常规电子书阅读器的做法:**把书拆成 HTML 文档再排版**,而不是当成图片。
5
+ * MOBI / AZW3 / KFX 不在支持范围:它们是亚马逊私有容器(KFX 还带 DRM),
6
+ * 桌面阅读器也是先转换(Calibre / KindleUnpack)再读,界面上会给同样的提示。
7
+ */
8
+ import zlib from 'node:zlib'
9
+
10
+ import { decodeEntities } from './text-util.js'
11
+
12
+ // ---- ZIP ------------------------------------------------------------------
13
+
14
+ const EOCD = 0x06054b50
15
+ const CENTRAL = 0x02014b50
16
+ const LOCAL = 0x04034b50
17
+
18
+ function findEocd(buffer) {
19
+ const min = Math.max(0, buffer.length - 66000)
20
+ for (let offset = buffer.length - 22; offset >= min; offset -= 1) {
21
+ if (buffer.readUInt32LE(offset) === EOCD) return offset
22
+ }
23
+ return -1
24
+ }
25
+
26
+ /** @returns {Map<string, () => Buffer>} 文件名 → 惰性解压函数 */
27
+ function readZip(buffer) {
28
+ const eocd = findEocd(buffer)
29
+ if (eocd < 0) throw new Error('not a zip')
30
+ const count = buffer.readUInt16LE(eocd + 10)
31
+ let cursor = buffer.readUInt32LE(eocd + 16)
32
+ const files = new Map()
33
+
34
+ for (let index = 0; index < count; index += 1) {
35
+ if (cursor + 46 > buffer.length || buffer.readUInt32LE(cursor) !== CENTRAL) break
36
+ const method = buffer.readUInt16LE(cursor + 10)
37
+ const compressedSize = buffer.readUInt32LE(cursor + 20)
38
+ const uncompressedSize = buffer.readUInt32LE(cursor + 24)
39
+ const nameLength = buffer.readUInt16LE(cursor + 28)
40
+ const extraLength = buffer.readUInt16LE(cursor + 30)
41
+ const commentLength = buffer.readUInt16LE(cursor + 32)
42
+ const localOffset = buffer.readUInt32LE(cursor + 42)
43
+ const name = buffer.toString('utf8', cursor + 46, cursor + 46 + nameLength)
44
+ cursor += 46 + nameLength + extraLength + commentLength
45
+
46
+ files.set(name, () => {
47
+ if (buffer.readUInt32LE(localOffset) !== LOCAL) throw new Error(`bad local header: ${name}`)
48
+ const localNameLength = buffer.readUInt16LE(localOffset + 26)
49
+ const localExtraLength = buffer.readUInt16LE(localOffset + 28)
50
+ const start = localOffset + 30 + localNameLength + localExtraLength
51
+ const raw = buffer.subarray(start, start + compressedSize)
52
+ if (method === 0) return Buffer.from(raw)
53
+ if (method === 8) return zlib.inflateRawSync(raw)
54
+ throw new Error(`unsupported zip compression: ${method}`)
55
+ })
56
+ }
57
+ return files
58
+ }
59
+
60
+ // ---- XHTML → blocks -------------------------------------------------------
61
+
62
+ const BLOCK_TAGS = /<(p|div|h1|h2|h3|h4|h5|h6|blockquote|li|tr|section|article)\b[^>]*>/gi
63
+
64
+ const HEADING_MARK = '\u0001H'
65
+
66
+ function htmlToBlocks(html) {
67
+ let text = String(html ?? '')
68
+ text = text.replace(/<\s*(script|style|head)[\s\S]*?<\s*\/\s*\1\s*>/gi, '')
69
+ text = text.replace(/<h([1-4])[^>]*>([\s\S]*?)<\/h\1>/gi, (_match, level, inner) => {
70
+ const label = String(inner).replace(/<[^>]+>/g, '').trim()
71
+ return `\n${HEADING_MARK}${level}${HEADING_MARK}${label}\n`
72
+ })
73
+ text = text.replace(/<br\s*\/?>/gi, '\n')
74
+ text = text.replace(/<img\b[^>]*alt="([^"]*)"[^>]*>/gi, (_match, alt) => `\n〔图:${alt}〕\n`)
75
+ text = text.replace(/<img\b[^>]*>/gi, '\n〔图〕\n')
76
+ text = text.replace(/<\/(p|div|h1|h2|h3|h4|h5|h6|blockquote|li|tr|section|article)>/gi, '\n')
77
+ text = text.replace(BLOCK_TAGS, '\n')
78
+ text = text.replace(/<[^>]+>/g, '')
79
+ text = decodeEntities(text)
80
+
81
+ const blocks = []
82
+ for (const rawLine of text.split('\n')) {
83
+ const line = rawLine.replace(/[ \t\u00a0]+/g, ' ').trim()
84
+ if (line === '') continue
85
+ if (line.startsWith(HEADING_MARK)) {
86
+ const parts = line.split(HEADING_MARK)
87
+ const level = Number(parts[1]) || 3
88
+ const heading = String(parts.slice(2).join('')).trim()
89
+ if (heading !== '') blocks.push({ t: 'h', l: Math.min(Math.max(level, 1), 3), x: heading })
90
+ continue
91
+ }
92
+ blocks.push({ t: 'p', x: line })
93
+ }
94
+ return blocks
95
+ }
96
+
97
+ function firstHeading(html) {
98
+ const match = /<h([1-3])[^>]*>([\s\S]*?)<\/h\1>/i.exec(String(html))
99
+ if (!match) return ''
100
+ return decodeEntities(match[2].replace(/<[^>]+>/g, '')).replace(/\s+/g, ' ').trim()
101
+ }
102
+
103
+ function tag(html, name) {
104
+ const match = new RegExp(`<${name}[^>]*>([\\s\\S]*?)</${name}>`, 'i').exec(String(html))
105
+ if (!match) return ''
106
+ return decodeEntities(match[1].replace(/<[^>]+>/g, '')).trim()
107
+ }
108
+
109
+ function resolvePath(base, href) {
110
+ if (/^[a-z]+:/i.test(href)) return href
111
+ const stack = base.split('/').filter((part) => part !== '' && part !== '.')
112
+ for (const part of href.split('/')) {
113
+ if (part === '' || part === '.') continue
114
+ if (part === '..') stack.pop()
115
+ else stack.push(part)
116
+ }
117
+ return stack.join('/')
118
+ }
119
+
120
+ /**
121
+ * @param {Buffer} buffer
122
+ * @returns {{title: string, author: string, chapters: Array<{title, blocks}>, warnings: string[]}}
123
+ */
124
+ export function parseEpub(buffer) {
125
+ const files = readZip(buffer)
126
+ const read = (name) => {
127
+ const entry = files.get(name)
128
+ if (!entry) return ''
129
+ return entry().toString('utf8')
130
+ }
131
+
132
+ const container = read('META-INF/container.xml')
133
+ const opfPath = /full-path="([^"]+)"/.exec(container)?.[1] ?? ''
134
+ if (opfPath === '') throw new Error('epub 缺少 container.xml')
135
+ const opf = read(opfPath)
136
+ if (opf === '') throw new Error('epub 缺少 OPF')
137
+
138
+ const title = tag(opf, 'dc:title') || tag(opf, 'title')
139
+ const author = tag(opf, 'dc:creator') || tag(opf, 'creator')
140
+
141
+ const base = opfPath.includes('/') ? opfPath.slice(0, opfPath.lastIndexOf('/')) : ''
142
+ const manifest = new Map()
143
+ for (const item of opf.matchAll(/<item\b[^>]*>/gi)) {
144
+ const tagText = item[0]
145
+ const id = /id="([^"]+)"/.exec(tagText)?.[1]
146
+ const href = /href="([^"]+)"/.exec(tagText)?.[1]
147
+ const type = /media-type="([^"]+)"/.exec(tagText)?.[1] ?? ''
148
+ if (id && href) manifest.set(id, { href: resolvePath(base, href), type })
149
+ }
150
+
151
+ const spine = []
152
+ for (const itemref of opf.matchAll(/<itemref\b[^>]*>/gi)) {
153
+ const idref = /idref="([^"]+)"/.exec(itemref[0])?.[1]
154
+ if (!idref) continue
155
+ const item = manifest.get(idref)
156
+ if (!item) continue
157
+ if (!/html|xml/i.test(item.type)) continue
158
+ spine.push(item.href)
159
+ }
160
+ if (spine.length === 0) throw new Error('epub 的 spine 是空的')
161
+
162
+ // 目录标题(nav 或 ncx)
163
+ const tocTitles = new Map()
164
+ const navHref = [...manifest.values()].find((item) => /nav\.xhtml$/i.test(item.href))?.href
165
+ const ncxHref = [...manifest.values()].find((item) => /\.ncx$/i.test(item.href))?.href
166
+ const tocHtml = navHref ? read(navHref) : ncxHref ? read(ncxHref) : ''
167
+ if (tocHtml !== '') {
168
+ for (const match of tocHtml.matchAll(/<a\b[^>]*href="([^"#]+)(?:#[^"]*)?"[^>]*>([\s\S]*?)<\/a>/gi)) {
169
+ const target = resolvePath(navHref ? navHref.includes('/') ? navHref.slice(0, navHref.lastIndexOf('/')) : '' : '', match[1])
170
+ const text = decodeEntities(match[2].replace(/<[^>]+>/g, '')).replace(/\s+/g, ' ').trim()
171
+ if (text !== '' && !tocTitles.has(target)) tocTitles.set(target, text)
172
+ }
173
+ for (const match of tocHtml.matchAll(/<navPoint\b[\s\S]*?<text>([\s\S]*?)<\/text>[\s\S]*?src="([^"]+)"/gi)) {
174
+ const target = resolvePath(ncxHref.includes('/') ? ncxHref.slice(0, ncxHref.lastIndexOf('/')) : '', match[2])
175
+ const text = decodeEntities(match[1]).trim()
176
+ if (text !== '' && !tocTitles.has(target)) tocTitles.set(target, text)
177
+ }
178
+ }
179
+
180
+ const chapters = []
181
+ const warnings = []
182
+ for (const [index, href] of spine.entries()) {
183
+ const html = read(href)
184
+ if (html === '') {
185
+ warnings.push(`spine 第 ${index + 1} 项读不到:${href}`)
186
+ continue
187
+ }
188
+ const blocks = htmlToBlocks(html)
189
+ if (blocks.length === 0) continue
190
+ const heading = firstHeading(html)
191
+ const chapterTitle = tocTitles.get(href) || heading || `第 ${chapters.length + 1} 节`
192
+ // 章标题已经写在目录里了,正文开头重复的同一个标题去掉。
193
+ if (blocks.length > 0 && blocks[0].t === 'h' && blocks[0].x === chapterTitle) blocks.shift()
194
+ chapters.push({ title: chapterTitle, blocks })
195
+ }
196
+ if (chapters.length === 0) throw new Error('epub 里没有可读的正文')
197
+
198
+ return {
199
+ title: title || '',
200
+ author,
201
+ chapters,
202
+ warnings,
203
+ }
204
+ }
205
+
206
+ /** 只判断是不是 EPUB 容器(不改状态)。 */
207
+ export function looksLikeEpub(buffer) {
208
+ return buffer.length > 4 && buffer[0] === 0x50 && buffer[1] === 0x4b && buffer[2] === 0x03 && buffer[3] === 0x04
209
+ }
package/lib/http.js ADDED
@@ -0,0 +1,93 @@
1
+ /** 出站 HTTP 小工具:超时、UA、cookie、JSON 容错。 */
2
+
3
+ export const BROWSER_UA =
4
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36'
5
+
6
+ export class ProviderError extends Error {
7
+ constructor(code, message, details) {
8
+ super(message)
9
+ this.name = 'ProviderError'
10
+ this.code = code
11
+ this.details = details ?? {}
12
+ }
13
+ }
14
+
15
+ export function withDeadline(timeoutMs, signal) {
16
+ const deadline = AbortSignal.timeout(timeoutMs)
17
+ return signal === undefined ? deadline : AbortSignal.any([signal, deadline])
18
+ }
19
+
20
+ /**
21
+ * @param {string} url
22
+ * @param {{method?: string, headers?: Record<string,string>, cookie?: string, body?: unknown, timeoutMs?: number, signal?: AbortSignal, referer?: string, accept?: string}} options
23
+ */
24
+ export async function request(url, options = {}) {
25
+ const {
26
+ method = 'GET',
27
+ headers = {},
28
+ cookie,
29
+ body,
30
+ timeoutMs = 20000,
31
+ signal,
32
+ referer,
33
+ accept = 'application/json, text/plain, */*',
34
+ } = options
35
+ const finalHeaders = {
36
+ 'user-agent': BROWSER_UA,
37
+ accept,
38
+ 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
39
+ ...headers,
40
+ }
41
+ if (cookie) finalHeaders.cookie = cookie
42
+ if (referer) finalHeaders.referer = referer
43
+ let payload = body
44
+ if (body !== undefined && typeof body !== 'string') {
45
+ finalHeaders['content-type'] = finalHeaders['content-type'] ?? 'application/json'
46
+ payload = JSON.stringify(body)
47
+ }
48
+ let response
49
+ try {
50
+ response = await fetch(url, { method, headers: finalHeaders, body: payload, signal: withDeadline(timeoutMs, signal) })
51
+ } catch (error) {
52
+ if (error?.name === 'TimeoutError') throw new ProviderError('NET', `请求超时:${new URL(url).host}`)
53
+ throw new ProviderError('NET', `连不上 ${new URL(url).host}:${error?.message ?? String(error)}`)
54
+ }
55
+ return response
56
+ }
57
+
58
+ export async function requestJson(url, options = {}) {
59
+ const response = await request(url, options)
60
+ const text = await response.text()
61
+ if (text.trim() === '') {
62
+ throw new ProviderError('NET', `${new URL(url).host} 返回了空响应(可能被风控拦截)。`, { status: response.status })
63
+ }
64
+ try {
65
+ return { status: response.status, ok: response.ok, json: JSON.parse(text), text }
66
+ } catch {
67
+ throw new ProviderError('NET', `${new URL(url).host} 返回的不是 JSON。`, { status: response.status, sample: text.slice(0, 160) })
68
+ }
69
+ }
70
+
71
+ export function parseCookie(raw) {
72
+ const pairs = new Map()
73
+ for (const part of String(raw ?? '').split(';')) {
74
+ const index = part.indexOf('=')
75
+ if (index <= 0) continue
76
+ const key = part.slice(0, index).trim()
77
+ const value = part.slice(index + 1).trim()
78
+ if (key !== '') pairs.set(key, value)
79
+ }
80
+ return pairs
81
+ }
82
+
83
+ /** 从链接里取番茄 / 微信读书的 id。 */
84
+ export function extractBookId(input) {
85
+ const text = String(input ?? '').trim()
86
+ if (text === '') return ''
87
+ const fanqie = /(?:fanqienovel\.com\/(?:page|reader)\/|changdunovel\.com\/(?:page|reader)\/)(\d{6,})/.exec(text)
88
+ if (fanqie) return fanqie[1]
89
+ const weread = /weread\.qq\.com\/web\/book\/(?:detail\/)?([A-Za-z0-9_-]{6,})/.exec(text)
90
+ if (weread) return weread[1]
91
+ if (/^\d{6,}$/.test(text)) return text
92
+ return ''
93
+ }
@@ -0,0 +1,233 @@
1
+ /** Markdown → 章节 / blocks。 */
2
+ import { joinLines, stripInline } from './text-util.js'
3
+
4
+ const HEADING = /^(#{1,6})\s+(.*)$/
5
+ const BULLET = /^\s{0,3}(?:[-*+]|\d{1,3}[.)])\s+(.*)$/
6
+ const FENCE = /^\s*(```+|~~~+)\s*([\w-]*)\s*$/
7
+ const RULE = /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/
8
+ const TABLE_ROW = /^\s*\|(.+)\|\s*$/
9
+ const TABLE_DIVIDER = /^\s*\|?[\s:|-]+\|?\s*$/
10
+ /** h2 只有在明显是「章」时才切章:节、小节不算。 */
11
+ const STRICT_CHAPTER = /^(?:第[零一二三四五六七八九十百千万两0-9]{1,12}[章回卷篇幕](?:\s|$|[::、..])|序章|楔子|尾声|终章|后记|番外|Chapter\s)/i
12
+
13
+ /**
14
+ * @param {string} source
15
+ * @param {{fallbackTitle?: string}} options
16
+ * @returns {{title: string, author: string, chapters: Array<{title: string, blocks: Array, chars: number}>}}
17
+ */
18
+ export function parseMarkdown(source, options = {}) {
19
+ const fallbackTitle = (options.fallbackTitle ?? '').trim()
20
+ const lines = String(source ?? '')
21
+ .replace(/\r\n?/g, '\n')
22
+ .replace(/\t/g, ' ')
23
+ .split('\n')
24
+
25
+ const meta = { title: '', author: '' }
26
+ let start = 0
27
+ if (lines[0]?.trim() === '---') {
28
+ for (let index = 1; index < Math.min(lines.length, 80); index += 1) {
29
+ if (lines[index].trim() === '---' || lines[index].trim() === '...') {
30
+ for (let cursor = 1; cursor < index; cursor += 1) {
31
+ const match = /^([A-Za-z_]+)\s*:\s*(.*)$/.exec(lines[cursor])
32
+ if (!match) continue
33
+ const key = match[1].toLowerCase()
34
+ const value = match[2].trim().replace(/^["']|["']$/g, '')
35
+ if (key === 'title' && value !== '') meta.title = value
36
+ if (key === 'author' && value !== '') meta.author = value
37
+ }
38
+ start = index + 1
39
+ break
40
+ }
41
+ }
42
+ }
43
+
44
+ // 有 h1 的书,h2 是节而不是章;没有 h1 的书,h2 才当章用。
45
+ const hasH1 = lines.slice(start).some((line) => /^#\s+\S/.test(line))
46
+
47
+ const chapters = []
48
+ let chapter = { title: '', blocks: [] }
49
+ let paragraph = []
50
+ let quote = []
51
+ let tableRows = []
52
+
53
+ const pushBlock = (block) => {
54
+ if (block !== null) chapter.blocks.push(block)
55
+ }
56
+ const flushParagraph = () => {
57
+ if (paragraph.length === 0) return
58
+ const text = stripInline(joinLines(paragraph))
59
+ paragraph = []
60
+ if (text !== '') pushBlock({ t: 'p', x: text })
61
+ }
62
+ const flushQuote = () => {
63
+ if (quote.length === 0) return
64
+ const text = quote.join(' ').trim()
65
+ quote = []
66
+ if (text !== '') pushBlock({ t: 'q', x: text })
67
+ }
68
+ const flushTable = () => {
69
+ if (tableRows.length === 0) return
70
+ const rows = tableRows
71
+ tableRows = []
72
+ const body = rows
73
+ .filter((row) => !TABLE_DIVIDER.test(`|${row}|`))
74
+ .map((row) => row.split('|').map((cell) => stripInline(cell)).filter((cell) => cell !== '').join(' | '))
75
+ .filter((row) => row !== '')
76
+ for (const row of body) pushBlock({ t: 'p', x: row })
77
+ }
78
+ const flushAll = () => {
79
+ flushParagraph()
80
+ flushQuote()
81
+ flushTable()
82
+ }
83
+ const finishChapter = () => {
84
+ flushAll()
85
+ if (chapter.blocks.length > 0) chapters.push(chapter)
86
+ chapter = { title: '', blocks: [] }
87
+ }
88
+
89
+ let fence = null
90
+ let fenceBuffer = []
91
+ for (let index = start; index < lines.length; index += 1) {
92
+ const line = lines[index]
93
+ const fenceMatch = FENCE.exec(line)
94
+ if (fence !== null) {
95
+ if (fenceMatch) {
96
+ pushBlock({ t: 'code', x: fenceBuffer.join('\n').replace(/\s+$/, '') })
97
+ fenceBuffer = []
98
+ fence = null
99
+ } else {
100
+ fenceBuffer.push(line)
101
+ }
102
+ continue
103
+ }
104
+ if (fenceMatch) {
105
+ flushAll()
106
+ fence = fenceMatch[1]
107
+ continue
108
+ }
109
+
110
+ const heading = HEADING.exec(line)
111
+ if (heading) {
112
+ const level = heading[1].length
113
+ const text = stripInline(heading[2])
114
+ flushAll()
115
+ const chapterHeading = level === 1 || (level === 2 && (!hasH1 || STRICT_CHAPTER.test(text)))
116
+ if (chapterHeading) {
117
+ finishChapter()
118
+ chapter.title = text
119
+ } else if (text !== '') {
120
+ pushBlock({ t: 'h', l: level === 2 ? 2 : 3, x: text })
121
+ }
122
+ continue
123
+ }
124
+
125
+ if (line.trim() === '') {
126
+ flushAll()
127
+ continue
128
+ }
129
+
130
+ const tableMatch = TABLE_ROW.exec(line)
131
+ if (tableMatch) {
132
+ flushParagraph()
133
+ flushQuote()
134
+ tableRows.push(tableMatch[1])
135
+ continue
136
+ }
137
+ if (tableRows.length > 0) flushTable()
138
+
139
+ if (RULE.test(line)) {
140
+ flushAll()
141
+ pushBlock({ t: 'hr' })
142
+ continue
143
+ }
144
+
145
+ const quoteMatch = /^\s{0,3}>\s?(.*)$/.exec(line)
146
+ if (quoteMatch) {
147
+ flushParagraph()
148
+ quote.push(stripInline(quoteMatch[1]))
149
+ continue
150
+ }
151
+ if (quote.length > 0) flushQuote()
152
+
153
+ const bullet = BULLET.exec(line)
154
+ if (bullet) {
155
+ flushParagraph()
156
+ const text = stripInline(bullet[1])
157
+ if (text !== '') pushBlock({ t: 'li', x: text })
158
+ continue
159
+ }
160
+
161
+ paragraph.push(line.trim())
162
+ }
163
+
164
+ if (fence !== null) {
165
+ pushBlock({ t: 'code', x: fenceBuffer.join('\n').replace(/\s+$/, '') })
166
+ }
167
+ finishChapter()
168
+
169
+ const cleaned = chapters.length > 0 ? chapters : fallbackChapters(lines.slice(start), fallbackTitle)
170
+ const segments = []
171
+ cleaned.forEach((item, index) => {
172
+ const baseTitle = item.title || (index === 0 ? fallbackTitle || '正文' : `第 ${index + 1} 章`)
173
+ const parts = splitOversized(item.blocks)
174
+ parts.forEach((part, partIndex) => {
175
+ segments.push({
176
+ title: partIndex === 0 ? baseTitle : `${baseTitle}(${partIndex + 1})`,
177
+ blocks: part,
178
+ })
179
+ })
180
+ })
181
+
182
+ return {
183
+ title: meta.title || cleaned[0]?.title || fallbackTitle || '未命名',
184
+ author: meta.author,
185
+ chapters: segments.map((entry) => ({
186
+ title: entry.title,
187
+ blocks: entry.blocks,
188
+ chars: entry.blocks.reduce((sum, block) => sum + (typeof block.x === 'string' ? block.x.length : 0), 0),
189
+ })),
190
+ }
191
+ }
192
+
193
+ /** 没有任何标题的 Markdown:整篇一段,标题用文件名。 */
194
+ function fallbackChapters(lines, fallbackTitle) {
195
+ const blocks = []
196
+ let paragraph = []
197
+ for (const line of lines) {
198
+ const text = stripInline(line)
199
+ if (text === '') {
200
+ if (paragraph.length > 0) {
201
+ blocks.push({ t: 'p', x: joinLines(paragraph) })
202
+ paragraph = []
203
+ }
204
+ continue
205
+ }
206
+ paragraph.push(text)
207
+ }
208
+ if (paragraph.length > 0) blocks.push({ t: 'p', x: joinLines(paragraph) })
209
+ return [{ title: fallbackTitle || '正文', blocks }]
210
+ }
211
+
212
+ const MAX_CHAPTER_CHARS = 24000
213
+
214
+ /** 超长章节按段落切段,返回多个 block 数组。 */
215
+ function splitOversized(blocks) {
216
+ const total = blocks.reduce((sum, block) => sum + (typeof block.x === 'string' ? block.x.length : 0), 0)
217
+ if (total <= MAX_CHAPTER_CHARS) return [blocks]
218
+ const parts = []
219
+ let current = []
220
+ let size = 0
221
+ for (const block of blocks) {
222
+ const length = typeof block.x === 'string' ? block.x.length : 0
223
+ if (size > 0 && size + length > MAX_CHAPTER_CHARS) {
224
+ parts.push(current)
225
+ current = []
226
+ size = 0
227
+ }
228
+ current.push(block)
229
+ size += length
230
+ }
231
+ if (current.length > 0) parts.push(current)
232
+ return parts.length > 0 ? parts : [blocks]
233
+ }
package/lib/notes.js ADDED
@@ -0,0 +1,155 @@
1
+ /** 笔记与划线:一本书里的引文 + 读者/AI 的想法。 */
2
+ import fsp from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import crypto from 'node:crypto'
5
+
6
+ export class Notes {
7
+ constructor(root) {
8
+ this.file = path.join(root, 'notes.json')
9
+ this.notes = []
10
+ this.loaded = false
11
+ this.queue = Promise.resolve()
12
+ }
13
+
14
+ async load() {
15
+ if (this.loaded) return this.notes
16
+ try {
17
+ const parsed = JSON.parse(await fsp.readFile(this.file, 'utf8'))
18
+ this.notes = Array.isArray(parsed) ? parsed.filter((note) => note && typeof note.id === 'string') : []
19
+ } catch (error) {
20
+ if (error?.code !== 'ENOENT') throw error
21
+ this.notes = []
22
+ }
23
+ this.loaded = true
24
+ return this.notes
25
+ }
26
+
27
+ serialize(operation) {
28
+ const run = this.queue.then(operation, operation)
29
+ this.queue = run.then(
30
+ () => undefined,
31
+ () => undefined,
32
+ )
33
+ return run
34
+ }
35
+
36
+ async #persist() {
37
+ await fsp.mkdir(path.dirname(this.file), { recursive: true })
38
+ const tmp = `${this.file}.tmp`
39
+ await fsp.writeFile(tmp, JSON.stringify(this.notes, null, 2), { mode: 0o600 })
40
+ await fsp.rename(tmp, this.file)
41
+ }
42
+
43
+ async list({ bookId } = {}) {
44
+ await this.load()
45
+ const items = bookId ? this.notes.filter((note) => note.bookId === bookId) : this.notes
46
+ return [...items].sort((left, right) => right.createdAt - left.createdAt)
47
+ }
48
+
49
+ async counts() {
50
+ await this.load()
51
+ const map = new Map()
52
+ for (const note of this.notes) map.set(note.bookId, (map.get(note.bookId) ?? 0) + 1)
53
+ return map
54
+ }
55
+
56
+ async add(input) {
57
+ return this.serialize(async () => {
58
+ await this.load()
59
+ const note = {
60
+ id: `nt_${crypto.randomBytes(5).toString('hex')}`,
61
+ bookId: String(input.bookId ?? ''),
62
+ bookTitle: String(input.bookTitle ?? ''),
63
+ chapterIndex: Number(input.chapterIndex) || 0,
64
+ chapterTitle: String(input.chapterTitle ?? ''),
65
+ quote: String(input.quote ?? '').slice(0, 4000),
66
+ note: String(input.note ?? '').slice(0, 20000),
67
+ mode: ['explain', 'expand', 'note'].includes(input.mode) ? input.mode : 'note',
68
+ createdAt: Date.now(),
69
+ }
70
+ this.notes.push(note)
71
+ await this.#persist()
72
+ return note
73
+ })
74
+ }
75
+
76
+ async remove(id) {
77
+ return this.serialize(async () => {
78
+ await this.load()
79
+ const index = this.notes.findIndex((note) => note.id === id)
80
+ if (index < 0) return false
81
+ this.notes.splice(index, 1)
82
+ await this.#persist()
83
+ return true
84
+ })
85
+ }
86
+
87
+ async removeBook(bookId) {
88
+ return this.serialize(async () => {
89
+ await this.load()
90
+ const before = this.notes.length
91
+ this.notes = this.notes.filter((note) => note.bookId !== bookId)
92
+ if (this.notes.length !== before) await this.#persist()
93
+ })
94
+ }
95
+ }
96
+
97
+ /** 笔记导出成 Markdown:按书分组、按时间排序,带出处与模式。 */
98
+ export function notesToMarkdown(notes, options = {}) {
99
+ const generatedAt = new Date().toLocaleString('zh-CN', { hour12: false })
100
+ const lines = []
101
+ lines.push('# 灯下 · 读书笔记')
102
+ lines.push('')
103
+ if (options.bookTitle) lines.push(`> 出自《${options.bookTitle}》`)
104
+ lines.push(`> 导出时间:${generatedAt} · 共 ${notes.length} 条`)
105
+ lines.push('')
106
+
107
+ const groups = new Map()
108
+ for (const note of notes) {
109
+ const key = note.bookId
110
+ if (!groups.has(key)) groups.set(key, { title: note.bookTitle || '未命名', items: [] })
111
+ groups.get(key).items.push(note)
112
+ }
113
+
114
+ for (const [, group] of groups) {
115
+ lines.push(`## 《${group.title}》`)
116
+ lines.push('')
117
+ const ordered = [...group.items].sort((left, right) => {
118
+ if (left.chapterIndex !== right.chapterIndex) return left.chapterIndex - right.chapterIndex
119
+ return left.createdAt - right.createdAt
120
+ })
121
+ for (const note of ordered) {
122
+ const where = note.chapterTitle ? `第 ${note.chapterIndex + 1} 章 · ${note.chapterTitle}` : `第 ${note.chapterIndex + 1} 章`
123
+ lines.push(`### ${where}`)
124
+ if (note.quote) {
125
+ for (const line of note.quote.split('\n')) lines.push(`> ${line}`)
126
+ lines.push('')
127
+ }
128
+ if (note.note) {
129
+ const label = note.mode === 'explain' ? '**解释**' : note.mode === 'expand' ? '**补充**' : ''
130
+ lines.push(`${label}${label ? ':' : ''}${note.note}`)
131
+ lines.push('')
132
+ }
133
+ lines.push(`<sub>${new Date(note.createdAt).toLocaleString('zh-CN', { hour12: false })}</sub>`)
134
+ lines.push('')
135
+ }
136
+ }
137
+ return lines.join('\n')
138
+ }
139
+
140
+ /** 书单导出:一眼看清读了什么、读到哪。 */
141
+ export function shelfToMarkdown(shelf) {
142
+ const generatedAt = new Date().toLocaleString('zh-CN', { hour12: false })
143
+ const lines = ['# 我的书架 · 灯下', '', `> 导出时间:${generatedAt} · 共 ${shelf.length} 本`, '']
144
+ lines.push('| 书名 | 作者 | 来源 | 进度 | 状态 |')
145
+ lines.push('| --- | --- | --- | --- | --- |')
146
+ for (const book of shelf) {
147
+ const percent = book.chapterCount > 0
148
+ ? Math.round(((book.progress?.chapterIndex ?? 0) + (book.progress?.percent ?? 0)) / book.chapterCount * 100)
149
+ : 0
150
+ const source = book.source === 'weread' ? '微信读书' : book.source === 'fanqie' ? '番茄小说' : '本地'
151
+ lines.push(`| ${book.title || '未命名'} | ${book.author || '—'} | ${source} | ${percent}% | ${book.finished ? '读完' : '在读'} |`)
152
+ }
153
+ lines.push('')
154
+ return lines.join('\n')
155
+ }