@gongfpp/dsh-novel-fish 1.0.0 → 1.1.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 (44) hide show
  1. package/README.md +42 -14
  2. package/docs/community-markets.md +18 -1
  3. package/docs/compatibility-101.md +41 -0
  4. package/docs/ebook-tests.md +99 -0
  5. package/docs/evidence/reading-demo-110.png +0 -0
  6. package/docs/evidence/reading-two-expansions-110.gif +0 -0
  7. package/docs/evidence/reading-two-expansions-110.json +89 -0
  8. package/docs/evidence/samples-110-capture.json +49 -0
  9. package/docs/evidence/settings-110.png +0 -0
  10. package/docs/marketplace.md +4 -4
  11. package/docs/release.md +25 -0
  12. package/index.json +24 -0
  13. package/lib/client.js +523 -95
  14. package/locale/en.json +6 -0
  15. package/locale/zh.json +6 -0
  16. package/package.json +10 -9
  17. package/samples/ebooks/LICENSE.md +355 -0
  18. package/samples/ebooks/NOTICE.md +33 -0
  19. package/samples/ebooks/aq-zheng-zhuan-wikisource.md +998 -0
  20. package/samples/ebooks/million-pound-bank-note-pg61522.txt +6970 -0
  21. package/samples/ebooks/sources.json +58 -0
  22. package/scripts/build.mjs +1 -0
  23. package/scripts/check-host-contracts.mjs +3 -2
  24. package/scripts/make-readme-gif.mjs +69 -0
  25. package/scripts/test-browser-samples.mjs +665 -0
  26. package/scripts/test-candidate-books.mjs +71 -0
  27. package/scripts/test-ebook-corpus.mjs +161 -0
  28. package/src/bundled-books.js +42 -0
  29. package/src/chat-adapter.js +34 -9
  30. package/src/client.js +8 -2
  31. package/src/novel-content.js +8 -0
  32. package/src/persistence.js +144 -3
  33. package/src/pg-notice.js +19 -0
  34. package/src/segments.js +115 -65
  35. package/src/settings.js +32 -8
  36. package/src/store.js +61 -3
  37. package/test/bundled-library.test.js +526 -0
  38. package/test/chat-adapter.test.js +87 -2
  39. package/test/client.test.js +49 -7
  40. package/test/ebooks.test.js +192 -0
  41. package/test/pg-notice.test.js +109 -0
  42. package/test/release.test.js +21 -7
  43. package/test/segments.test.js +136 -2
  44. package/test/settings.test.js +42 -1
