@gongfpp/dsh-novel-fish 1.0.1 → 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 (91) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +65 -22
  3. package/docs/evidence/reading-demo-110.png +0 -0
  4. package/docs/evidence/settings-reliability.png +0 -0
  5. package/index.json +24 -0
  6. package/lib/client.js +1225 -191
  7. package/locale/en.json +21 -0
  8. package/locale/zh.json +21 -0
  9. package/package.json +6 -7
  10. package/samples/ebooks/LICENSE.md +355 -0
  11. package/samples/ebooks/NOTICE.md +33 -0
  12. package/samples/ebooks/aq-zheng-zhuan-wikisource.md +998 -0
  13. package/samples/ebooks/million-pound-bank-note-pg61522.txt +6970 -0
  14. package/samples/ebooks/sources.json +58 -0
  15. package/screenshots.json +6 -0
  16. package/docs/acceptance.md +0 -42
  17. package/docs/community-markets.md +0 -71
  18. package/docs/compatibility-017.md +0 -70
  19. package/docs/compatibility-101.md +0 -41
  20. package/docs/continuous-reading-020.md +0 -46
  21. package/docs/evidence/abc-result.json +0 -9
  22. package/docs/evidence/banner-100.png +0 -0
  23. package/docs/evidence/community-market-014-result.json +0 -170
  24. package/docs/evidence/compatibility-017-result.json +0 -65
  25. package/docs/evidence/continuous-reading-020-result.json +0 -72
  26. package/docs/evidence/formats-result.json +0 -12
  27. package/docs/evidence/live-ab.png +0 -0
  28. package/docs/evidence/live-collapsed.png +0 -0
  29. package/docs/evidence/live-disabled.png +0 -0
  30. package/docs/evidence/live-epub.png +0 -0
  31. package/docs/evidence/live-market.png +0 -0
  32. package/docs/evidence/live-resume.png +0 -0
  33. package/docs/evidence/live-unloaded.png +0 -0
  34. package/docs/evidence/long-result.json +0 -11
  35. package/docs/evidence/multi-region-014-result.json +0 -47
  36. package/docs/evidence/native-disclosure-013-result.json +0 -36
  37. package/docs/evidence/native-disclosures-013.png +0 -0
  38. package/docs/evidence/native-open-013.png +0 -0
  39. package/docs/evidence/native-settings-sample.md +0 -11
  40. package/docs/evidence/native-settings-types-015.png +0 -0
  41. package/docs/evidence/npm-market-014-result.json +0 -132
  42. package/docs/evidence/plugin-settings-details.png +0 -0
  43. package/docs/evidence/public-release-014-result.json +0 -51
  44. package/docs/evidence/public-release-015-result.json +0 -36
  45. package/docs/evidence/public-release-result.json +0 -48
  46. package/docs/evidence/reading-demo-100.png +0 -0
  47. package/docs/evidence/settings-011-result.json +0 -28
  48. package/docs/evidence/settings-011.png +0 -0
  49. package/docs/evidence/settings-100.png +0 -0
  50. package/docs/evidence/settings-chat-011.png +0 -0
  51. package/docs/evidence/type-append-012-result.json +0 -30
  52. package/docs/evidence/type-append-012.png +0 -0
  53. package/docs/evidence/type-settings-012.png +0 -0
  54. package/docs/evidence/unload-result.json +0 -7
  55. package/docs/host-adapter.md +0 -43
  56. package/docs/icon-metadata-021.md +0 -40
  57. package/docs/interaction-paths-020.md +0 -39
  58. package/docs/marketplace.md +0 -42
  59. package/docs/multi-region-update.md +0 -53
  60. package/docs/native-disclosure-update.md +0 -39
  61. package/docs/native-settings-update.md +0 -48
  62. package/docs/plugin-settings-update.md +0 -61
  63. package/docs/release.md +0 -139
  64. package/docs/settings-update.md +0 -49
  65. package/docs/type-append-update.md +0 -50
  66. package/pnpm-workspace.yaml +0 -5
  67. package/scripts/build.mjs +0 -69
  68. package/scripts/check-host-contracts.mjs +0 -246
  69. package/scripts/licenses/path-webpack.txt +0 -28
  70. package/src/chat-adapter.js +0 -253
  71. package/src/client.js +0 -55
  72. package/src/epub.js +0 -166
  73. package/src/novel-content.js +0 -20
  74. package/src/persistence.js +0 -130
  75. package/src/segments.js +0 -135
  76. package/src/settings.js +0 -219
  77. package/src/store.js +0 -371
  78. package/src/text-decoding.js +0 -28
  79. package/test/chat-adapter.test.js +0 -433
  80. package/test/client.test.js +0 -82
  81. package/test/epub.test.js +0 -185
  82. package/test/helpers/host-primitives.js +0 -28
  83. package/test/helpers/memory-storage.js +0 -48
  84. package/test/host-contracts.test.js +0 -32
  85. package/test/import.test.js +0 -102
  86. package/test/persistence.test.js +0 -27
  87. package/test/release.test.js +0 -85
  88. package/test/segments.test.js +0 -48
  89. package/test/settings.test.js +0 -271
  90. package/test/store.test.js +0 -617
  91. package/test/text-decoding.test.js +0 -49
