@gongfpp/dsh-novel-fish 1.1.0 → 1.2.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 (99) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +41 -20
  3. package/docs/evidence/settings-reliability.png +0 -0
  4. package/index.json +12 -0
  5. package/lib/client.js +734 -128
  6. package/locale/en.json +15 -0
  7. package/locale/zh.json +15 -0
  8. package/package.json +5 -7
  9. package/screenshots.json +6 -0
  10. package/docs/acceptance.md +0 -42
  11. package/docs/community-markets.md +0 -88
  12. package/docs/compatibility-017.md +0 -70
  13. package/docs/compatibility-101.md +0 -41
  14. package/docs/continuous-reading-020.md +0 -46
  15. package/docs/ebook-tests.md +0 -99
  16. package/docs/evidence/abc-result.json +0 -9
  17. package/docs/evidence/banner-100.png +0 -0
  18. package/docs/evidence/community-market-014-result.json +0 -170
  19. package/docs/evidence/compatibility-017-result.json +0 -65
  20. package/docs/evidence/continuous-reading-020-result.json +0 -72
  21. package/docs/evidence/formats-result.json +0 -12
  22. package/docs/evidence/live-ab.png +0 -0
  23. package/docs/evidence/live-collapsed.png +0 -0
  24. package/docs/evidence/live-disabled.png +0 -0
  25. package/docs/evidence/live-epub.png +0 -0
  26. package/docs/evidence/live-market.png +0 -0
  27. package/docs/evidence/live-resume.png +0 -0
  28. package/docs/evidence/live-unloaded.png +0 -0
  29. package/docs/evidence/long-result.json +0 -11
  30. package/docs/evidence/multi-region-014-result.json +0 -47
  31. package/docs/evidence/native-disclosure-013-result.json +0 -36
  32. package/docs/evidence/native-disclosures-013.png +0 -0
  33. package/docs/evidence/native-open-013.png +0 -0
  34. package/docs/evidence/native-settings-sample.md +0 -11
  35. package/docs/evidence/native-settings-types-015.png +0 -0
  36. package/docs/evidence/npm-market-014-result.json +0 -132
  37. package/docs/evidence/plugin-settings-details.png +0 -0
  38. package/docs/evidence/public-release-014-result.json +0 -51
  39. package/docs/evidence/public-release-015-result.json +0 -36
  40. package/docs/evidence/public-release-result.json +0 -48
  41. package/docs/evidence/reading-demo-100.png +0 -0
  42. package/docs/evidence/reading-two-expansions-110.gif +0 -0
  43. package/docs/evidence/reading-two-expansions-110.json +0 -89
  44. package/docs/evidence/samples-110-capture.json +0 -49
  45. package/docs/evidence/settings-011-result.json +0 -28
  46. package/docs/evidence/settings-011.png +0 -0
  47. package/docs/evidence/settings-100.png +0 -0
  48. package/docs/evidence/settings-110.png +0 -0
  49. package/docs/evidence/settings-chat-011.png +0 -0
  50. package/docs/evidence/type-append-012-result.json +0 -30
  51. package/docs/evidence/type-append-012.png +0 -0
  52. package/docs/evidence/type-settings-012.png +0 -0
  53. package/docs/evidence/unload-result.json +0 -7
  54. package/docs/host-adapter.md +0 -43
  55. package/docs/icon-metadata-021.md +0 -40
  56. package/docs/interaction-paths-020.md +0 -39
  57. package/docs/marketplace.md +0 -42
  58. package/docs/multi-region-update.md +0 -53
  59. package/docs/native-disclosure-update.md +0 -39
  60. package/docs/native-settings-update.md +0 -48
  61. package/docs/plugin-settings-update.md +0 -61
  62. package/docs/release.md +0 -151
  63. package/docs/settings-update.md +0 -49
  64. package/docs/type-append-update.md +0 -50
  65. package/pnpm-workspace.yaml +0 -5
  66. package/scripts/build.mjs +0 -70
  67. package/scripts/check-host-contracts.mjs +0 -247
  68. package/scripts/licenses/path-webpack.txt +0 -28
  69. package/scripts/make-readme-gif.mjs +0 -69
  70. package/scripts/test-browser-samples.mjs +0 -665
  71. package/scripts/test-candidate-books.mjs +0 -71
  72. package/scripts/test-ebook-corpus.mjs +0 -161
  73. package/src/bundled-books.js +0 -42
  74. package/src/chat-adapter.js +0 -278
  75. package/src/client.js +0 -61
  76. package/src/epub.js +0 -166
  77. package/src/novel-content.js +0 -28
  78. package/src/persistence.js +0 -271
  79. package/src/pg-notice.js +0 -19
  80. package/src/segments.js +0 -185
  81. package/src/settings.js +0 -243
  82. package/src/store.js +0 -429
  83. package/src/text-decoding.js +0 -28
  84. package/test/bundled-library.test.js +0 -526
  85. package/test/chat-adapter.test.js +0 -518
  86. package/test/client.test.js +0 -124
  87. package/test/ebooks.test.js +0 -192
  88. package/test/epub.test.js +0 -185
  89. package/test/helpers/host-primitives.js +0 -28
  90. package/test/helpers/memory-storage.js +0 -48
  91. package/test/host-contracts.test.js +0 -32
  92. package/test/import.test.js +0 -102
  93. package/test/persistence.test.js +0 -27
  94. package/test/pg-notice.test.js +0 -109
  95. package/test/release.test.js +0 -87
  96. package/test/segments.test.js +0 -182
  97. package/test/settings.test.js +0 -312
  98. package/test/store.test.js +0 -617
  99. package/test/text-decoding.test.js +0 -49