@@ -0,0 +1,71 @@
1
+ // Optional local-only probe. Restricted candidates are never bundled or downloaded here.
2
+ // Usage: node scripts/test-candidate-books.mjs
3
+ import assert from 'node:assert/strict'
4
+ import { readFile, mkdir, writeFile } from 'node:fs/promises'
5
+ import { createHash } from 'node:crypto'
6
+ import { dirname, resolve } from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { NovelStore } from '../src/store.js'
9
+ import { MemoryStorage } from '../test/helpers/memory-storage.js'
10
+ import { DEFAULT_SEGMENT_LENGTH, parseTextBook } from '../src/segments.js'
11
+
12
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
13
+ const input = resolve(root, 'samples/ebooks-next')
14
+ const manifest = JSON.parse(await readFile(resolve(input, 'sources.json'), 'utf8'))
15
+ const storage = new MemoryStorage()
16
+ const store = new NovelStore(storage)
17
+ const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' })
18
+ function units(text) {
19
+ let total = 0
20
+ for (const { segment } of graphemes.segment(text)) {
21
+ total += segment === '\n' ? 40 : segment === '\t' ? 4
22
+ : /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Extended_Pictographic}\p{Regional_Indicator}\u3000-\u303f\uff01-\uff60\uffe0-\uffe6]/u.test(segment) ? 2 : 1
23
+ }
24
+ return total
25
+ }
26
+ function distribution(values) {
27
+ const sorted = [...values].sort((a, b) => a - b)
28
+ const at = p => sorted[Math.floor((sorted.length - 1) * p)]
29
+ return { min: sorted[0], median: at(0.5), p90: at(0.9), max: sorted.at(-1) }
30
+ }
31
+ const results = []
32
+ try {
33
+ await store.ready
34
+ const original = await store.importFile({ name: 'existing.txt', arrayBuffer: async () => new TextEncoder().encode('保留原来的书与阅读进度。'.repeat(100)).buffer })
35
+ await store.claimPassage('existing-before-candidates')
36
+ const originalProgress = storage.books.get(original.id).progress
37
+ const originalSegments = [...storage.passages.entries()]
38
+ for (const source of manifest.books) {
39
+ assert.equal(source.format, 'txt', 'this probe only covers the two acquired TXT candidates')
40
+ const path = resolve(input, source.file)
41
+ assert.ok(path.startsWith(input + '/'), 'manifest must not escape its candidate directory')
42
+ const bytes = await readFile(path)
43
+ assert.equal(bytes.length, source.bytes)
44
+ assert.equal(createHash('sha256').update(bytes).digest('hex'), source.sha256)
45
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
46
+ const parsed = parseTextBook(text)
47
+ const normalizedBody = parsed.chapters.map(chapter => chapter.text).join('').replace(/\s/gu, '')
48
+ assert.equal(parsed.segments.map(segment => segment.text).join('').replace(/\s/gu, ''), normalizedBody)
49
+ const book = await store.importFile({ name: source.file, arrayBuffer: async () => Uint8Array.from(bytes).buffer })
50
+ const segments = await Promise.all(Array.from({ length: book.segmentCount }, (_, index) => storage.getSegment(book.id, index)))
51
+ assert.deepEqual(segments.map(segment => segment.text), parsed.segments.map(segment => segment.text))
52
+ const widths = segments.map(segment => units(segment.text))
53
+ assert.ok(widths.every(width => width <= Math.floor(DEFAULT_SEGMENT_LENGTH * 1.25)))
54
+ assert.ok(segments.every(segment => !segment.text.includes('\uFFFD')))
55
+ assert.equal(store.getSettingsSnapshot().currentBookId, original.id)
56
+ assert.equal(storage.books.get(original.id).progress, originalProgress)
57
+ for (const [key, segment] of originalSegments) assert.deepEqual(storage.passages.get(key), segment)
58
+ results.push({ file: source.file, bytes: bytes.length, sha256: source.sha256,
59
+ packaged: false, packageByDefault: source.redistribution?.packageByDefault ?? false, chapters: parsed.chapters.length,
60
+ segments: segments.length, displayUnits: distribution(widths),
61
+ characters: distribution(segments.map(segment => [...segment.text].length)),
62
+ englishWords: distribution(segments.map(segment => (segment.text.match(/\b[A-Za-z]+\b/gu) ?? []).length)),
63
+ below200DisplayUnits: widths.filter(width => width < 200).length,
64
+ preservedBody: true, originalLibraryUnchanged: true })
65
+ }
66
+ const report = { scope: 'local candidate TXT import + MemoryStorage, not GUI, not redistribution clearance',
67
+ softDisplayUnits: DEFAULT_SEGMENT_LENGTH, hardDisplayUnits: Math.floor(DEFAULT_SEGMENT_LENGTH * 1.25), results }
68
+ await mkdir(resolve(root, 'dist/ebooks'), { recursive: true })
69
+ await writeFile(resolve(root, 'dist/ebooks/candidate-results.json'), JSON.stringify(report, null, 2) + '\n')
70
+ console.log(JSON.stringify(report, null, 2))
71
+ } finally { store.dispose() }
@@ -0,0 +1,161 @@
1
+ import assert from 'node:assert/strict'
2
+ import { readFile, writeFile, copyFile, mkdir } from 'node:fs/promises'
3
+ import { createHash } from 'node:crypto'
4
+ import { resolve, dirname } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+ import JSZip from 'jszip'
7
+ import { NovelStore } from '../src/store.js'
8
+ import { MemoryStorage } from '../test/helpers/memory-storage.js'
9
+
10
+ // Explicit local-only extended probe; ordinary tests never read these downloads.
11
+ // Use existing dist/ebooks Alice files, or --copy-from <download-directory>.
12
+ // Generates one clearly labelled test-only EPUB from the complete AQ export;
13
+ // this is NOT a downloaded original EPUB or a new bundled book.
14
+ // This script does not download anything or add support for negative formats.
15
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
16
+ const output = resolve(root, 'dist/ebooks')
17
+ const args = process.argv.slice(2)
18
+ if (args.length && (args.length !== 2 || args[0] !== '--copy-from')) {
19
+ throw new Error('Usage: node scripts/test-ebook-corpus.mjs [--copy-from <download-directory>]')
20
+ }
21
+ const { books } = JSON.parse(await readFile(resolve(root, 'samples/ebooks/sources.json'), 'utf8'))
22
+ assert.deepEqual(books.map(book => book.id), ['million-pound-bank-note', 'aq-zheng-zhuan'])
23
+ const additional = [
24
+ { file: 'alice.html', format: 'html', source: 'https://www.gutenberg.org/ebooks/11', download: 'https://www.gutenberg.org/ebooks/11.html.images' },
25
+ { file: 'alice.azw3', format: 'azw3', source: 'https://www.gutenberg.org/ebooks/11', download: 'https://www.gutenberg.org/ebooks/11.kf8.images' },
26
+ { file: 'alice.mobi', format: 'mobi', source: 'https://www.gutenberg.org/ebooks/11', download: 'https://www.gutenberg.org/ebooks/11.kindle.noimages' },
27
+ { file: 'alice.pdf', format: 'pdf', source: 'https://www.adobe.com/be_en/active-use/pdf/Alice_in_Wonderland.pdf', download: 'https://www.adobe.com/be_en/active-use/pdf/Alice_in_Wonderland.pdf' },
28
+ ]
29
+ const compact = text => text.replace(/\s+/gu, '')
30
+ const asFile = (name, bytes) => ({ name, arrayBuffer: async () => Uint8Array.from(bytes).buffer })
31
+ const aqChapters = ['第一章 序', '第二章 優勝記略', '第三章 續優勝記略', '第四章 戀愛的悲劇', '第五章 生計問題', '第六章 從中興到末路', '第七章 革命', '第八章 不准革命', '第九章 大團圓']
32
+ await mkdir(output, { recursive: true })
33
+ for (const source of books) await copyFile(resolve(root, 'samples/ebooks', source.file), resolve(output, source.file))
34
+ if (args.length) {
35
+ const input = resolve(args[1])
36
+ for (const source of additional) {
37
+ if (resolve(input, source.file) !== resolve(output, source.file)) await copyFile(resolve(input, source.file), resolve(output, source.file))
38
+ }
39
+ }
40
+ const aq = books.find(book => book.id === 'aq-zheng-zhuan')
41
+ const aqText = await readFile(resolve(output, aq.file), 'utf8')
42
+ const prefix = aq.derivation.prefix
43
+ assert.ok(aqText.startsWith(prefix))
44
+ const originalAqText = aqText.slice(prefix.length)
45
+ assert.equal(Buffer.byteLength(originalAqText), aq.derivation.originalBytes)
46
+ assert.equal(createHash('sha256').update(originalAqText).digest('hex'), aq.derivation.originalSha256)
47
+ // A deterministic EPUB container around the entire recovered export, including
48
+ // all credits/license text. No source EPUB is claimed and no obsolete sample is read.
49
+ const escapeXml = text => text.replace(/&/gu, '&amp;').replace(/</gu, '&lt;').replace(/>/gu, '&gt;')
50
+ const zip = new JSZip()
51
+ const add = (path, text) => zip.file(path, text, { date: new Date('2000-01-01T00:00:00Z'), compression: 'STORE', createFolders: false })
52
+ add('mimetype', 'application/epub+zip')
53
+ add('META-INF/container.xml', '<?xml version="1.0"?><container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles></container>')
54
+ add('OEBPS/content.opf', '<?xml version="1.0"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="book-id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="book-id">aq-derived-test-fixture</dc:identifier><dc:title>阿Q正傳 · derived test fixture</dc:title><dc:language>zh</dc:language><meta property="dcterms:modified">2000-01-01T00:00:00Z</meta></metadata><manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/><item id="text" href="text.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="text"/></spine></package>')
55
+ add('OEBPS/nav.xhtml', '<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><head><title>Test fixture</title></head><body><nav epub:type="toc"><ol><li><a href="text.xhtml">阿Q正傳</a></li></ol></nav></body></html>')
56
+ add('OEBPS/text.xhtml', `<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Test fixture</title></head><body><h1>阿Q正傳</h1><pre>${escapeXml(originalAqText)}</pre></body></html>`)
57
+ const fixtureFile = 'aq-derived-test-fixture.epub'
58
+ const fixtureBytes = await zip.generateAsync({ type: 'nodebuffer', compression: 'STORE' })
59
+ const checked = await JSZip.loadAsync(fixtureBytes, { checkCRC32: true })
60
+ assert.equal(await checked.file('mimetype').async('string'), 'application/epub+zip')
61
+ await writeFile(resolve(output, fixtureFile), fixtureBytes)
62
+ const corpus = [
63
+ ...books.map(book => ({ ...book, expectedSegments: book.format === 'txt' ? 820 : 100, expected: 'imported' })),
64
+ { id: aq.id, file: fixtureFile, format: 'epub', title: '阿Q正傳 · derived test fixture', source: aq.source,
65
+ derivedFrom: aq.file, transformation: 'Test-only EPUB container with an XML-escaped complete original TXT export and one title heading; not an original downloaded EPUB; never bundled.', expected: 'imported' },
66
+ ...additional.map(book => ({ ...book, title: "Alice's Adventures in Wonderland", expected: 'rejected' })),
67
+ ]
68
+ const storage = new MemoryStorage()
69
+ const store = new NovelStore(storage)
70
+ await store.ready
71
+ const results = []
72
+ try {
73
+ const original = await store.importFile(asFile('existing.txt', new TextEncoder().encode('第一章 原书\n\n保留的原有内容。'.repeat(200))))
74
+ const first = await store.claimPassage('original-before-import')
75
+ assert.equal(first.kind, 'ready')
76
+ const originalBook = structuredClone(storage.books.get(original.id))
77
+ const originalPassages = structuredClone([...storage.passages.entries()])
78
+ let bundledBytes = 0
79
+ for (const source of corpus) {
80
+ const bytes = await readFile(resolve(output, source.file))
81
+ if (source.format === 'pdf') assert.equal(bytes.subarray(0, 5).toString(), '%PDF-')
82
+ if (['mobi', 'azw3'].includes(source.format)) assert.equal(bytes.subarray(60, 68).toString(), 'BOOKMOBI')
83
+ if (source.format === 'html') assert.match(bytes.toString('utf8').slice(0, 200), /<!DOCTYPE html|<html/iu)
84
+ const hash = createHash('sha256').update(bytes).digest('hex')
85
+ if (source.sha256) {
86
+ assert.equal(bytes.length, source.bytes, source.file)
87
+ assert.equal(hash, source.sha256, source.file)
88
+ bundledBytes += bytes.length
89
+ }
90
+ const file = asFile(source.file, bytes)
91
+ const started = performance.now()
92
+ const result = {
93
+ file: source.file, title: source.title, format: source.format, source: source.source,
94
+ ...(source.download ? { download: source.download } : {}),
95
+ ...(source.edition ? { edition: source.edition, license: source.license } : {}),
96
+ ...(source.derivedFrom ? { derivedFrom: source.derivedFrom, transformation: source.transformation } : {}),
97
+ bytes: bytes.length, sha256: hash, expected: source.expected,
98
+ }
99
+ if (source.expected === 'rejected') {
100
+ const before = await storage.load()
101
+ const passages = structuredClone([...storage.passages.entries()])
102
+ await assert.rejects(store.importFile(file), error => {
103
+ assert.match(error.message, /只支持 EPUB、TXT、MD 文件/u)
104
+ result.message = error.message
105
+ return true
106
+ })
107
+ assert.deepEqual(await storage.load(), before)
108
+ assert.deepEqual([...storage.passages.entries()], passages)
109
+ result.actual = 'rejected-with-library-unchanged'
110
+ } else {
111
+ const book = await store.importFile(file)
112
+ assert.equal(book.format, source.format)
113
+ assert.ok(book.segmentCount > 1)
114
+ if (source.expectedSegments) assert.equal(book.segmentCount, source.expectedSegments)
115
+ assert.equal(book.progress, 0)
116
+ const segments = await Promise.all(Array.from({ length: book.segmentCount }, (_, index) => storage.getSegment(book.id, index)))
117
+ const body = segments.map(segment => segment.text).join('\n')
118
+ const text = compact(body)
119
+ assert.doesNotMatch(body, /\uFFFD/u)
120
+ if (source.id === 'million-pound-bank-note') {
121
+ assert.ok(text.includes(compact('When I was twenty-seven years old, I was a mining-broker’s clerk in San Francisco')), 'not merely PG metadata/license')
122
+ assert.ok(text.includes(compact('My Portia’s papa took that friendly and hospitable bill back to the Bank of England and cashed it')))
123
+ assert.match(body, /_A MAJESTIC LITERARY FOSSIL_/u)
124
+ assert.match(body, /START: FULL LICENSE/u)
125
+ assert.match(body, /Section 5\. General Information/u)
126
+ result.actual = 'imported-readable-english-collection'
127
+ } else {
128
+ assert.equal(source.id, 'aq-zheng-zhuan')
129
+ assert.ok(text.includes('我要給阿Q做正傳,已經不止一兩年了。'))
130
+ assert.ok(text.includes('他們白跟一趟了。'))
131
+ assert.ok(text.includes('(一九二一年十二月。)'))
132
+ assert.match(body, /About this digital edition/u)
133
+ assert.match(body, /Creative Commons Attribution-ShareAlike 3\.0 Unported.*GNU FDL/u)
134
+ assert.match(body, /Dbenbenn/u)
135
+ assert.equal(text, compact(originalAqText), 'Markdown and test EPUB retain the complete exported text')
136
+ assert.equal(segments[0].chapterTitle, '阿Q正傳')
137
+ for (const title of aqChapters) assert.ok(text.includes(compact(title)), title)
138
+ result.actual = source.format === 'md' ? 'imported-readable-complete-chinese-markdown-derivative' : 'imported-readable-complete-chinese-derived-test-epub'
139
+ }
140
+ result.segmentCount = book.segmentCount
141
+ }
142
+ assert.equal(store.getSettingsSnapshot().currentBookId, original.id)
143
+ assert.deepEqual(storage.books.get(original.id), originalBook)
144
+ for (const [key, passage] of originalPassages) assert.deepEqual(storage.passages.get(key), passage)
145
+ assert.deepEqual(await store.claimPassage('original-before-import'), first, 'imports do not invalidate or advance the existing passage')
146
+ result.milliseconds = Math.round((performance.now() - started) * 100) / 100
147
+ results.push(result)
148
+ }
149
+ assert.equal(bundledBytes, 462708)
150
+ assert.ok(bundledBytes < 600 * 1024)
151
+ const report = {
152
+ verifiedOn: new Date().toISOString(), scope: 'NovelStore + MemoryStorage; no GUI claims; no network requests',
153
+ output: 'dist/ebooks', bundledBytes, originalSelectionAndProgressUnchanged: true,
154
+ redistribution: 'Bundled samples comprise one unchanged English TXT download and one clearly labelled complete AQ Markdown derivative, under their individual notices, not plugin MIT. The Markdown suffix retains the full original official TXT export and credits byte-for-byte. The generated AQ EPUB is a local test-only derivative preserving the complete export, not an original EPUB download or package asset. The four Alice files are local negative-test downloads, not package assets; the Adobe PDF is not cleared for redistribution.',
155
+ results,
156
+ }
157
+ await writeFile(resolve(output, 'results.json'), `${JSON.stringify(report, null, 2)}\n`)
158
+ console.log(JSON.stringify(report, null, 2))
159
+ } finally {
160
+ store.dispose()
161
+ }
@@ -0,0 +1,42 @@
1
+ import manifest from '../samples/ebooks/sources.json'
2
+ import millionPoundBankNote from '../samples/ebooks/million-pound-bank-note-pg61522.txt'
3
+ import aqZhengZhuan from '../samples/ebooks/aq-zheng-zhuan-wikisource.md'
4
+ import notices from '../samples/ebooks/LICENSE.md'
5
+
6
+ // TXT uses the existing base64 loader; Markdown stays text, like legal notices.
7
+ // Encode/decode lazily during hydration/import, without File or network access.
8
+ const payloads = {
9
+ 'million-pound-bank-note': () => Uint8Array.from(atob(millionPoundBankNote), character => character.charCodeAt(0)),
10
+ 'aq-zheng-zhuan': () => new TextEncoder().encode(aqZhengZhuan),
11
+ }
12
+ export const sampleBooks = manifest.books.map(({ id, title, author, format, bytes, source, license }) => ({ id, title, author, format, bytes, source, license }))
13
+
14
+ export function createSampleFile(id) {
15
+ const book = sampleBooks.find(book => book.id === id)
16
+ if (!book || !Object.hasOwn(payloads, id)) throw new Error('Unknown bundled ebook')
17
+ const bytes = payloads[id]()
18
+ return { name: `${book.title}.${book.format}`, arrayBuffer: async () => bytes.buffer }
19
+ }
20
+
21
+ // Separate from the original seeding marker: upgrades must not restore deleted
22
+ // defaults or claim ownership of untagged manual imports, even identical ones.
23
+ export const bundledCatalog = {
24
+ version: 2,
25
+ removedIds: ['shanhaijing-illustrated'],
26
+ updates: [{
27
+ id: 'aq-zheng-zhuan', fromFormat: 'txt', format: 'md',
28
+ createFile: () => {
29
+ const prefix = '# 阿Q正傳\n\n'
30
+ if (!aqZhengZhuan.startsWith(prefix)) throw new Error('Invalid bundled Markdown source prefix')
31
+ const bytes = new TextEncoder().encode(aqZhengZhuan.slice(prefix.length))
32
+ return { name: '阿Q正傳.txt', arrayBuffer: async () => bytes.buffer }
33
+ },
34
+ }],
35
+ }
36
+
37
+ // Combined full licenses and attribution are immediately accessible offline.
38
+ let licenseHref
39
+ export function getSampleLicenseHref() {
40
+ if (!licenseHref) licenseHref = `data:text/plain;charset=utf-8,${encodeURIComponent(notices)}`
41
+ return licenseHref
42
+ }
@@ -1,5 +1,6 @@
1
1
  import { passageSnapshotKey } from './store.js'