package/src/store.js DELETED
@@ -1,371 +0,0 @@
1
- import { parseEpub } from './epub.js'
2
- import { DEFAULT_SEGMENT_LENGTH, parseTextBook } from './segments.js'
3
- import { decodeBookText } from './text-decoding.js'
4
-
5
- export const TARGET_TYPES = Object.freeze(['reasoning', 'tool-call', 'read-file', 'command', 'file-search'])
6
-
7
- export const DEFAULT_SETTINGS = Object.freeze({
8
- enabled: true,
9
- currentBookId: null,
10
- targetTypes: Object.freeze(['reasoning']),
11
- mainTitle: '',
12
- extraTitle: '',
13
- continueOnReopen: false,
14
- })
15
-
16
- const EMPTY_STATUS = Object.freeze({ kind: 'empty' })
17
-
18
- export function passageSnapshotKey(bookId, stepKey) {
19
- return `${bookId}\u0000${stepKey}`
20
- }
21
-
22
- /** Own persistent books/settings and page-only passage cache for Novel Fish. */
23
- export class NovelStore {
24
- constructor(storage) {
25
- this.storage = storage
26
- this.state = { books: [], settings: { ...DEFAULT_SETTINGS }, hydrated: false, error: null }
27
- this.ui = { notice: null }
28
- this.listeners = new Set()
29
- this.settingsListeners = new Set()
30
- this.uiListeners = new Set()
31
- this.passageListeners = new Set()
32
- this.passageStates = new Map()
33
- this.passageSnapshot = Object.freeze({})
34
- this.stateSource = Object.freeze({ getSnapshot: this.getSnapshot, subscribe: this.subscribe })
35
- this.settingsSource = Object.freeze({ getSnapshot: this.getSettingsSnapshot, subscribe: this.subscribeSettings })
36
- this.uiSource = Object.freeze({ getSnapshot: this.getUiSnapshot, subscribe: this.subscribeUi })
37
- this.passageSource = Object.freeze({ getSnapshot: this.getPassageSnapshot, subscribe: this.subscribePassages })
38
- this.pendingReads = new Map()
39
- this.cacheGeneration = 0
40
- this.disposed = false
41
- this.persistenceError = null
42
- this.mutationQueue = Promise.resolve()
43
- this.ready = this.#hydrate()
44
- }
45
-
46
- getSnapshot = () => this.state
47
- getSettingsSnapshot = () => this.state.settings
48
- getUiSnapshot = () => this.ui
49
- getPassageSnapshot = () => this.passageSnapshot
50
-
51
- subscribe = listener => this.#subscribe(this.listeners, listener)
52
- subscribeSettings = listener => this.#subscribe(this.settingsListeners, listener)
53
- subscribeUi = listener => this.#subscribe(this.uiListeners, listener)
54
- subscribePassages = listener => this.#subscribe(this.passageListeners, listener)
55
-
56
- getPassageStatus(bookId, stepKey) {
57
- if (!bookId) return EMPTY_STATUS
58
- return this.passageStates.get(passageSnapshotKey(bookId, stepKey)) ?? EMPTY_STATUS
59
- }
60
-
61
- dispose() {
62
- this.disposed = true
63
- this.cacheGeneration += 1
64
- this.passageStates.clear()
65
- this.passageSnapshot = Object.freeze({})
66
- this.pendingReads.clear()
67
- this.listeners.clear()
68
- this.settingsListeners.clear()
69
- this.uiListeners.clear()
70
- this.passageListeners.clear()
71
- this.storage.close?.()
72
- }
73
-
74
- setNotice(notice) {
75
- this.ui = { ...this.ui, notice: notice ? String(notice) : null }
76
- this.#emitUi()
77
- }
78
-
79
- async setOption(key, value) {
80
- if (!['enabled', 'targetTypes', 'mainTitle', 'extraTitle', 'continueOnReopen'].includes(key)) throw new Error('未知设置项')
81
- let normalized
82
- if (key === 'targetTypes') {
83
- if (!Array.isArray(value) || value.some(type => !TARGET_TYPES.includes(type)) || new Set(value).size !== value.length) {
84
- throw new Error('阅读类型必须是有效且不重复的类型数组')
85
- }
86
- normalized = Object.freeze([...value])
87
- } else if (key === 'enabled' || key === 'continueOnReopen') {
88
- normalized = Boolean(value)
89
- } else {
90
- normalized = String(value)
91
- }
92
- // Invalidate at intent time, not after a queued settings write finishes.
93
- // Any type update also covers removals from settings writes still in flight.
94
- if ((key === 'enabled' && !normalized) || key === 'targetTypes') this.#cancelPendingReads()
95
- return this.#updateSettings(() => ({ [key]: normalized }))
96
- }
97
-
98
- async selectBook(bookId) {
99
- const nextId = bookId || null
100
- this.cacheGeneration += 1
101
- return this.#enqueueMutation(async () => {
102
- if (nextId && !this.state.books.some(book => book.id === nextId)) throw new Error('找不到这本书')
103
- if (nextId === this.state.settings.currentBookId) return
104
- await this.#saveSettings({ ...this.state.settings, currentBookId: nextId })
105
- this.#clearPassages(false)
106
- })
107
- }
108
-
109
- async importFile(file) {
110
- await this.ready
111
- this.#assertWritable()
112
- const extension = String(file.name).split('.').at(-1)?.toLowerCase()
113
- if (!['epub', 'txt', 'md'].includes(extension)) throw new Error('只支持 EPUB、TXT、MD 文件')
114
- const parsed = extension === 'epub'
115
- ? await parseEpub(file, DEFAULT_SEGMENT_LENGTH)
116
- : parseTextBook(decodeBookText(await file.arrayBuffer()), extension, DEFAULT_SEGMENT_LENGTH)
117
- const fallbackTitle = String(file.name).replace(/\.(epub|txt|md)$/iu, '')
118
- return this.#addBook({
119
- title: parsed.title?.trim() || fallbackTitle || '未命名书籍',
120
- format: extension,
121
- segments: parsed.segments,
122
- })
123
- }
124
-
125
- async deleteBook(bookId) {
126
- if (bookId === this.state.settings.currentBookId) this.cacheGeneration += 1
127
- return this.#enqueueMutation(async () => {
128
- if (!this.state.books.some(item => item.id === bookId)) return
129
- const books = this.state.books.filter(item => item.id !== bookId)
130
- const previousSettings = this.state.settings
131
- const settings = {
132
- ...previousSettings,
133
- currentBookId: previousSettings.currentBookId === bookId ? books[0]?.id ?? null : previousSettings.currentBookId,
134
- }
135
- // Save selection first: a failed settings write must not delete the selected book.
136
- await this.storage.saveSettings(settings)
137
- try {
138
- await this.storage.deleteBook(bookId)
139
- } catch (error) {
140
- await this.#restore(() => this.storage.saveSettings(previousSettings))
141
- throw error
142
- }
143
- this.#setState({ books, settings })
144
- if (settings.currentBookId !== previousSettings.currentBookId) this.#clearPassages(false)
145
- })
146
- }
147
-
148
- /** Reopening a region shows the passage it already holds; a first expansion reads the next one. */
149
- async claimPassage(stepKey, targetType = 'reasoning') {
150
- return this.#readPassage(stepKey, targetType, false)
151
- }
152
-
153
- /**
154
- * Same contract as claimPassage, except a region that already shows a passage
155
- * advances to the next one. Only an explicit reopen can reach this path, so a
156
- * repeated expansion still cannot paginate by accident while long reads
157
- * continue inside the same native row.
158
- */
159
- async continuePassage(stepKey, targetType = 'reasoning') {
160
- return this.#readPassage(stepKey, targetType, true)
161
- }
162
-
163
- async #readPassage(stepKey, targetType, advance) {
164
- if (this.disposed) return EMPTY_STATUS
165
- const generation = this.cacheGeneration
166
- const requestKey = `${generation}\u0000${targetType}\u0000${stepKey}`
167
- const inFlight = this.pendingReads.get(requestKey)
168
- if (inFlight) return inFlight
169
-
170
- let bookId
171
- let loadingStatus
172
- const operation = this.#enqueueMutation(async () => {
173
- if (!this.#canRead(generation, targetType)) return EMPTY_STATUS
174
- bookId = this.state.settings.currentBookId
175
- if (!bookId) return EMPTY_STATUS
176
- const existing = this.getPassageStatus(bookId, stepKey)
177
- if (existing.kind === 'end') return existing
178
- if (!advance && existing.kind === 'ready') return existing
179
- const book = this.state.books.find(item => item.id === bookId)
180
- if (!book || book.progress >= book.segmentCount) {
181
- return this.#writePassageStatus(bookId, stepKey, { kind: 'end', bookId })
182
- }
183
-
184
- loadingStatus = { kind: 'loading' }
185
- this.#writePassageStatus(bookId, stepKey, loadingStatus)
186
- const index = book.progress
187
- const passage = await this.storage.getSegment(bookId, index)
188
- if (!passage?.text) throw new Error('当前段落为空或已损坏')
189
- if (!this.#canRead(generation, targetType)) return EMPTY_STATUS
190
-
191
- const updated = { ...book, progress: index + 1 }
192
- await this.storage.updateBook(updated)
193
- if (!this.#canRead(generation, targetType)) {
194
- await this.#restore(() => this.storage.updateBook(book))
195
- return EMPTY_STATUS
196
- }
197
- const result = { kind: 'ready', bookId, index, passage }
198
- this.#setState({ books: this.state.books.map(item => item.id === bookId ? updated : item) })
199
- return this.#writePassageStatus(bookId, stepKey, result)
200
- }).catch(error => {
201
- if (!this.persistenceError && !this.#canRead(generation, targetType)) return EMPTY_STATUS
202
- const failure = { kind: 'error', message: messageOf(error) }
203
- if (this.#canRead(generation, targetType) && bookId) this.#writePassageStatus(bookId, stepKey, failure)
204
- return failure
205
- })
206
-
207
- this.pendingReads.set(requestKey, operation)
208
- try {
209
- return await operation
210
- } finally {
211
- if (this.pendingReads.get(requestKey) === operation) this.pendingReads.delete(requestKey)
212
- if (bookId && loadingStatus && generation !== this.cacheGeneration && this.getPassageStatus(bookId, stepKey) === loadingStatus) {
213
- this.#writePassageStatus(bookId, stepKey, EMPTY_STATUS)
214
- }
215
- }
216
- }
217
-
218
- async #hydrate() {
219
- try {
220
- const stored = await this.storage.load()
221
- const books = stored.books ?? []
222
- const storedSettings = stored.settings ?? {}
223
- const availableIds = new Set(books.map(book => book.id))
224
- const settings = {
225
- ...Object.fromEntries(Object.entries(DEFAULT_SETTINGS).map(([key, fallback]) => [key, storedSettings[key] ?? fallback])),
226
- currentBookId: availableIds.has(storedSettings.currentBookId) ? storedSettings.currentBookId : null,
227
- // Migrate the old reasoning-only field once; never carry it into writes.
228
- targetTypes: Object.freeze(Array.isArray(storedSettings.targetTypes)
229
- ? [...new Set(storedSettings.targetTypes.filter(type => TARGET_TYPES.includes(type)))]
230
- : [...DEFAULT_SETTINGS.targetTypes]),
231
- }
232
- this.#setState({ books, settings, hydrated: true, error: null })
233
- } catch (error) {
234
- this.persistenceError = error
235
- this.#setState({ hydrated: true, error: messageOf(error) })
236
- }
237
- }
238
-
239
- #addBook({ title, format, segments }) {
240
- return this.#enqueueMutation(async () => {
241
- if (!segments.length) throw new Error('没有可导入的正文')
242
- const book = {
243
- id: randomId(),
244
- title: String(title).trim() || '未命名书籍',
245
- format,
246
- segmentCount: segments.length,
247
- progress: 0,
248
- importedAt: Date.now(),
249
- }
250
- await this.storage.addBook(book, segments)
251
- const settings = this.state.settings.currentBookId
252
- ? this.state.settings
253
- : { ...this.state.settings, currentBookId: book.id }
254
- try {
255
- if (settings !== this.state.settings) await this.storage.saveSettings(settings)
256
- } catch (error) {
257
- await this.#restore(() => this.storage.deleteBook(book.id))
258
- throw error
259
- }
260
- if (settings !== this.state.settings) this.#clearPassages()
261
- this.#setState({ books: [...this.state.books, book], settings })
262
- return book
263
- })
264
- }
265
-
266
- #updateSettings(update) {
267
- return this.#enqueueMutation(async () => {
268
- const patch = update(this.state.settings)
269
- if (!patch) return this.state.settings
270
- return this.#saveSettings({ ...this.state.settings, ...patch })
271
- })
272
- }
273
-
274
- async #saveSettings(settings) {
275
- await this.storage.saveSettings(settings)
276
- this.#setState({ settings })
277
- return settings
278
- }
279
-
280
- #enqueueMutation(action) {
281
- const operation = this.mutationQueue.then(async () => {
282
- await this.ready
283
- this.#assertWritable()
284
- return action()
285
- })
286
- this.mutationQueue = operation.catch(() => undefined)
287
- return operation
288
- }
289
-
290
- #assertWritable() {
291
- if (this.persistenceError) throw new Error(`本地书库不可用,请刷新后重试:${messageOf(this.persistenceError)}`)
292
- if (this.disposed) throw new Error('本地书库已关闭')
293
- }
294
-
295
- async #restore(action) {
296
- try {
297
- await action()
298
- } catch (error) {
299
- this.persistenceError = error
300
- this.#setState({ error: `本地书库恢复失败,请刷新后检查阅读进度:${messageOf(error)}` })
301
- throw error
302
- }
303
- }
304
-
305
- #canRead(generation, targetType) {
306
- return !this.disposed && generation === this.cacheGeneration
307
- && this.state.settings.enabled && this.state.settings.targetTypes.includes(targetType)
308
- }
309
-
310
- #cancelPendingReads() {
311
- this.cacheGeneration += 1
312
- this.pendingReads.clear()
313
- let changed = false
314
- for (const [key, status] of this.passageStates) {
315
- if (status.kind === 'loading') {
316
- this.passageStates.delete(key)
317
- changed = true
318
- }
319
- }
320
- if (changed) {
321
- this.passageSnapshot = Object.freeze(Object.fromEntries(this.passageStates))
322
- this.#emitPassages()
323
- }
324
- }
325
-
326
- #clearPassages(cancelReads = true) {
327
- if (cancelReads) this.cacheGeneration += 1
328
- this.passageStates.clear()
329
- this.passageSnapshot = Object.freeze({})
330
- this.#emitPassages()
331
- }
332
-
333
- #writePassageStatus(bookId, stepKey, status) {
334
- if (!bookId) return status
335
- const key = passageSnapshotKey(bookId, stepKey)
336
- this.passageStates.set(key, status)
337
- this.passageSnapshot = Object.freeze({ ...this.passageSnapshot, [key]: status })
338
- this.#emitPassages()
339
- return status
340
- }
341
-
342
- #setState(changes) {
343
- const next = { ...this.state, ...changes }
344
- this.state = next
345
- for (const listener of [...this.listeners]) listener()
346
- if (changes.settings !== undefined) {
347
- for (const listener of [...this.settingsListeners]) listener()
348
- }
349
- }
350
-
351
- #emitPassages() {
352
- for (const listener of [...this.passageListeners]) listener()
353
- }
354
-
355
- #emitUi() {
356
- for (const listener of [...this.uiListeners]) listener()
357
- }
358
-
359
- #subscribe(listeners, listener) {
360
- listeners.add(listener)
361
- return () => listeners.delete(listener)
362
- }
363
- }
364
-
365
- function randomId() {
366
- return globalThis.crypto?.randomUUID?.() ?? `book-${Date.now()}-${Math.random().toString(36).slice(2)}`
367
- }
368
-
369
- function messageOf(error) {
370
- return error instanceof Error ? error.message : String(error)
371
- }
@@ -1,28 +0,0 @@
1
- // 只接受可确定的 Unicode 编码,避免把损坏或传统编码文本静默替换后保存。
2
- export function decodeBookText(input, { xml = false } = {}) {
3
- const bytes = input instanceof Uint8Array ? input : new Uint8Array(input)
4
- let encoding = 'utf-8'
5
- let marked = false
6
- if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) marked = true
7
- else if (bytes[0] === 0xff && bytes[1] === 0xfe) { encoding = 'utf-16le'; marked = true }
8
- else if (bytes[0] === 0xfe && bytes[1] === 0xff) { encoding = 'utf-16be'; marked = true }
9
- else if (xml && bytes[0] === 0x3c && bytes[1] === 0 && bytes[3] === 0) encoding = 'utf-16le'
10
- else if (xml && bytes[0] === 0 && bytes[1] === 0x3c && bytes[2] === 0) encoding = 'utf-16be'
11
-
12
- let text
13
- try {
14
- text = new TextDecoder(encoding, { fatal: true }).decode(bytes)
15
- } catch {
16
- throw new Error('文本编码无效:请使用 UTF-8 或带 BOM 的 UTF-16 文件')
17
- }
18
- if (text.includes('\u0000')) throw new Error('不支持的文本编码:请转换为 UTF-8 或带 BOM 的 UTF-16')
19
- if (xml) {
20
- const declared = /^<\?xml\s[^?]*\bencoding\s*=\s*(['"])([^'"]+)\1/iu.exec(text)?.[2].toLowerCase()
21
- const allowed = { 'utf-8': 'utf-8', utf8: 'utf-8', 'utf-16': 'utf-16', 'utf-16le': 'utf-16le', 'utf-16be': 'utf-16be' }
22
- if (declared && !allowed[declared]) throw new Error(`不支持的 XML 编码:${declared}`)
23
- if (declared && (allowed[declared] === 'utf-16' ? !encoding.startsWith('utf-16') : allowed[declared] !== encoding)) {
24
- throw new Error(`XML 编码声明与${marked ? ' BOM' : '实际字节'}不符:${declared}`)
25
- }
26
- }
27
- return text
28
- }