package/src/epub.js DELETED
@@ -1,166 +0,0 @@
1
- import JSZip from 'jszip'
2
- import CRC32 from 'crc-32'
3
- import { decodeBookText } from './text-decoding.js'
4
- import { DOMParser } from '@xmldom/xmldom'
5
- import containerModule from 'epubjs/lib/container.js'
6
- import packagingModule from 'epubjs/lib/packaging.js'
7
- import navigationModule from 'epubjs/lib/navigation.js'
8
- import { segmentChapters } from './segments.js'
9
-
10
- // Use epubjs's actual container/OPF/navigation parsers, not its rendering lifecycle.
11
- const Container = containerModule.default ?? containerModule
12
- const Packaging = packagingModule.default ?? packagingModule
13
- const Navigation = navigationModule.default ?? navigationModule
14
- const ORIGIN = 'https://local-epub.invalid/'
15
- const MAX_UNPACKED_BYTES = 128 * 1024 * 1024
16
-
17
- /** Parse an EPUB's declared linear spine once; no iframe, script, CSS, or network is used. */
18
- export async function parseEpub(file, targetLength = 600) {
19
- try {
20
- // 不启用全包 CRC 检查:它会在读取正文前解压所有未引用资源。
21
- const zip = await JSZip.loadAsync(await file.arrayBuffer())
22
- const budget = { remaining: MAX_UNPACKED_BYTES }
23
- const readXml = async path => {
24
- const entry = zip.file(path)
25
- if (!entry) throw new Error(`书内文件缺失:${path}`)
26
- const bytes = await readEntry(entry, budget)
27
- const source = decodeBookText(bytes, { xml: true })
28
- if (/<!ENTITY|<!DOCTYPE[^>]*\[/iu.test(source)) throw new Error(`不支持含外部实体声明的书内文件:${path}`)
29
- return new DOMParser({
30
- onError(level, message) { if (level !== 'warning') throw new Error(`${path}: ${message}`) },
31
- }).parseFromString(source, 'application/xml')
32
- }
33
- const container = new Container(await readXml('META-INF/container.xml'))
34
- const packagePath = archivePath(container.packagePath)
35
- const packaging = new Packaging(await readXml(packagePath))
36
- const navPath = packaging.navPath || packaging.ncxPath
37
- const navigation = navPath ? new Navigation(await readXml(archivePath(navPath, packagePath))) : null
38
- const labels = tocLabels(navigation?.toc ?? [], packagePath)
39
- const chapters = []
40
- for (const item of packaging.spine) {
41
- if (item.linear === 'no') continue
42
- const manifest = packaging.manifest[item.idref]
43
- if (!manifest) throw new Error(`阅读顺序引用了缺失章节:${item.idref}`)
44
- if (!['application/xhtml+xml', 'text/html'].includes(manifest.type)) {
45
- throw new Error(`不支持的章节格式:${manifest.type}`)
46
- }
47
- const path = archivePath(manifest.href, packagePath)
48
- const document = await readXml(path)
49
- const body = document.getElementsByTagNameNS('http://www.w3.org/1999/xhtml', 'body')[0]
50
- || document.getElementsByTagNameNS(null, 'body')[0]
51
- if (!body) throw new Error(`章节没有正文:${path}`)
52
- const sectionTitle = labels.get(path) || manifest.href.replace(/\.[^.]+$/u, '')
53
- let current = { title: sectionTitle, paragraphs: [] }
54
- const flush = () => {
55
- const text = current.paragraphs.join('\n\n').trim()
56
- if (text) chapters.push({ title: current.title, text })
57
- current = { title: sectionTitle, paragraphs: [] }
58
- }
59
- for (const block of extractBlocks(body)) {
60
- if (block.kind === 'heading') {
61
- flush()
62
- current = { title: block.text, paragraphs: [] }
63
- } else current.paragraphs.push(block.text)
64
- }
65
- flush()
66
- }
67
- const segments = segmentChapters(chapters, targetLength)
68
- if (!segments.length) throw new Error('EPUB 没有可读取的线性正文')
69
- return { chapters, segments, title: packaging.metadata.title || '' }
70
- } catch (error) {
71
- throw new Error(`EPUB 无法解析:${error instanceof Error ? error.message : String(error)}`)
72
- }
73
- }
74
-
75
- // 使用 JSZip 的分块流而非 async() 的全量累积,预算在保存每个块之前扣除。
76
- function readEntry(entry, budget) {
77
- return new Promise((resolve, reject) => {
78
- const stream = entry.internalStream('uint8array')
79
- let chunks = []
80
- let length = 0
81
- let checksum = 0
82
- let settled = false
83
- const fail = error => {
84
- if (settled) return
85
- settled = true
86
- // pause 会停止后续压缩输入;当前 inflate 输入仍可能产出少量块,回调不再保留它们。
87
- stream.pause()
88
- chunks = []
89
- reject(error)
90
- }
91
- stream.on('data', chunk => {
92
- if (settled) return
93
- if (chunk.byteLength > budget.remaining) {
94
- fail(new Error('EPUB 解压正文超过 128 MiB,请使用较小书籍'))
95
- return
96
- }
97
- budget.remaining -= chunk.byteLength
98
- length += chunk.byteLength
99
- checksum = CRC32.buf(chunk, checksum)
100
- chunks.push(chunk)
101
- }).on('error', fail).on('end', () => {
102
- if (settled) return
103
- // JSZip 未公开期望 CRC;此字段来自它解析的中央目录,只用于校验实际读取项。
104
- if ((checksum >>> 0) !== (entry._data.crc32 >>> 0)) {
105
- fail(new Error(`书内文件 CRC 校验失败:${entry.name}`))
106
- return
107
- }
108
- const bytes = new Uint8Array(length)
109
- let offset = 0
110
- for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength }
111
- chunks = []
112
- settled = true
113
- resolve(bytes)
114
- }).resume()
115
- })
116
- }
117
-
118
- function archivePath(href, base = '') {
119
- const url = new URL(href, new URL(base, ORIGIN))
120
- if (url.origin !== new URL(ORIGIN).origin || url.search) throw new Error('EPUB 只能引用书内文件')
121
- return decodeURIComponent(url.pathname.slice(1))
122
- }
123
-
124
- function hidden(node) {
125
- const tag = String(node.localName ?? node.nodeName).toLowerCase()
126
- return ['script', 'style', 'noscript', 'iframe', 'object', 'svg', 'nav'].includes(tag)
127
- || node.hasAttribute('hidden') || node.getAttribute('aria-hidden') === 'true'
128
- || /(?:display\s*:\s*none|visibility\s*:\s*hidden)/iu.test(node.getAttribute('style') || '')
129
- }
130
-
131
- function extractBlocks(root) {
132
- const blocks = []
133
- const blockTags = new Set(['div', 'section', 'article', 'aside', 'main', 'header', 'footer', 'address',
134
- 'p', 'li', 'ul', 'ol', 'blockquote', 'pre', 'figure', 'figcaption', 'dl', 'dt', 'dd',
135
- 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'hr'])
136
- let pending = ''
137
- let kind = 'paragraph'
138
- const flush = () => {
139
- const text = pending.replace(/\u00a0/gu, ' ').trim()
140
- if (text) blocks.push({ kind, text })
141
- pending = ''
142
- }
143
- const walk = node => {
144
- if (node.nodeType === 3 || node.nodeType === 4) { pending += node.nodeValue || ''; return }
145
- if (node.nodeType !== 1 || hidden(node)) return
146
- const tag = String(node.localName ?? node.nodeName).toLowerCase()
147
- if (tag === 'br') { pending += '\n'; return }
148
- const heading = /^h[1-6]$/u.test(tag)
149
- const block = heading || blockTags.has(tag)
150
- const previousKind = kind
151
- if (block) { flush(); kind = heading ? 'heading' : 'paragraph' }
152
- for (const child of Array.from(node.childNodes ?? [])) walk(child)
153
- if (block) { flush(); kind = previousKind }
154
- }
155
- walk(root)
156
- flush()
157
- return blocks
158
- }
159
-
160
- function tocLabels(items, base, labels = new Map()) {
161
- for (const item of items) {
162
- if (item.href && item.label) labels.set(archivePath(item.href, base), String(item.label).trim())
163
- tocLabels(item.subitems ?? item.items ?? [], base, labels)
164
- }
165
- return labels
166
- }
@@ -1,28 +0,0 @@
1
- // 小说只作为纯文本呈现,不交给 Markdown / 数学 / 自动链接解析器。
2
- export const NOVEL_STYLE = {
3
- fontSize: 'var(--dsh-content-font-size-secondary, 13px)',
4
- lineHeight: 'var(--dsh-content-line-height-secondary, 1.6)',
5
- color: 'var(--dsw-alias-label-tertiary)',
6
- whiteSpace: 'pre-wrap', overflowWrap: 'anywhere',
7
- }
8
- // 只约束新增的小说正文,不裁剪原生思考/工具输出。窄屏与旧书的长段落
9
- // 仍保留全部文字,可滚动/键盘阅读,避免把宿主折叠控件推得过远。
10
- export const PASSAGE_STYLE = {
11
- maxHeight: 'min(40vh, 20.8em)',
12
- overflowY: 'auto',
13
- scrollbarGutter: 'stable',
14
- }
15
- export const SEPARATOR_STYLE = {
16
- border: 0, borderTop: '1px solid var(--dsw-alias-border-l2)', margin: '10px 0 8px',
17
- }
18
-
19
- export function novelContent(status, hasBook, t) {
20
- if (status.kind === 'ready') return {
21
- label: t('chat.novel'), chapter: status.passage.chapterTitle || '',
22
- text: status.passage.text, index: status.index + 1,
23
- projectGutenberg: status.projectGutenberg === true,
24
- }
25
- const message = status.kind === 'loading' ? 'chat.loading' : status.kind === 'end' ? 'chat.end'
26
- : status.kind === 'error' ? 'chat.readError' : hasBook ? 'chat.switchHint' : 'chat.noBook'
27
- return { label: t('chat.novel'), chapter: '', text: t(message), role: status.kind === 'error' ? 'alert' : 'status' }
28
- }
@@ -1,271 +0,0 @@
1
- const DATABASE_NAME = 'dsh-touch-fish-novel'
2
- const DATABASE_VERSION = 1
3
- const SETTINGS_KEY = 'settings'
4
- const BUNDLED_BOOKS_KEY = 'bundled-books-v1'
5
- const BUNDLED_CATALOG_KEY = 'bundled-catalog-version'
6
-
7
- /** IndexedDB persistence for book metadata, parsed passages, and plugin settings. */
8
- export class IndexedDbStorage {
9
- constructor(indexedDb = globalThis.indexedDB, keyRange = globalThis.IDBKeyRange) {
10
- this.indexedDb = indexedDb
11
- this.keyRange = keyRange
12
- this.database = undefined
13
- }
14
-
15
- close() {
16
- this.database?.close()
17
- this.database = undefined
18
- }
19
-
20
- async load() {
21
- const db = await this.#open()
22
- const tx = db.transaction(['books', 'settings'], 'readonly')
23
- const done = transactionDone(tx)
24
- const stored = await readLibrary(tx)
25
- await done
26
- return stored
27
- }
28
-
29
- /** Seed ordinary, deletable books exactly once, including across concurrent tabs. */
30
- async initializeBundledBooks(entries, catalogVersion) {
31
- if (catalogVersion !== undefined && (!Number.isSafeInteger(catalogVersion) || catalogVersion < 1)) throw new Error('内置书目版本无效')
32
- if (!Array.isArray(entries) || !entries.length) throw new Error('内置书籍列表不能为空')
33
- const ids = new Set()
34
- for (const { book, segments } of entries) {
35
- if (!book?.id || !book.bundledId || !Array.isArray(segments) || !segments.length
36
- || book.segmentCount !== segments.length || ids.has(book.id)) {
37
- throw new Error('内置书籍数据无效或重复')
38
- }
39
- ids.add(book.id)
40
- }
41
- const db = await this.#open()
42
- const tx = db.transaction(['books', 'segments', 'settings'], 'readwrite')
43
- const done = transactionDone(tx)
44
- // A synchronous put failure must still consume the subsequent abort rejection.
45
- done.catch(() => undefined)
46
- try {
47
- const stored = await readLibrary(tx)
48
- if (!stored.bundledBooksInitialized) {
49
- const bookStore = tx.objectStore('books')
50
- const segmentStore = tx.objectStore('segments')
51
- const existingBooks = [...stored.books]
52
- let firstBookId
53
- for (const { book, segments } of entries) {
54
- let matchingBook
55
- for (const candidate of existingBooks) {
56
- // EPUB metadata titles can differ from the concise bundled menu title.
57
- if (candidate.format !== book.format || candidate.segmentCount !== segments.length) continue
58
- const existingSegments = await requestResult(segmentStore.index('bookId').getAll(this.keyRange.only(candidate.id)))
59
- const byIndex = new Map(existingSegments.map(segment => [segment.index, segment]))
60
- if (existingSegments.length === segments.length && segments.every((segment, index) => sameSegment(byIndex.get(index), segment))) {
61
- matchingBook = candidate
62
- break
63
- }
64
- }
65
- if (matchingBook) {
66
- firstBookId ??= matchingBook.id
67
- continue // Legacy imports keep their original IDs, metadata and progress.
68
- }
69
- if (existingBooks.some(candidate => candidate.id === book.id)) throw new Error('内置书籍 ID 与已有书籍冲突')
70
- bookStore.add(book)
71
- segments.forEach((segment, index) => segmentStore.add({
72
- ...segment, id: `${book.id}:${index}`, bookId: book.id, index,
73
- }))
74
- existingBooks.push(book)
75
- firstBookId ??= book.id
76
- }
77
- // Do not replace an existing user's intentional empty selection or settings.
78
- if (!stored.books.length && !stored.settings?.currentBookId) {
79
- tx.objectStore('settings').put({ key: SETTINGS_KEY, value: { ...stored.settings, currentBookId: firstBookId } })
80
- }
81
- tx.objectStore('settings').put({ key: BUNDLED_BOOKS_KEY, value: true })
82
- if (catalogVersion !== undefined) tx.objectStore('settings').put({ key: BUNDLED_CATALOG_KEY, value: catalogVersion })
83
- }
84
- // Read inside this transaction: a losing initializer sees the winner's state.
85
- const latest = await readLibrary(tx)
86
- await done
87
- return latest
88
- } catch (error) {
89
- try { tx.abort() } catch { /* The transaction may already have aborted. */ }
90
- await done.catch(() => undefined)
91
- throw error
92
- }
93
- }
94
-
95
- /** Upgrade only identifiable defaults; metadata, deletion and marker commit together. */
96
- async migrateBundledCatalog({ version, removedIds = [], updates = [] }) {
97
- if (!Number.isSafeInteger(version) || version < 1 || !Array.isArray(removedIds)
98
- || removedIds.some(id => typeof id !== 'string' || !id) || !Array.isArray(updates)
99
- || updates.some(update => !update?.id || !['txt', 'md'].includes(update.fromFormat)
100
- || !['txt', 'md'].includes(update.format) || !Array.isArray(update.segments) || !update.segments.length)) {
101
- throw new Error('内置书目迁移数据无效')
102
- }
103
- const db = await this.#open()
104
- const tx = db.transaction(['books', 'segments', 'settings'], 'readwrite')
105
- const done = transactionDone(tx)
106
- done.catch(() => undefined)
107
- try {
108
- const stored = await readLibrary(tx)
109
- if (stored.bundledBooksInitialized && (stored.bundledCatalogVersion ?? 0) < version) {
110
- const books = tx.objectStore('books')
111
- const segments = tx.objectStore('segments')
112
- const removedBookIds = new Set()
113
- const owned = (book, id) => book.bundledId === id || book.id === `bundled:${id}`
114
- for (const book of stored.books) {
115
- if (removedIds.some(id => owned(book, id))) {
116
- books.delete(book.id)
117
- const keys = await requestResult(segments.index('bookId').getAllKeys(this.keyRange.only(book.id)))
118
- keys.forEach(key => segments.delete(key))
119
- removedBookIds.add(book.id)
120
- continue
121
- }
122
- const update = updates.find(update => owned(book, update.id) && book.format === update.fromFormat)
123
- if (!update || book.segmentCount !== update.segments.length) continue
124
- const existing = await requestResult(segments.index('bookId').getAll(this.keyRange.only(book.id)))
125
- const byIndex = new Map(existing.map(segment => [segment.index, segment]))
126
- if (existing.length === update.segments.length && update.segments.every((segment, index) => sameSegment(byIndex.get(index), segment))) {
127
- // Keep every passage, ID, title, import time and progress byte-for-byte;
128
- // only the file-format label changes after exact canonical comparison.
129
- books.put({ ...book, format: update.format })
130
- }
131
- }
132
- if (removedBookIds.has(stored.settings?.currentBookId)) {
133
- const currentBookId = stored.books.find(book => !removedBookIds.has(book.id))?.id ?? null
134
- tx.objectStore('settings').put({ key: SETTINGS_KEY, value: { ...stored.settings, currentBookId } })
135
- }
136
- // Even a deliberately empty library advances without reseeding anything.
137
- tx.objectStore('settings').put({ key: BUNDLED_CATALOG_KEY, value: version })
138
- }
139
- const latest = await readLibrary(tx)
140
- await done
141
- return latest
142
- } catch (error) {
143
- try { tx.abort() } catch { /* The transaction may already have aborted. */ }
144
- await done.catch(() => undefined)
145
- throw error
146
- }
147
- }
148
-
149
- async saveSettings(value) {
150
- const db = await this.#open()
151
- const tx = db.transaction('settings', 'readwrite')
152
- const done = transactionDone(tx)
153
- tx.objectStore('settings').put({ key: SETTINGS_KEY, value })
154
- await done
155
- }
156
-
157
- async addBook(book, segments) {
158
- const db = await this.#open()
159
- const tx = db.transaction(['books', 'segments'], 'readwrite')
160
- const done = transactionDone(tx)
161
- tx.objectStore('books').put(book)
162
- const segmentStore = tx.objectStore('segments')
163
- segments.forEach((segment, index) => segmentStore.put({
164
- id: `${book.id}:${index}`,
165
- bookId: book.id,
166
- index,
167
- ...segment,
168
- }))
169
- await done
170
- }
171
-
172
- async updateBook(book) {
173
- const db = await this.#open()
174
- const tx = db.transaction('books', 'readwrite')
175
- const done = transactionDone(tx)
176
- const books = tx.objectStore('books')
177
- const existing = await requestResult(books.get(book.id))
178
- if (!existing) {
179
- await done
180
- throw new Error('找不到这本书,无法保存阅读进度')
181
- }
182
- books.put(book)
183
- await done
184
- }
185
-
186
- async getSegment(bookId, index) {
187
- const db = await this.#open()
188
- const tx = db.transaction('segments', 'readonly')
189
- const done = transactionDone(tx)
190
- const result = await requestResult(tx.objectStore('segments').get(`${bookId}:${index}`))
191
- await done
192
- if (!result) return null
193
- const { id: _id, bookId: _bookId, index: _index, ...segment } = result
194
- return segment
195
- }
196
-
197
- async deleteBook(bookId) {
198
- const db = await this.#open()
199
- const tx = db.transaction(['books', 'segments'], 'readwrite')
200
- const done = transactionDone(tx)
201
- tx.objectStore('books').delete(bookId)
202
- const cursorRequest = tx.objectStore('segments').index('bookId').openCursor(this.keyRange.only(bookId))
203
- cursorRequest.onsuccess = () => {
204
- const cursor = cursorRequest.result
205
- if (!cursor) return
206
- cursor.delete()
207
- cursor.continue()
208
- }
209
- await done
210
- }
211
-
212
- async #open() {
213
- if (this.database) return this.database
214
- if (!this.indexedDb) throw new Error('当前浏览器不支持 IndexedDB')
215
- this.database = await new Promise((resolve, reject) => {
216
- const request = this.indexedDb.open(DATABASE_NAME, DATABASE_VERSION)
217
- request.onupgradeneeded = () => {
218
- const db = request.result
219
- if (!db.objectStoreNames.contains('books')) db.createObjectStore('books', { keyPath: 'id' })
220
- if (!db.objectStoreNames.contains('segments')) {
221
- const store = db.createObjectStore('segments', { keyPath: 'id' })
222
- store.createIndex('bookId', 'bookId', { unique: false })
223
- }
224
- if (!db.objectStoreNames.contains('settings')) db.createObjectStore('settings', { keyPath: 'key' })
225
- }
226
- request.onsuccess = () => resolve(request.result)
227
- request.onerror = () => reject(request.error ?? new Error('无法打开本地书库'))
228
- request.onblocked = () => reject(new Error('本地书库正在被其他页面占用,请关闭重复页面后重试'))
229
- })
230
- this.database.onversionchange = () => {
231
- this.database?.close()
232
- this.database = undefined
233
- }
234
- return this.database
235
- }
236
- }
237
-
238
- async function readLibrary(tx) {
239
- const [books, settings, marker, catalog] = await Promise.all([
240
- requestResult(tx.objectStore('books').getAll()),
241
- requestResult(tx.objectStore('settings').get(SETTINGS_KEY)),
242
- requestResult(tx.objectStore('settings').get(BUNDLED_BOOKS_KEY)),
243
- requestResult(tx.objectStore('settings').get(BUNDLED_CATALOG_KEY)),
244
- ])
245
- return { books, settings: settings?.value,
246
- ...(marker?.value === true ? { bundledBooksInitialized: true } : {}),
247
- ...(Number.isSafeInteger(catalog?.value) && catalog.value > 0 ? { bundledCatalogVersion: catalog.value } : {}),
248
- }
249
- }
250
-
251
- function sameSegment(stored, parsed) {
252
- if (!stored) return false
253
- const { id: _id, bookId: _bookId, index: _index, ...content } = stored
254
- const keys = Object.keys(parsed)
255
- return Object.keys(content).length === keys.length && keys.every(key => content[key] === parsed[key])
256
- }
257
-
258
- function requestResult(request) {
259
- return new Promise((resolve, reject) => {
260
- request.onsuccess = () => resolve(request.result)
261
- request.onerror = () => reject(request.error ?? new Error('本地书库读写失败'))
262
- })
263
- }
264
-
265
- function transactionDone(transaction) {
266
- return new Promise((resolve, reject) => {
267
- transaction.oncomplete = () => resolve()
268
- transaction.onerror = () => reject(transaction.error ?? new Error('本地书库事务失败'))
269
- transaction.onabort = () => reject(transaction.error ?? new Error('本地书库事务已取消'))
270
- })
271
- }
package/src/pg-notice.js DELETED
@@ -1,19 +0,0 @@
1
- // Project Gutenberg License §1.E.1, with only the source's line wrapping removed.
2
- export const PG_NOTICE = 'This eBook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg™ License included with this eBook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook.'
3
-
4
- // Separate from PASSAGE_STYLE: the notice must never be hidden inside the novel's
5
- // scroll viewport or a collapsed details element. Both renderers share this style.
6
- export const PG_NOTICE_STYLE = {
7
- margin: '8px 0', padding: '10px 12px',
8
- border: '1px solid var(--dsw-alias-border-l2)', borderRadius: '8px',
9
- fontSize: 'var(--dsh-content-font-size-secondary, 13px)', lineHeight: '1.6',
10
- color: 'var(--dsw-alias-label-primary, inherit)',
11
- whiteSpace: 'normal', overflowWrap: 'anywhere',
12
- }
13
-
14
- export const PG_LICENSE_LABEL = 'Full Project Gutenberg™ License (offline download)'
15
- export const PG_LICENSE_DOWNLOAD = 'project-gutenberg-full-license.txt'
16
-
17
- export function hasProjectGutenbergReference(text) {
18
- return /\bProject\s+Gutenberg\b/iu.test(String(text ?? ''))
19
- }
package/src/segments.js DELETED
@@ -1,185 +0,0 @@
1
- // Half-width display units, not a character/word count: Latin ≈ 1, CJK/emoji ≈ 2.
2
- // At 13px in a 320–600px text column, 800 units occupy roughly 9–17 lines.
3
- export const DEFAULT_SEGMENT_LENGTH = 800
4
-
5
- const TXT_CHAPTER = /^\s*(?:第[0-90-9零〇一二三四五六七八九十百千万两壹贰叁肆伍陆柒捌玖拾佰仟]{1,24}[章节卷篇回部](?:[\t \u3000]+[^。!?!?,,;;\r\n]{1,80})?|chapter\s+(?:\d+|[ivxlcdm]+)(?:[\t ]+[^.!?\r\n]{1,80})?|(?:序章|楔子|前言|尾声|后记|附录)(?:[\t \u3000]+[^。!?!?,,;;\r\n]{1,80})?)\s*$/iu
6
- const MD_HEADING = /^\s{0,3}(#{1,6})\s+(.+?)\s*#*\s*$/u
7
- const WIDE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Extended_Pictographic}\u3000-\u303f\uff01-\uff60\uffe0-\uffe6]/u
8
- const CLOSING = /^[”’"'」』】))\]]+$/u
9
-
10
- /** Split plain text into chapter groups while retaining paragraph breaks. */
11
- export function textToChapters(text, format = 'txt') {
12
- const lines = String(text).replace(/^\uFEFF/u, '').replace(/\r\n?/gu, '\n').split('\n')
13
- const chapters = []
14
- let title = '正文'
15
- let body = []
16
- let sawHeading = false
17
-
18
- const flush = () => {
19
- const content = body.join('\n').trim()
20
- if (content) chapters.push({ title, text: content })
21
- body = []
22
- }
23
-
24
- for (const line of lines) {
25
- const heading = format === 'md' ? line.match(MD_HEADING) : line.match(TXT_CHAPTER)
26
- if (!heading) {
27
- body.push(line)
28
- continue
29
- }
30
- flush()
31
- title = format === 'md' ? heading[2].trim() : line.trim()
32
- sawHeading = true
33
- }
34
- flush()
35
- if (!chapters.length && !sawHeading) {
36
- const content = lines.join('\n').trim()
37
- if (content) chapters.push({ title: '正文', text: content })
38
- }
39
- return chapters
40
- }
41
-
42
- /**
43
- * Segment new imports only; stored passages/progress are not read or rewritten.
44
- * targetLength is a positive-integer soft display-width budget (half-width units).
45
- * Paragraph/sentence boundaries may extend it to floor(targetLength * 1.25).
46
- * Newlines cost 40 units (a conservative wrap/blank-line allowance). A single
47
- * indivisible grapheme may exceed the hard budget rather than being corrupted.
48
- */
49
- export function segmentChapters(chapters, targetLength = DEFAULT_SEGMENT_LENGTH) {
50
- const target = positiveInteger(targetLength)
51
- const segments = []
52
- chapters.forEach((chapter, chapterIndex) => {
53
- for (const text of splitChapter(chapter.text, target)) {
54
- segments.push({ text, chapterTitle: chapter.title, chapterIndex })
55
- }
56
- })
57
- return segments
58
- }
59
-
60
- /** Normalize a parsed text file into titled reading passages. */
61
- export function parseTextBook(text, format = 'txt', targetLength = DEFAULT_SEGMENT_LENGTH) {
62
- const chapters = textToChapters(text, format)
63
- const segments = segmentChapters(chapters, targetLength)
64
- if (!segments.length) throw new Error('文件里没有可阅读的正文文本')
65
- return { chapters, segments }
66
- }
67
-
68
- function splitChapter(text, target) {
69
- const source = String(text).replace(/\r\n?/gu, '\n').split(/\n\s*\n+/u)
70
- .map(value => value.trim()).filter(Boolean).join('\n\n')
71
- if (!source) return []
72
- const parts = graphemes(source)
73
- const widths = [0]
74
- const offsets = [0]
75
- for (const part of parts) {
76
- widths.push(widths.at(-1) + displayWidth(part))
77
- offsets.push(offsets.at(-1) + part.length)
78
- }
79
- const sentenceEnds = new Set()
80
- if (typeof Intl.Segmenter === 'function') {
81
- for (const item of new Intl.Segmenter(undefined, { granularity: 'sentence' }).segment(source)) {
82
- sentenceEnds.add(item.index + item.segment.length)
83
- }
84
- }
85
- const hard = Math.max(1, Math.floor(target * 1.25))
86
- // A word that fits in one passage stays intact even if that requires a short
87
- // predecessor. Only genuinely overlong tokens are eligible for forced cuts.
88
- const insideWord = new Set()
89
- for (let index = 0; index < parts.length;) {
90
- if (/^\s+$/u.test(parts[index]) || WIDE.test(parts[index])) { index += 1; continue }
91
- const begin = index
92
- while (index < parts.length && !/^\s+$/u.test(parts[index]) && !WIDE.test(parts[index])) index += 1
93
- if (widths[index] - widths[begin] <= hard) {
94
- for (let end = begin + 1; end < index; end += 1) insideWord.add(end)
95
- }
96
- }
97
- const segments = []
98
- let start = 0
99
- while (start < parts.length) {
100
- // Boundary whitespace has no meaning outside a passage, and must not create
101
- // an empty fragment (even for targetLength=1 or punctuation-free input).
102
- while (start < parts.length && /^\s+$/u.test(parts[start])) start += 1
103
- if (start === parts.length) break
104
- const remaining = widths.at(-1) - widths[start]
105
- if (remaining <= hard) {
106
- segments.push(source.slice(offsets[start]).trim())
107
- break
108
- }
109
- // Plan balanced passages rather than greedily producing a 20-character tail.
110
- const count = Math.max(2, Math.round(remaining / target), Math.ceil(remaining / hard))
111
- const ideal = remaining / count
112
- const minimum = Math.min(target * 0.55, ideal * 0.7)
113
- let best = start + 1
114
- let bestScore = Infinity
115
- for (let end = start + 1; end <= parts.length; end += 1) {
116
- const width = widths[end] - widths[start]
117
- if (width > hard && end > start + 1) break
118
- if (insideWord.has(end)) continue
119
- // Discourage short tails, but preserve a fitting word even when no fully
120
- // balanced cut exists. Chapters and indivisible tokens are never merged.
121
- const tail = widths.at(-1) - widths[end]
122
- const priority = boundaryPriority(parts, end, sentenceEnds.has(offsets[end]))
123
- const shortPenalty = (width < minimum ? target : 0) + (tail < minimum ? target : 0)
124
- const score = Math.abs(width - ideal) + priority * target + shortPenalty
125
- if (score < bestScore) {
126
- bestScore = score
127
- best = end
128
- }
129
- }
130
- const passage = source.slice(offsets[start], offsets[best]).trim()
131
- if (passage) segments.push(passage)
132
- start = best
133
- }
134
- return segments
135
- }
136
-
137
- function boundaryPriority(parts, end, sentenceEnd) {
138
- const previous = parts[end - 1]
139
- const next = parts[end] ?? ''
140
- if (previous === '\n' && parts[end - 2] === '\n') return 0
141
- if (previous === '\n') return 0.08
142
- // Neither leave an opening quote behind nor strand a closing quote/punctuation.
143
- if (/^[“‘「『【((\[]+$/u.test(previous)
144
- || (/^["']$/u.test(previous) && /^\s$/u.test(parts[end - 2] ?? ''))
145
- || CLOSING.test(next) || /^[。!?!?,,;;::]/u.test(next)) return 2
146
- if (sentenceEnd) return 0.10
147
- let index = end - 1
148
- while (index >= 0 && (/^\s+$/u.test(parts[index]) || CLOSING.test(parts[index]))) index -= 1
149
- if (/[。!?!?…]$/u.test(parts[index] ?? '')
150
- || (typeof Intl.Segmenter !== 'function' && /\.$/u.test(parts[index] ?? ''))) return 0.10
151
- if (/[,,;;::]$/u.test(parts[index] ?? '')) return 0.22
152
- if (/^\s+$/u.test(previous) || /^\s+$/u.test(next)) return 0.30
153
- // A Latin word may exceed the budget; only then fall back to a grapheme cut.
154
- return WIDE.test(previous) || WIDE.test(next) ? 0.48 : 2
155
- }
156
-
157
- function displayWidth(part) {
158
- if (part === '\n') return 40
159
- if (part === '\t') return 4
160
- return WIDE.test(part) || /\p{Regional_Indicator}/u.test(part) ? 2 : 1
161
- }
162
-
163
- function graphemes(text) {
164
- if (typeof Intl.Segmenter === 'function') {
165
- return Array.from(new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text), item => item.segment)
166
- }
167
- // Conservative fallback for older hosts: keep marks, variation selectors,
168
- // emoji modifiers, ZWJ sequences and regional-indicator flag pairs together.
169
- const parts = []
170
- let regionalCount = 0
171
- for (const point of text) {
172
- const regional = /\p{Regional_Indicator}/u.test(point)
173
- if (parts.length && (/^[\p{Mark}\p{Emoji_Modifier}\u200d\ufe0e\ufe0f]$/u.test(point)
174
- || parts.at(-1).endsWith('\u200d') || (regional && regionalCount % 2 === 1))) {
175
- parts[parts.length - 1] += point
176
- } else parts.push(point)
177
- regionalCount = regional ? regionalCount + 1 : 0
178
- }
179
- return parts
180
- }
181
-
182
- function positiveInteger(value) {
183
- if (!Number.isSafeInteger(value) || value < 1) throw new RangeError('分段长度必须是正整数')
184
- return value
185
- }