@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.
- package/README.md +42 -14
- package/docs/community-markets.md +18 -1
- package/docs/compatibility-101.md +41 -0
- package/docs/ebook-tests.md +99 -0
- package/docs/evidence/reading-demo-110.png +0 -0
- package/docs/evidence/reading-two-expansions-110.gif +0 -0
- package/docs/evidence/reading-two-expansions-110.json +89 -0
- package/docs/evidence/samples-110-capture.json +49 -0
- package/docs/evidence/settings-110.png +0 -0
- package/docs/marketplace.md +4 -4
- package/docs/release.md +25 -0
- package/index.json +24 -0
- package/lib/client.js +523 -95
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +10 -9
- package/samples/ebooks/LICENSE.md +355 -0
- package/samples/ebooks/NOTICE.md +33 -0
- package/samples/ebooks/aq-zheng-zhuan-wikisource.md +998 -0
- package/samples/ebooks/million-pound-bank-note-pg61522.txt +6970 -0
- package/samples/ebooks/sources.json +58 -0
- package/scripts/build.mjs +1 -0
- package/scripts/check-host-contracts.mjs +3 -2
- package/scripts/make-readme-gif.mjs +69 -0
- package/scripts/test-browser-samples.mjs +665 -0
- package/scripts/test-candidate-books.mjs +71 -0
- package/scripts/test-ebook-corpus.mjs +161 -0
- package/src/bundled-books.js +42 -0
- package/src/chat-adapter.js +34 -9
- package/src/client.js +8 -2
- package/src/novel-content.js +8 -0
- package/src/persistence.js +144 -3
- package/src/pg-notice.js +19 -0
- package/src/segments.js +115 -65
- package/src/settings.js +32 -8
- package/src/store.js +61 -3
- package/test/bundled-library.test.js +526 -0
- package/test/chat-adapter.test.js +87 -2
- package/test/client.test.js +49 -7
- package/test/ebooks.test.js +192 -0
- package/test/pg-notice.test.js +109 -0
- package/test/release.test.js +21 -7
- package/test/segments.test.js +136 -2
- package/test/settings.test.js +42 -1
package/test/client.test.js
CHANGED
|
@@ -17,11 +17,15 @@ test('构建产物只在本包详情注册设置,复用宿主 Switch 与原有
|
|
|
17
17
|
const settings = { ...DEFAULT_SETTINGS, enabled: false, currentBookId: book.id, mainTitle: '已保存标题' }
|
|
18
18
|
await storage.addBook(book, [{ text: 'A' }, { text: 'B' }])
|
|
19
19
|
await storage.saveSettings(settings)
|
|
20
|
-
const
|
|
20
|
+
const manifest = JSON.parse(await readFile(new URL('../samples/ebooks/sources.json', import.meta.url), 'utf8'))
|
|
21
|
+
const notices = await readFile(new URL('../samples/ebooks/LICENSE.md', import.meta.url), 'utf8')
|
|
22
|
+
const imports = [], effects = [], injections = [], registrations = [], decodedPayloads = []
|
|
21
23
|
let module
|
|
22
24
|
vm.runInNewContext(await readFile(new URL('../lib/client.js', import.meta.url), 'utf8'), {
|
|
23
25
|
window: { __ModuleLoader__: { load: value => { module = value } } },
|
|
24
|
-
indexedDB, IDBKeyRange, TextDecoder, TextEncoder,
|
|
26
|
+
indexedDB, IDBKeyRange, TextDecoder, TextEncoder, URL, Blob,
|
|
27
|
+
atob: payload => { decodedPayloads.push(payload); return atob(payload) },
|
|
28
|
+
setTimeout, clearTimeout, setImmediate, clearImmediate,
|
|
25
29
|
console,
|
|
26
30
|
})
|
|
27
31
|
const plugin = module.factory(name => {
|
|
@@ -50,13 +54,22 @@ test('构建产物只在本包详情注册设置,复用宿主 Switch 与原有
|
|
|
50
54
|
const injected = own.options.inject()
|
|
51
55
|
const source = injected.hooks.novelState
|
|
52
56
|
await new Promise((resolve, reject) => {
|
|
53
|
-
|
|
54
|
-
|
|
57
|
+
// Real default-book parsing competes with parallel EPUB/host tests. This
|
|
58
|
+
// checks completion, not a 2-second performance SLA on the test runner.
|
|
59
|
+
const timer = setTimeout(() => { off(); reject(new Error('Book hydration timed out')) }, 10000)
|
|
60
|
+
const check = () => {
|
|
61
|
+
const state = source.getSnapshot()
|
|
62
|
+
if (state.error || state.hydrated) {
|
|
63
|
+
off(); clearTimeout(timer)
|
|
64
|
+
if (state.error) reject(new Error(`Book hydration failed: ${state.error}`))
|
|
65
|
+
else resolve()
|
|
66
|
+
}
|
|
67
|
+
}
|
|
55
68
|
const off = source.subscribe(check)
|
|
56
69
|
check()
|
|
57
70
|
})
|
|
58
71
|
assert.equal(source.getSnapshot().error, null)
|
|
59
|
-
assert.equal(source.getSnapshot().books
|
|
72
|
+
assert.equal(source.getSnapshot().books.find(entry => entry.id === book.id).progress, 1)
|
|
60
73
|
assert.equal(source.getSnapshot().settings.mainTitle, settings.mainTitle)
|
|
61
74
|
const props = { ...injected, t: key => key, view: 'page',
|
|
62
75
|
useNovelState: select => select(React.useSyncExternalStore(source.subscribe, source.getSnapshot)),
|
|
@@ -65,15 +78,44 @@ test('构建产物只在本包详情注册设置,复用宿主 Switch 与原有
|
|
|
65
78
|
await act(async () => { view = TestRenderer.create(React.createElement(own.Component, props)) })
|
|
66
79
|
const enabledSwitch = () => view.root.findAllByType(HostSwitch).find(node => node.props.label === 'settings.enabled')
|
|
67
80
|
assert.equal(enabledSwitch().props.checked, false)
|
|
68
|
-
assert.equal(source.getSnapshot().books
|
|
81
|
+
assert.equal(source.getSnapshot().books.find(entry => entry.id === book.id).progress, 1)
|
|
69
82
|
await act(async () => { await injected.onSetOption('enabled', true) })
|
|
70
83
|
assert.equal(enabledSwitch().props.checked, true)
|
|
71
84
|
const saved = await storage.load()
|
|
72
85
|
assert.equal(saved.settings.enabled, true)
|
|
73
86
|
assert.equal(saved.settings.currentBookId, book.id)
|
|
74
87
|
assert.equal(saved.settings.mainTitle, settings.mainTitle)
|
|
75
|
-
assert.equal(saved.books
|
|
88
|
+
assert.equal(saved.books.find(entry => entry.id === book.id).progress, 1)
|
|
76
89
|
assert.deepEqual(await storage.getSegment(book.id, 1), { text: 'B' })
|
|
90
|
+
const expectedSamples = manifest.books.map(({ id, title, author, format, bytes, source, license }) => ({ id, title, author, format, bytes, source, license }))
|
|
91
|
+
assert.deepEqual(JSON.parse(JSON.stringify(injected.sampleBooks)), expectedSamples)
|
|
92
|
+
for (const sample of manifest.books) {
|
|
93
|
+
assert.ok(sample.license?.trim(), `Missing concise license for ${sample.id}`)
|
|
94
|
+
assert.equal(sample.bytes, (await readFile(new URL(`../samples/ebooks/${sample.file}`, import.meta.url))).byteLength)
|
|
95
|
+
}
|
|
96
|
+
assert.equal(decodedPayloads.length, manifest.books.filter(book => book.format !== 'md').length, 'Initial hydration provisions all bundled books once')
|
|
97
|
+
assert.equal(injected.onImportSample, undefined, 'No separate bundled import action')
|
|
98
|
+
const licenseHref = injected.getSampleLicenseHref()
|
|
99
|
+
assert.ok(licenseHref.startsWith('data:text/plain;charset=utf-8,'))
|
|
100
|
+
assert.equal(decodeURIComponent(licenseHref.slice(licenseHref.indexOf(',') + 1)), notices)
|
|
101
|
+
assert.equal(injected.getSampleLicenseHref(), licenseHref)
|
|
102
|
+
assert.equal(decodedPayloads.length, manifest.books.filter(book => book.format !== 'md').length, 'Offline notices must not decode another ebook')
|
|
103
|
+
for (const sample of injected.sampleBooks) {
|
|
104
|
+
const seeded = source.getSnapshot().books.find(entry => entry.bundledId === sample.id)
|
|
105
|
+
assert.equal(seeded.id, `bundled:${sample.id}`)
|
|
106
|
+
assert.equal(seeded.title, sample.title)
|
|
107
|
+
assert.equal(seeded.format, sample.format)
|
|
108
|
+
assert.ok(seeded.segmentCount > 1)
|
|
109
|
+
}
|
|
110
|
+
assert.equal((await storage.load()).books.length, 1 + manifest.books.length)
|
|
111
|
+
const seededId = `bundled:${injected.sampleBooks[0].id}`
|
|
112
|
+
await act(async () => { await injected.onSelectBook(seededId) })
|
|
113
|
+
assert.equal(source.getSnapshot().settings.currentBookId, seededId)
|
|
114
|
+
await act(async () => { await injected.onDeleteBook(seededId) })
|
|
115
|
+
assert.equal(source.getSnapshot().books.some(entry => entry.id === seededId), false)
|
|
116
|
+
assert.equal((await storage.load()).bundledBooksInitialized, true)
|
|
117
|
+
assert.equal((await storage.load()).books.length, manifest.books.length)
|
|
118
|
+
assert.equal(source.getSnapshot().books.find(entry => entry.id === book.id).progress, 1)
|
|
77
119
|
} finally {
|
|
78
120
|
if (view) await act(async () => view.unmount())
|
|
79
121
|
effects[1]()() // Dispose only the store effect; do not install chat DOM observers.
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { readFile } from 'node:fs/promises'
|
|
4
|
+
import { createHash } from 'node:crypto'
|
|
5
|
+
import { NovelStore } from '../src/store.js'
|
|
6
|
+
import { MemoryStorage } from './helpers/memory-storage.js'
|
|
7
|
+
|
|
8
|
+
// Ordinary tests use only committed samples: no dist, temporary downloads or network.
|
|
9
|
+
const samples = new URL('../samples/ebooks/', import.meta.url)
|
|
10
|
+
const { books } = JSON.parse(await readFile(new URL('sources.json', samples), 'utf8'))
|
|
11
|
+
const pinned = {
|
|
12
|
+
'million-pound-bank-note': { file: 'million-pound-bank-note-pg61522.txt', format: 'txt', bytes: 394538, sha256: '4f36f8ce3837afd6c28a23684153a946e39c8970a27486d36f6f4c64b92bb0d2' },
|
|
13
|
+
'aq-zheng-zhuan': { file: 'aq-zheng-zhuan-wikisource.md', format: 'md', bytes: 68170, sha256: '228f5e9504caecc97460e815461df7ac60de80ea311f289f7de23760c69c9643' },
|
|
14
|
+
}
|
|
15
|
+
const aqChapters = ['第一章 序', '第二章 優勝記略', '第三章 續優勝記略', '第四章 戀愛的悲劇', '第五章 生計問題', '第六章 從中興到末路', '第七章 革命', '第八章 不准革命', '第九章 大團圓']
|
|
16
|
+
const otherStories = ['MENTAL TELEGRAPHY', 'A CURE FOR THE BLUES', 'THE ENEMY CONQUERED; OR, LOVE TRIUMPHANT', 'ABOUT ALL KINDS OF SHIPS', 'PLAYING COURIER', 'THE GERMAN CHICAGO', 'A PETITION TO THE QUEEN OF ENGLAND', 'A MAJESTIC LITERARY FOSSIL']
|
|
17
|
+
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex')
|
|
18
|
+
const compact = text => text.replace(/\s+/gu, '')
|
|
19
|
+
const asFile = (name, bytes) => ({ name, arrayBuffer: async () => Uint8Array.from(bytes).buffer })
|
|
20
|
+
const byId = id => books.find(book => book.id === id)
|
|
21
|
+
const segmentsFor = (storage, book) => Promise.all(Array.from({ length: book.segmentCount }, (_, index) => storage.getSegment(book.id, index)))
|
|
22
|
+
const storedBody = async (storage, book) => (await segmentsFor(storage, book)).map(segment => segment.text).join('\n')
|
|
23
|
+
|
|
24
|
+
function assertReadableBody(id, body) {
|
|
25
|
+
assert.doesNotMatch(body, /\uFFFD/u)
|
|
26
|
+
const text = compact(body)
|
|
27
|
+
if (id === 'million-pound-bank-note') {
|
|
28
|
+
assert.ok(text.includes(compact('When I was twenty-seven years old, I was a mining-broker’s clerk in San Francisco')), 'English narrative, not just PG wrapper')
|
|
29
|
+
assert.ok(text.includes(compact('My Portia’s papa took that friendly and hospitable bill back to the Bank of England and cashed it')), 'title story reaches its ending')
|
|
30
|
+
for (const title of otherStories) assert.ok(text.includes(compact(`_${title}_`)), title)
|
|
31
|
+
} else {
|
|
32
|
+
assert.equal(id, 'aq-zheng-zhuan')
|
|
33
|
+
assert.ok(text.includes('我要給阿Q做正傳,已經不止一兩年了。'))
|
|
34
|
+
assert.ok(text.includes('他們白跟一趟了。'), 'AQ final paragraph survived import')
|
|
35
|
+
assert.ok(text.includes('(一九二一年十二月。)'))
|
|
36
|
+
assert.match(body, /About this digital edition/u)
|
|
37
|
+
assert.match(body, /The following users contributed to this book:/u)
|
|
38
|
+
assert.match(body, /Dbenbenn/u)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function seededStorage() {
|
|
43
|
+
return new MemoryStorage({
|
|
44
|
+
books: [{ id: 'existing', title: '已有的书', format: 'txt', progress: 1, segmentCount: 3, importedAt: 1 }],
|
|
45
|
+
settings: { currentBookId: 'existing', mainTitle: '原来的标题' },
|
|
46
|
+
passages: { existing: [{ text: '已经读过。' }, { text: '保留现有阅读位置。' }, { text: '最后一段。' }] },
|
|
47
|
+
})
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
test('confirmed two-book offline corpus pins original English TXT and complete derived AQ Markdown bytes', async () => {
|
|
51
|
+
assert.deepEqual(books.map(book => book.id), Object.keys(pinned))
|
|
52
|
+
let totalBytes = 0
|
|
53
|
+
for (const source of books) {
|
|
54
|
+
for (const [key, value] of Object.entries(pinned[source.id])) assert.equal(source[key], value, `${source.id}.${key}`)
|
|
55
|
+
const bytes = await readFile(new URL(source.file, samples))
|
|
56
|
+
assert.equal(bytes.length, source.bytes, source.file)
|
|
57
|
+
assert.equal(sha256(bytes), source.sha256, source.file)
|
|
58
|
+
assert.equal(source.redistribution.status, 'permitted-with-conditions')
|
|
59
|
+
assert.equal(source.redistribution.packageByDefault, true)
|
|
60
|
+
assert.match(source.redistribution.conditions, /Retain|Keep/u)
|
|
61
|
+
totalBytes += bytes.length
|
|
62
|
+
}
|
|
63
|
+
assert.equal(totalBytes, 462708)
|
|
64
|
+
assert.ok(totalBytes < 600 * 1024, `Bundled corpus grew to ${totalBytes} bytes`)
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
test('manifest and combined notices distinguish collection, complete Markdown derivative and digital licenses', async () => {
|
|
68
|
+
const english = byId('million-pound-bank-note')
|
|
69
|
+
const aq = byId('aq-zheng-zhuan')
|
|
70
|
+
assert.equal(english.source, 'https://www.gutenberg.org/ebooks/61522')
|
|
71
|
+
assert.equal(english.redistribution.authorDeathYear, 1910)
|
|
72
|
+
assert.match(english.edition, /Unmodified original download.*collection/u)
|
|
73
|
+
assert.match(english.edition, /full title story and eight other stories; not a standalone/u)
|
|
74
|
+
assert.match(english.redistribution.conditions, /1\.E\.1.*full-license.*Fee-bearing/u)
|
|
75
|
+
assert.equal(aq.redistribution.authorDeathYear, 1936)
|
|
76
|
+
assert.match(aq.download, /^https:\/\/ws-export\.wmcloud\.org\/\?lang=zh&format=txt&page=/u)
|
|
77
|
+
assert.match(aq.edition, /Local Markdown derivative.*complete nine chapters/u)
|
|
78
|
+
assert.match(aq.redistribution.license, /CC BY-SA 3\.0 Unported or GFDL/u)
|
|
79
|
+
const notices = await readFile(new URL('LICENSE.md', samples), 'utf8')
|
|
80
|
+
for (const source of books) {
|
|
81
|
+
assert.ok(notices.includes(source.source), `${source.id} source attribution`)
|
|
82
|
+
assert.ok(notices.includes(source.redistribution.licenseUrl), `${source.id} license access`)
|
|
83
|
+
}
|
|
84
|
+
assert.match(notices, /NOT covered by the plugin's MIT/u)
|
|
85
|
+
assert.match(notices, /NOT a standalone/u)
|
|
86
|
+
assert.doesNotMatch(notices, /山海經|南山經|shanhaijing/u)
|
|
87
|
+
assert.match(notices, /CC BY-SA 3\.0.*GFDL/su)
|
|
88
|
+
const noticeIndex = await readFile(new URL('NOTICE.md', samples), 'utf8')
|
|
89
|
+
assert.match(noticeIndex, /^# 内置两本样书/mu)
|
|
90
|
+
assert.ok(noticeIndex.includes('462708 bytes'))
|
|
91
|
+
for (const source of books) assert.ok(noticeIndex.includes(source.file))
|
|
92
|
+
for (const [, link] of noticeIndex.matchAll(/\]\(<?([^)>]+)>?\)/gu)) {
|
|
93
|
+
if (!/^https?:/u.test(link)) await readFile(new URL(link, samples))
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const original = (await readFile(new URL(english.file, samples), 'utf8')).replace(/\r\n?/gu, '\n')
|
|
97
|
+
assert.match(original, /Credits: Produced by Richard Tonsing/u)
|
|
98
|
+
const licenseStart = original.indexOf('START: FULL LICENSE')
|
|
99
|
+
assert.ok(licenseStart > 0)
|
|
100
|
+
const fullLicense = original.slice(licenseStart).trim()
|
|
101
|
+
assert.match(fullLicense, /1\.E\.1\./u)
|
|
102
|
+
assert.match(fullLicense, /Section 5\. General Information/u)
|
|
103
|
+
assert.ok(notices.replace(/\r\n?/gu, '\n').includes(fullLicense), 'combined LICENSE retains the entire original PG license verbatim')
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
test('official AQ export has all nine ordered chapters, ending, notices and complete credit tail', async () => {
|
|
107
|
+
const original = await readFile(new URL(byId('aq-zheng-zhuan').file, samples), 'utf8')
|
|
108
|
+
assert.deepEqual([...original.matchAll(/^第[一二三四五六七八九]章[\t \u3000]+.+$/gmu)].map(match => match[0].replace(/\s+/gu, ' ')), aqChapters)
|
|
109
|
+
assertReadableBody('aq-zheng-zhuan', original)
|
|
110
|
+
assert.ok(original.indexOf('他們白跟一趟了。') < original.indexOf('About this digital edition'))
|
|
111
|
+
assert.match(original, /Creative Commons Attribution-ShareAlike 3\.0 Unported.*GNU FDL/u)
|
|
112
|
+
assert.match(original, /https:\/\/www\.creativecommons\.org\/licenses\/by-sa\/3\.0/u)
|
|
113
|
+
assert.match(original, /https:\/\/www\.gnu\.org\/copyleft\/fdl\.html/u)
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
for (const source of books) {
|
|
117
|
+
test(`real ${source.format.toUpperCase()} ${source.title}: body, selection safety, deduplicated reads and persisted progress`, async () => {
|
|
118
|
+
const storage = seededStorage()
|
|
119
|
+
const original = await storage.load()
|
|
120
|
+
const originalPassages = structuredClone([...storage.passages.entries()])
|
|
121
|
+
const store = new NovelStore(storage)
|
|
122
|
+
await store.ready
|
|
123
|
+
let restored
|
|
124
|
+
try {
|
|
125
|
+
const book = await store.importFile(asFile(source.file, await readFile(new URL(source.file, samples))))
|
|
126
|
+
assert.equal(book.format, source.format)
|
|
127
|
+
assert.ok(book.segmentCount > 1)
|
|
128
|
+
assert.equal(book.progress, 0)
|
|
129
|
+
assertReadableBody(source.id, await storedBody(storage, book))
|
|
130
|
+
if (source.id === 'aq-zheng-zhuan') {
|
|
131
|
+
const segments = await segmentsFor(storage, book)
|
|
132
|
+
assert.equal(segments[0].chapterTitle, '阿Q正傳')
|
|
133
|
+
const body = segments.map(segment => segment.text).join('\n')
|
|
134
|
+
for (const title of aqChapters) assert.ok(compact(body).includes(compact(title)), title)
|
|
135
|
+
}
|
|
136
|
+
assert.equal(store.getSettingsSnapshot().currentBookId, 'existing')
|
|
137
|
+
assert.equal(store.getSettingsSnapshot().mainTitle, '原来的标题')
|
|
138
|
+
assert.deepEqual(storage.books.get('existing'), original.books[0])
|
|
139
|
+
for (const [key, passage] of originalPassages) assert.deepEqual(storage.passages.get(key), passage)
|
|
140
|
+
|
|
141
|
+
await store.selectBook(book.id)
|
|
142
|
+
const [first, duplicate] = await Promise.all([store.claimPassage(`real-${source.id}`), store.claimPassage(`real-${source.id}`)])
|
|
143
|
+
assert.equal(first.kind, 'ready')
|
|
144
|
+
assert.equal(first.index, 0)
|
|
145
|
+
assert.ok(first.passage.text.trim())
|
|
146
|
+
assert.deepEqual(duplicate, first)
|
|
147
|
+
assert.deepEqual(await store.claimPassage(`real-${source.id}`), first, 'reopening must not consume another passage')
|
|
148
|
+
assert.equal(storage.books.get(book.id).progress, 1)
|
|
149
|
+
store.dispose()
|
|
150
|
+
|
|
151
|
+
restored = new NovelStore(storage)
|
|
152
|
+
await restored.ready
|
|
153
|
+
assert.equal(restored.getSettingsSnapshot().currentBookId, book.id)
|
|
154
|
+
assert.equal(restored.getSnapshot().books.find(item => item.id === book.id).progress, 1)
|
|
155
|
+
const next = await restored.claimPassage(`restored-${source.id}`)
|
|
156
|
+
assert.equal(next.kind, 'ready')
|
|
157
|
+
assert.equal(next.index, 1)
|
|
158
|
+
assert.equal(storage.books.get(book.id).progress, 2)
|
|
159
|
+
assert.deepEqual(storage.books.get('existing'), original.books[0])
|
|
160
|
+
for (const [key, passage] of originalPassages) assert.deepEqual(storage.passages.get(key), passage)
|
|
161
|
+
} finally {
|
|
162
|
+
store.dispose()
|
|
163
|
+
restored?.dispose()
|
|
164
|
+
}
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
test('canonical AQ Markdown retains the entire original official export byte-for-byte after its sole heading', async () => {
|
|
169
|
+
const source = byId('aq-zheng-zhuan')
|
|
170
|
+
const bytes = await readFile(new URL(source.file, samples))
|
|
171
|
+
const prefix = Buffer.from(source.derivation.prefix, 'utf8')
|
|
172
|
+
assert.deepEqual(bytes.subarray(0, prefix.length), prefix)
|
|
173
|
+
const original = bytes.subarray(prefix.length)
|
|
174
|
+
assert.equal(original.length, 68156)
|
|
175
|
+
assert.equal(sha256(original), '15a60f2d6e105c0869c4a11516eaba0d6726e6df68a91c40836dad51c1016b51')
|
|
176
|
+
const text = original.toString('utf8')
|
|
177
|
+
const storage = new MemoryStorage()
|
|
178
|
+
const store = new NovelStore(storage)
|
|
179
|
+
await store.ready
|
|
180
|
+
try {
|
|
181
|
+
const book = await store.importFile(asFile(source.file, bytes))
|
|
182
|
+
assert.equal(book.format, 'md')
|
|
183
|
+
const body = await storedBody(storage, book)
|
|
184
|
+
assertReadableBody(source.id, body)
|
|
185
|
+
for (const title of aqChapters) assert.ok(compact(body).includes(compact(title)), title)
|
|
186
|
+
assert.equal(compact(body), compact(text), 'all original exported text survives the Markdown import')
|
|
187
|
+
assert.equal((await storage.getSegment(book.id, 0)).chapterTitle, '阿Q正傳')
|
|
188
|
+
assert.match(body, /Creative Commons Attribution-ShareAlike 3\.0 Unported.*GNU FDL/u)
|
|
189
|
+
} finally {
|
|
190
|
+
store.dispose()
|
|
191
|
+
}
|
|
192
|
+
})
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { readFile } from 'node:fs/promises'
|
|
4
|
+
import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'
|
|
5
|
+
import { IndexedDbStorage } from '../src/persistence.js'
|
|
6
|
+
import { DEFAULT_SETTINGS, NovelStore } from '../src/store.js'
|
|
7
|
+
import { parseTextBook } from '../src/segments.js'
|
|
8
|
+
import { PG_NOTICE, hasProjectGutenbergReference } from '../src/pg-notice.js'
|
|
9
|
+
import { novelContent } from '../src/novel-content.js'
|
|
10
|
+
import { MemoryStorage } from './helpers/memory-storage.js'
|
|
11
|
+
|
|
12
|
+
const source = await readFile(new URL('../samples/ebooks/million-pound-bank-note-pg61522.txt', import.meta.url), 'utf8')
|
|
13
|
+
const pgSegments = parseTextBook(source).segments
|
|
14
|
+
const file = (name, text) => ({ name, arrayBuffer: async () => new TextEncoder().encode(text).buffer })
|
|
15
|
+
|
|
16
|
+
test('notice is exactly the licensed §1.E.1 statement, including ™', async () => {
|
|
17
|
+
const license = await readFile(new URL('../samples/ebooks/LICENSE.md', import.meta.url), 'utf8')
|
|
18
|
+
const statement = license.slice(license.indexOf(' This eBook'), license.indexOf('1.E.2.')).trim().replace(/\s+/gu, ' ')
|
|
19
|
+
assert.equal(PG_NOTICE, statement)
|
|
20
|
+
assert.match(PG_NOTICE, /Project Gutenberg™ License/u)
|
|
21
|
+
assert.equal(hasProjectGutenbergReference('The PROJECT\nGUTENBERG eBook'), true)
|
|
22
|
+
assert.equal(hasProjectGutenbergReference('阿Q正傳'), false)
|
|
23
|
+
assert.equal(hasProjectGutenbergReference('notProject Gutenbergish'), false)
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
test('real bundled PG default is detected without tagging AQ or title-based lookalikes', async () => {
|
|
27
|
+
const storage = new IndexedDbStorage(new IDBFactory(), IDBKeyRange)
|
|
28
|
+
const aq = await readFile(new URL('../samples/ebooks/aq-zheng-zhuan-wikisource.md', import.meta.url), 'utf8')
|
|
29
|
+
const store = new NovelStore(storage, { bundledBooks: [
|
|
30
|
+
{ id: 'million-pound-bank-note', title: '百萬英鎊', format: 'txt', createFile: () => file('default.txt', source) },
|
|
31
|
+
{ id: 'aq-zheng-zhuan', title: '阿Q正傳', format: 'md', createFile: () => file('aq.md', aq) },
|
|
32
|
+
{ id: 'unrelated', title: 'Project Gutenberg', format: 'txt', createFile: () => file('other.txt', 'Unrelated original text.') },
|
|
33
|
+
] })
|
|
34
|
+
try {
|
|
35
|
+
await store.ready
|
|
36
|
+
assert.equal(store.getSnapshot().error, null)
|
|
37
|
+
assert.equal((await store.claimPassage('pg')).projectGutenberg, true)
|
|
38
|
+
await store.selectBook('bundled:aq-zheng-zhuan')
|
|
39
|
+
assert.equal((await store.claimPassage('aq')).projectGutenberg, false)
|
|
40
|
+
await store.selectBook('bundled:unrelated')
|
|
41
|
+
assert.equal((await store.claimPassage('other')).projectGutenberg, false)
|
|
42
|
+
} finally { store.dispose() }
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
test('adopted legacy PG with arbitrary ID/title resumes using cached segment-zero provenance without migration', async () => {
|
|
46
|
+
const book = { id: 'old-random-import-42', title: 'Renamed by reader', format: 'txt', progress: 8, segmentCount: pgSegments.length, importedAt: 42 }
|
|
47
|
+
const storage = new MemoryStorage({ books: [book], settings: { ...DEFAULT_SETTINGS, currentBookId: book.id }, passages: { [book.id]: pgSegments } })
|
|
48
|
+
const indices = []
|
|
49
|
+
const getSegment = storage.getSegment.bind(storage)
|
|
50
|
+
storage.getSegment = async (id, index) => { indices.push(index); return getSegment(id, index) }
|
|
51
|
+
const store = new NovelStore(storage)
|
|
52
|
+
try {
|
|
53
|
+
await store.ready
|
|
54
|
+
assert.deepEqual(storage.books.get(book.id), book)
|
|
55
|
+
assert.equal(storage.reads, 0, 'hydration does not scan books or consume progress')
|
|
56
|
+
const first = await store.claimPassage('first')
|
|
57
|
+
assert.equal(first.projectGutenberg, true)
|
|
58
|
+
assert.equal(first.index, 8)
|
|
59
|
+
assert.equal(first.passage.text, pgSegments[8].text)
|
|
60
|
+
assert.equal(novelContent(first, true, key => key).projectGutenberg, true)
|
|
61
|
+
const next = await store.continuePassage('first')
|
|
62
|
+
assert.equal(next.projectGutenberg, true)
|
|
63
|
+
assert.deepEqual(indices, [8, 0, 9], 'header is loaded once; subsequent claims reuse provenance')
|
|
64
|
+
assert.deepEqual(storage.books.get(book.id), { ...book, progress: 10 }, 'only normal progress changes, not IDs, ownership or metadata')
|
|
65
|
+
assert.strictEqual(await store.claimPassage('first'), next)
|
|
66
|
+
assert.deepEqual(indices, [8, 0, 9], 'cached remount does not read again')
|
|
67
|
+
} finally { store.dispose() }
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
test('manual import of the identical PG TXT is detected despite arbitrary filename and no bundled identity', async () => {
|
|
71
|
+
const storage = new MemoryStorage()
|
|
72
|
+
const store = new NovelStore(storage)
|
|
73
|
+
try {
|
|
74
|
+
await store.ready
|
|
75
|
+
const imported = await store.importFile(file('reader-chosen-name.txt', source))
|
|
76
|
+
assert.equal(imported.bundledId, undefined)
|
|
77
|
+
const first = await store.claimPassage('import')
|
|
78
|
+
assert.equal(first.projectGutenberg, true)
|
|
79
|
+
assert.equal(first.passage.text, pgSegments[0].text)
|
|
80
|
+
assert.equal(storage.reads, 1, 'first claim reuses its segment-zero read')
|
|
81
|
+
assert.equal((await store.continuePassage('import')).projectGutenberg, true)
|
|
82
|
+
assert.equal(storage.reads, 2)
|
|
83
|
+
} finally { store.dispose() }
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
test('a canceled provenance read never publishes a passage or advances resumed progress', async () => {
|
|
87
|
+
const book = { id: 'legacy', title: 'Renamed', format: 'txt', progress: 2, segmentCount: 4 }
|
|
88
|
+
const storage = new MemoryStorage({ books: [book], settings: { ...DEFAULT_SETTINGS, currentBookId: book.id }, passages: { legacy: pgSegments.slice(0, 4) } })
|
|
89
|
+
let release, entered
|
|
90
|
+
const gate = new Promise(resolve => { release = resolve })
|
|
91
|
+
const started = new Promise(resolve => { entered = resolve })
|
|
92
|
+
const getSegment = storage.getSegment.bind(storage)
|
|
93
|
+
storage.getSegment = async (id, index) => {
|
|
94
|
+
if (index === 0) { entered(); await gate }
|
|
95
|
+
return getSegment(id, index)
|
|
96
|
+
}
|
|
97
|
+
const store = new NovelStore(storage)
|
|
98
|
+
try {
|
|
99
|
+
await store.ready
|
|
100
|
+
const reading = store.claimPassage('pending')
|
|
101
|
+
await started
|
|
102
|
+
const disabling = store.setOption('enabled', false)
|
|
103
|
+
release()
|
|
104
|
+
assert.equal((await reading).kind, 'empty')
|
|
105
|
+
await disabling
|
|
106
|
+
assert.equal(storage.books.get(book.id).progress, 2)
|
|
107
|
+
assert.equal(store.getPassageStatus(book.id, 'pending').kind, 'empty')
|
|
108
|
+
} finally { release(); store.dispose() }
|
|
109
|
+
})
|
package/test/release.test.js
CHANGED
|
@@ -10,7 +10,7 @@ test('public package identity matches the Host patch and browser module', async
|
|
|
10
10
|
const manifest = JSON.parse(await read('package.json'))
|
|
11
11
|
assert.equal(manifest.name, '@gongfpp/dsh-novel-fish')
|
|
12
12
|
assert.equal(manifest.repository.url, 'https://github.com/gongfpp/dsh-novel-fish.git')
|
|
13
|
-
assert.equal(manifest.engines.dsh, '>=0.2.1-rc.2
|
|
13
|
+
assert.equal(manifest.engines.dsh, '>=0.2.1-rc.2 <0.3.0-0')
|
|
14
14
|
assert.ok((await read('cordis.patch.yml')).includes(`name: '${manifest.name}'`))
|
|
15
15
|
assert.ok((await read('src/client.js')).includes(`const MODULE_ID = '${manifest.name}'`))
|
|
16
16
|
assert.ok((await read('lib/client.js')).includes(manifest.name))
|
|
@@ -19,13 +19,25 @@ test('public package identity matches the Host patch and browser module', async
|
|
|
19
19
|
}
|
|
20
20
|
})
|
|
21
21
|
|
|
22
|
-
test('host compatibility
|
|
22
|
+
test('host compatibility covers the whole 0.2.x line but not earlier work or 0.3', async () => {
|
|
23
23
|
const { engines } = JSON.parse(await read('package.json'))
|
|
24
24
|
// DSH preflight evaluates prereleases explicitly, unlike npm's default semver rules.
|
|
25
|
-
|
|
25
|
+
// A ceiling of the form `<=0.2.2-alpha.2` sorts below `0.2.2-rc.1`, which is how
|
|
26
|
+
// 1.0.0 locked out the rc hosts it was meant to serve; `<0.3.0-0` keeps every
|
|
27
|
+
// 0.2.x prerelease admissible and still rejects 0.3.0's own prereleases.
|
|
28
|
+
for (const version of [
|
|
29
|
+
'0.2.1-rc.2',
|
|
30
|
+
'0.2.1-rc.3',
|
|
31
|
+
'0.2.1-rc.4',
|
|
32
|
+
'0.2.1-rc.5',
|
|
33
|
+
'0.2.2-alpha.2',
|
|
34
|
+
'0.2.2-alpha.3',
|
|
35
|
+
'0.2.2-rc.1',
|
|
36
|
+
'0.2.2',
|
|
37
|
+
]) {
|
|
26
38
|
assert.equal(semver.satisfies(version, engines.dsh, { includePrerelease: true }), true, version)
|
|
27
39
|
}
|
|
28
|
-
for (const version of ['0.2.0', '0.2.1-alpha.5', '0.2.1-rc.1', '0.
|
|
40
|
+
for (const version of ['0.2.0', '0.2.1-alpha.5', '0.2.1-rc.1', '0.3.0-rc.1', '0.3.0', '1.0.0']) {
|
|
29
41
|
assert.equal(semver.satisfies(version, engines.dsh, { includePrerelease: true }), false, version)
|
|
30
42
|
}
|
|
31
43
|
})
|
|
@@ -62,9 +74,11 @@ test('市场索引保留固定提交来源、版本唯一和宿主兼容范围',
|
|
|
62
74
|
test('README local links resolve and installation contains no personal absolute path', async () => {
|
|
63
75
|
const readme = await read('README.md')
|
|
64
76
|
assert.doesNotMatch(readme, /\/Users\/|C:\\Users\\/u)
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
77
|
+
const manifest = JSON.parse(await read('package.json'))
|
|
78
|
+
// Source docs describe the version being built. The public index is appended
|
|
79
|
+
// only after release, when its immutable source SHA and timestamp are known.
|
|
80
|
+
assert.ok(readme.includes(`github:gongfpp/dsh-novel-fish#v${manifest.version}`), 'installation matches the release being built')
|
|
81
|
+
assert.ok(readme.includes(`@gongfpp/dsh-novel-fish@${manifest.version}`))
|
|
68
82
|
for (const match of readme.matchAll(/\]\(([^)]+)\)/gu)) {
|
|
69
83
|
const path = match[1].replace(/^<|>$/gu, '').split('#')[0]
|
|
70
84
|
if (!path || /^[a-z]+:/iu.test(path)) continue
|
package/test/segments.test.js
CHANGED
|
@@ -36,8 +36,8 @@ test('long text is split around target length without breaking Unicode code poin
|
|
|
36
36
|
assert.equal(segments.map(segment => segment.text).join(''), source)
|
|
37
37
|
})
|
|
38
38
|
|
|
39
|
-
test('paragraph boundaries take priority
|
|
40
|
-
assert.equal(DEFAULT_SEGMENT_LENGTH,
|
|
39
|
+
test('paragraph boundaries take priority within the default display-width budget', () => {
|
|
40
|
+
assert.equal(DEFAULT_SEGMENT_LENGTH, 800)
|
|
41
41
|
const segments = segmentChapters([{ title: '正文', text: `${'甲'.repeat(300)}。\n\n${'乙'.repeat(300)}。` }])
|
|
42
42
|
assert.equal(segments.length, 2)
|
|
43
43
|
assert.ok(segments.every(segment => [...segment.text].length < 600))
|
|
@@ -46,3 +46,137 @@ test('paragraph boundaries take priority and the default target is about 600 cha
|
|
|
46
46
|
test('empty plain text is rejected instead of importing an unreadable book', () => {
|
|
47
47
|
assert.throws(() => parseTextBook(' \n\n ', 'txt'), /没有可阅读的正文文本/u)
|
|
48
48
|
})
|
|
49
|
+
|
|
50
|
+
// Synthetic narrative fixtures, not quotations or claims about a real edition.
|
|
51
|
+
export const englishNarrative = 'When I reached the little office by the river, the clerk had already put away his books. "You must come again tomorrow," he said, looking from my muddy coat to the sealed envelope. I explained that the gentleman was leaving on the morning train, and that a delay of even one night might change everything. '
|
|
52
|
+
export const chineseNarrative = '天色已经暗了下来,街上的人却还没有散。他把车停在门口,抹去额上的汗,望了望远处亮着灯的窗口。“再等一会儿吧,”老人说,“也许他马上就回来了。”他没有回答,只把那封信仔细地放回衣袋里。'
|
|
53
|
+
export const narrativeCorpora = {
|
|
54
|
+
english: Array.from({ length: 36 }, (_, i) => i % 6 === 0 ? '"Not tonight," he replied.' : englishNarrative.repeat(1 + i % 5).trim()).join('\n\n'),
|
|
55
|
+
chinese: Array.from({ length: 36 }, (_, i) => i % 6 === 0 ? '“还早呢。”' : chineseNarrative.repeat(1 + i % 5)).join('\n\n'),
|
|
56
|
+
dialogue: Array.from({ length: 90 }, (_, i) => i % 2 ? '“你当真要走?”' : '“天亮以前,我就得赶到城门外。”').join('\n\n'),
|
|
57
|
+
}
|
|
58
|
+
const compact = text => text.replace(/\s/gu, '')
|
|
59
|
+
const passages = (text, target) => segmentChapters([{ title: 'Sample', text }], target).map(segment => segment.text)
|
|
60
|
+
function displayUnits(text) {
|
|
61
|
+
return Array.from(new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text), ({ segment }) => {
|
|
62
|
+
if (segment === '\n') return 40
|
|
63
|
+
if (segment === '\t') return 4
|
|
64
|
+
return /[\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
|
|
65
|
+
}).reduce((sum, value) => sum + value, 0)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
for (const [language, text] of Object.entries(narrativeCorpora)) {
|
|
69
|
+
test(`${language} narrative balances short dialogue and long paragraphs without losing body text`, () => {
|
|
70
|
+
const result = passages(text)
|
|
71
|
+
assert.ok(result.length > 2, 'a complete chapter must not become one huge passage')
|
|
72
|
+
assert.equal(compact(result.join('')), compact(text))
|
|
73
|
+
assert.ok(result.every(part => displayUnits(part) <= 1000))
|
|
74
|
+
assert.ok(result.every(part => displayUnits(part) >= 400), 'avoid isolated short paragraphs and short tails')
|
|
75
|
+
if (language === 'english') {
|
|
76
|
+
assert.ok(result.length < 45, 'do not require a click for each short English fragment')
|
|
77
|
+
assert.ok(result.every(part => (part.match(/\b[A-Za-z]+\b/gu) ?? []).length >= 60))
|
|
78
|
+
}
|
|
79
|
+
if (language === 'chinese') assert.ok(result.every(part => [...part].length <= 500))
|
|
80
|
+
if (language === 'dialogue') assert.ok(result.every(part => part.split('\n').length <= 22), 'blank lines count toward the visible reading budget')
|
|
81
|
+
})
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
test('targetLength means a soft half-width budget with a 1.25x hard limit, not raw characters', () => {
|
|
85
|
+
const latin = passages('a'.repeat(4000))
|
|
86
|
+
const han = passages('甲'.repeat(2000))
|
|
87
|
+
assert.equal(latin.length, han.length)
|
|
88
|
+
assert.deepEqual(latin.map(part => displayUnits(part)), han.map(part => displayUnits(part)))
|
|
89
|
+
assert.ok(latin.every(part => [...part].length === DEFAULT_SEGMENT_LENGTH))
|
|
90
|
+
for (const target of [1, 2, 7, 31, 600]) {
|
|
91
|
+
assert.ok(passages('abcd'.repeat(1800), target).every(part => displayUnits(part) <= Math.floor(target * 1.25)))
|
|
92
|
+
}
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
test('sentence and quotation boundaries preserve exact intra-paragraph spacing', () => {
|
|
96
|
+
for (const text of [englishNarrative.repeat(14).trim(), chineseNarrative.repeat(30)]) {
|
|
97
|
+
const result = passages(text)
|
|
98
|
+
assert.equal(compact(result.join('')), compact(text))
|
|
99
|
+
assert.ok(result.every(part => text.includes(part)), 'never insert spaces into Chinese prose or rewrite English spacing')
|
|
100
|
+
assert.ok(result.slice(0, -1).every(part => /[.!?。!?][”’"'」』】))]?$/u.test(part)))
|
|
101
|
+
assert.ok(result.every(part => !/^[”’」』】))]/u.test(part)), 'closing quotes stay with preceding sentences')
|
|
102
|
+
}
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
test('punctuation-free English splits at complete words unless one token exceeds the hard cap', () => {
|
|
106
|
+
const words = Array.from({ length: 1100 }, (_, i) => `word${i}`)
|
|
107
|
+
const result = passages(words.join(' '), 100)
|
|
108
|
+
assert.deepEqual(result.join(' ').split(/\s+/u), words)
|
|
109
|
+
assert.ok(result.every(part => displayUnits(part) <= 125))
|
|
110
|
+
const hugeWord = 'pneumonoultramicroscopic'.repeat(500)
|
|
111
|
+
assert.equal(passages(hugeWord, 100).join(''), hugeWord)
|
|
112
|
+
// A long but still fitting word cannot be split just to fill the target.
|
|
113
|
+
for (const [prefix, word] of [['a'.repeat(20), 'b'.repeat(980)], ['a'.repeat(300), 'b'.repeat(800)], ['a'.repeat(990), 'b'.repeat(80)]]) {
|
|
114
|
+
assert.deepEqual(passages(`${prefix} ${word}`), [prefix, word])
|
|
115
|
+
}
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
test('commas are a fallback after sentences and do not create unbounded Chinese clauses', () => {
|
|
119
|
+
const clause = '他把信放回衣袋里,又在门前等了一阵,街上渐渐没有了行人,'
|
|
120
|
+
const text = clause.repeat(60)
|
|
121
|
+
const result = passages(text, 200)
|
|
122
|
+
assert.equal(result.join(''), text)
|
|
123
|
+
assert.ok(result.every(part => displayUnits(part) <= 250))
|
|
124
|
+
assert.ok(result.slice(0, -1).every(part => part.endsWith(',')))
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
test('a short final paragraph is balanced with its predecessor, but never with the next chapter', () => {
|
|
128
|
+
const text = `${'甲'.repeat(390)}。\n\n最后一封信。`
|
|
129
|
+
const result = passages(text)
|
|
130
|
+
assert.equal(result.length, 1)
|
|
131
|
+
const split = passages(`${'alpha '.repeat(165)}${'bravo '.repeat(14)}`)
|
|
132
|
+
assert.equal(split.length, 2)
|
|
133
|
+
assert.ok(split.every(part => part.length >= 400))
|
|
134
|
+
const chapters = segmentChapters([{ title: 'Chapter I', text }, { title: 'Chapter II', text: 'Next day.' }])
|
|
135
|
+
assert.deepEqual(chapters.map(part => part.chapterTitle), ['Chapter I', 'Chapter II'])
|
|
136
|
+
assert.deepEqual(chapters.map(part => part.chapterIndex), [0, 1])
|
|
137
|
+
assert.equal(chapters[1].text, 'Next day.')
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
test('TXT Roman numeral headings are chapter boundaries, not prose or merged labels', () => {
|
|
141
|
+
const book = parseTextBook('Chapter I\n\nFirst short passage.\n\nChapter II The visitor\n\nAnother short passage.\n\nChapter in the old house was unfinished.', 'txt')
|
|
142
|
+
assert.deepEqual(book.chapters.map(chapter => chapter.title), ['Chapter I', 'Chapter II The visitor'])
|
|
143
|
+
assert.equal(book.segments.length, 2)
|
|
144
|
+
assert.match(book.segments[1].text, /Chapter in the old house/u)
|
|
145
|
+
})
|
|
146
|
+
|
|
147
|
+
test('grapheme clusters, flags, combining accents and ZWJ families survive every cut', () => {
|
|
148
|
+
const tokens = ['👨👩👧👦', '🇨🇳', 'e\u0301', '👍🏽', '猫']
|
|
149
|
+
const text = tokens.join('').repeat(300)
|
|
150
|
+
const expected = Array.from(new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text), item => item.segment)
|
|
151
|
+
const result = passages(text, 7)
|
|
152
|
+
assert.equal(result.join(''), text)
|
|
153
|
+
assert.deepEqual(result.flatMap(part => Array.from(new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(part), item => item.segment)), expected)
|
|
154
|
+
assert.ok(result.every(part => displayUnits(part) <= 8))
|
|
155
|
+
assert.equal(passages('👨👩👧👦', 1)[0], '👨👩👧👦', 'one indivisible grapheme wins over a tiny budget')
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
test('fallback without Intl.Segmenter remains Unicode-safe and splits Latin full stops', t => {
|
|
159
|
+
const original = Intl.Segmenter
|
|
160
|
+
Intl.Segmenter = undefined
|
|
161
|
+
t.after(() => { Intl.Segmenter = original })
|
|
162
|
+
const source = `Mr. Green waited. Then he went home. ${'👨👩👧👦🇨🇳e\u0301👍🏽'.repeat(180)}`
|
|
163
|
+
const result = passages(source, 45)
|
|
164
|
+
assert.equal(compact(result.join('')), compact(source))
|
|
165
|
+
assert.ok(result.every(part => !/^[\p{Mark}\p{Emoji_Modifier}\u200d]/u.test(part) && !part.endsWith('\u200d')))
|
|
166
|
+
const prose = passages('He waited at the door. '.repeat(40).trim(), 80)
|
|
167
|
+
assert.ok(prose.every(part => part.endsWith('.')))
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
test('large punctuation-free chapters and newline-only tails terminate within bounded passages', { timeout: 4000 }, () => {
|
|
171
|
+
for (const source of ['字'.repeat(120000), 'x'.repeat(120000), 'word\n'.repeat(6000), `${'甲'.repeat(900)}\n\n `]) {
|
|
172
|
+
const result = passages(source)
|
|
173
|
+
assert.equal(compact(result.join('')), compact(source))
|
|
174
|
+
assert.ok(result.every(part => part.length && displayUnits(part) <= 1000))
|
|
175
|
+
}
|
|
176
|
+
})
|
|
177
|
+
|
|
178
|
+
test('invalid targets reject immediately rather than causing an infinite split loop', () => {
|
|
179
|
+
for (const value of [0, -1, 0.5, Infinity, NaN, '600', Number.MAX_SAFE_INTEGER + 1]) {
|
|
180
|
+
assert.throws(() => passages('正文', value), RangeError)
|
|
181
|
+
}
|
|
182
|
+
})
|