2
- import { NOVEL_STYLE, SEPARATOR_STYLE, novelContent } from './novel-content.js'
2
+ import { NOVEL_STYLE, PASSAGE_STYLE, SEPARATOR_STYLE, novelContent } from './novel-content.js'
3
+ import { PG_NOTICE, PG_NOTICE_STYLE, PG_LICENSE_LABEL, PG_LICENSE_DOWNLOAD } from './pg-notice.js'
3
4
 
4
5
  const THOUGHT = '[data-chat-flow-kind="assistant-step"] [data-variant="think"]'
5
6
  const TOOL = '[data-chat-call-id] [data-tool], [data-chat-call-id] [data-sample="bash"]'
@@ -7,12 +8,12 @@ const REGIONS = `${THOUGHT}, ${TOOL}`
7
8
  const EMPTY = Object.freeze({ kind: 'empty' })
8
9
 
9
10
  /** DSH 0.2.1 窄适配:保留原生控件和正文,只改标题文字并追加本地纯文本。 */
10
- export function registerChatAdapter(ctx, store, React, locale) {
11
+ export function registerChatAdapter(ctx, store, React, locale, { getSampleLicenseHref } = {}) {
11
12
  const t = ctx.locale?.bind(locale) ?? (key => key)
12
13
  ctx.slots.inject('conversation.chat.reasoning.body', () => ctx.slots.register({
13
14
  name: 'conversation.chat.reasoning.body', priority: -10, locale,
14
15
  inject: () => ({ hooks: { novelSettings: store.settingsSource, novelPassages: store.passageSource } }),
15
- }, createBody(React)))
16
+ }, createBody(React, getSampleLicenseHref)))
16
17
 
17
18
  ctx.effect(() => {
18
19
  const decorated = new Map()
@@ -91,7 +92,7 @@ export function registerChatAdapter(ctx, store, React, locale) {
91
92
  record.signature = null
92
93
  }
93
94
  if (signature !== record.signature) {
94
- renderPlainAppend(record.append, model)
95
+ renderPlainAppend(record.append, model, getSampleLicenseHref)
95
96
  record.signature = signature
96
97
  }
97
98
  }
@@ -195,7 +196,7 @@ function writeText(node, value) {
195
196
  }
196
197
  function restoreText(node, text) { if (readText(node) === text.shown) writeText(node, text.native) }
197
198
 
198
- function createBody(React) {
199
+ function createBody(React, getSampleLicenseHref) {
199
200
  const h = React.createElement
200
201
  return function NovelBody({ text, running, sessionId, useNovelSettings, useNovelPassages, renderFactorySlot, t }) {
201
202
  const ref = React.useRef(null)
@@ -211,11 +212,15 @@ function createBody(React) {
211
212
  model === null ? null : h('div', { 'data-novel-append': true, style: NOVEL_STYLE },
212
213
  h('hr', { style: SEPARATOR_STYLE }),
213
214
  h('div', { 'data-novel-label': true }, model.chapter ? `${model.label} · ${model.chapter}` : model.label),
214
- h('div', { 'data-novel-passage': model.index, role: model.role }, model.text)),
215
+ model.projectGutenberg ? h('aside', { 'data-novel-pg-notice': true, style: PG_NOTICE_STYLE },
216
+ h('p', { style: { margin: '0 0 6px' } }, PG_NOTICE),
217
+ h('a', { href: getSampleLicenseHref?.(), download: PG_LICENSE_DOWNLOAD }, PG_LICENSE_LABEL)) : null,
218
+ h('div', { 'data-novel-passage': model.index, role: model.role, style: PASSAGE_STYLE,
219
+ tabIndex: model.index ? 0 : undefined, 'aria-label': model.index ? model.label : undefined }, model.text)),
215
220
  )
216
221
  }
217
222
  }
218
- function renderPlainAppend(element, model) {
223
+ function renderPlainAppend(element, model, getSampleLicenseHref) {
219
224
  Object.assign(element.style, NOVEL_STYLE)
220
225
  const divider = document.createElement('hr')
221
226
  Object.assign(divider.style, SEPARATOR_STYLE)
@@ -223,10 +228,30 @@ function renderPlainAppend(element, model) {
223
228
  label.setAttribute('data-novel-label', '')
224
229
  label.textContent = model.chapter ? `${model.label} · ${model.chapter}` : model.label
225
230
  const content = document.createElement('div')
226
- if (model.index) content.setAttribute('data-novel-passage', model.index)
231
+ Object.assign(content.style, PASSAGE_STYLE)
232
+ if (model.index) {
233
+ content.setAttribute('data-novel-passage', model.index)
234
+ content.tabIndex = 0
235
+ content.setAttribute('aria-label', model.label)
236
+ }
227
237
  if (model.role) content.setAttribute('role', model.role)
228
238
  content.textContent = model.text
229
- element.replaceChildren(divider, label, content)
239
+ const notice = []
240
+ if (model.projectGutenberg) {
241
+ const aside = document.createElement('aside')
242
+ aside.setAttribute('data-novel-pg-notice', '')
243
+ Object.assign(aside.style, PG_NOTICE_STYLE)
244
+ const statement = document.createElement('p')
245
+ statement.style.margin = '0 0 6px'
246
+ statement.textContent = PG_NOTICE
247
+ const license = document.createElement('a')
248
+ license.href = getSampleLicenseHref?.() ?? ''
249
+ license.download = PG_LICENSE_DOWNLOAD
250
+ license.textContent = PG_LICENSE_LABEL
251
+ aside.append(statement, license)
252
+ notice.push(aside)
253
+ }
254
+ element.replaceChildren(divider, label, ...notice, content)
230
255
  }
231
256
  function identityOf(element) {
232
257
  const root = element?.closest('[data-variant="think"], [data-tool], [data-sample="bash"]')
package/src/client.js CHANGED
@@ -2,6 +2,7 @@ import { IndexedDbStorage } from './persistence.js'
2
2
  import { NovelStore } from './store.js'
3
3
  import { registerChatAdapter } from './chat-adapter.js'
4
4
  import { createSettingsRow } from './settings.js'
5
+ import { sampleBooks, bundledCatalog, createSampleFile, getSampleLicenseHref } from './bundled-books.js'
5
6
  import zh from '../locale/zh.json'
6
7
  import en from '../locale/en.json'
7
8
 
@@ -24,7 +25,10 @@ window.__ModuleLoader__.load({
24
25
  inject: ['slots', 'locale'],
25
26
  apply(ctx) {
26
27
  const storage = new IndexedDbStorage()
27
- const store = new NovelStore(storage)
28
+ const store = new NovelStore(storage, {
29
+ bundledBooks: sampleBooks.map(book => ({ ...book, createFile: () => createSampleFile(book.id) })),
30
+ bundledCatalog,
31
+ })
28
32
  const SettingsRow = createSettingsRow(React, primitives)
29
33
  const settingsActions = {
30
34
  onSetOption: (key, value) => store.setOption(key, value),
@@ -32,6 +36,8 @@ window.__ModuleLoader__.load({
32
36
  onSelectBook: bookId => store.selectBook(bookId),
33
37
  onDeleteBook: bookId => store.deleteBook(bookId),
34
38
  onImportFile: file => store.importFile(file),
39
+ sampleBooks,
40
+ getSampleLicenseHref,
35
41
  }
36
42
 
37
43
  ctx.effect(() => ctx.locale.register(LOCALE, { zh: flatten(zh), en: flatten(en) }), 'novel-fish: locale')
@@ -48,7 +54,7 @@ window.__ModuleLoader__.load({
48
54
  ...settingsActions,
49
55
  }),
50
56
  }, SettingsRow))
51
- registerChatAdapter(ctx, store, React, LOCALE)
57
+ registerChatAdapter(ctx, store, React, LOCALE, { getSampleLicenseHref })
52
58
  },
53
59
  }
54
60
  },
@@ -5,6 +5,13 @@ export const NOVEL_STYLE = {
5
5
  color: 'var(--dsw-alias-label-tertiary)',
6
6
  whiteSpace: 'pre-wrap', overflowWrap: 'anywhere',
7
7
  }
8
+ // 只约束新增的小说正文,不裁剪原生思考/工具输出。窄屏与旧书的长段落
9
+ // 仍保留全部文字,可滚动/键盘阅读,避免把宿主折叠控件推得过远。
10
+ export const PASSAGE_STYLE = {
11
+ maxHeight: 'min(40vh, 20.8em)',
12
+ overflowY: 'auto',
13
+ scrollbarGutter: 'stable',
14
+ }
8
15
  export const SEPARATOR_STYLE = {
9
16
  border: 0, borderTop: '1px solid var(--dsw-alias-border-l2)', margin: '10px 0 8px',
10
17
  }
@@ -13,6 +20,7 @@ export function novelContent(status, hasBook, t) {
13
20
  if (status.kind === 'ready') return {
14
21
  label: t('chat.novel'), chapter: status.passage.chapterTitle || '',
15
22
  text: status.passage.text, index: status.index + 1,
23
+ projectGutenberg: status.projectGutenberg === true,
16
24
  }
17
25
  const message = status.kind === 'loading' ? 'chat.loading' : status.kind === 'end' ? 'chat.end'
18
26
  : status.kind === 'error' ? 'chat.readError' : hasBook ? 'chat.switchHint' : 'chat.noBook'
@@ -1,6 +1,8 @@
1
1
  const DATABASE_NAME = 'dsh-touch-fish-novel'
2
2
  const DATABASE_VERSION = 1
3
3
  const SETTINGS_KEY = 'settings'
4
+ const BUNDLED_BOOKS_KEY = 'bundled-books-v1'
5
+ const BUNDLED_CATALOG_KEY = 'bundled-catalog-version'
4
6
 
5
7
  /** IndexedDB persistence for book metadata, parsed passages, and plugin settings. */
6
8
  export class IndexedDbStorage {
@@ -19,10 +21,129 @@ export class IndexedDbStorage {
19
21
  const db = await this.#open()
20
22
  const tx = db.transaction(['books', 'settings'], 'readonly')
21
23
  const done = transactionDone(tx)
22
- const books = await requestResult(tx.objectStore('books').getAll())
23
- const settings = await requestResult(tx.objectStore('settings').get(SETTINGS_KEY))
24
+ const stored = await readLibrary(tx)
24
25
  await done
25
- return { books, settings: settings?.value }
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
+ }
26
147
  }
27
148
 
28
149
  async saveSettings(value) {
@@ -114,6 +235,26 @@ export class IndexedDbStorage {
114
235
  }
115
236
  }
116
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
+
117
258
  function requestResult(request) {
118
259
  return new Promise((resolve, reject) => {
119
260
  request.onsuccess = () => resolve(request.result)
@@ -0,0 +1,19 @@
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
+ }