@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/scripts/build.mjs DELETED
@@ -1,69 +0,0 @@
1
- import { build } from 'esbuild'
2
- import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises'
3
- import { fileURLToPath } from 'node:url'
4
- import { dirname, resolve, join } from 'node:path'
5
- import { createRequire } from 'node:module'
6
-
7
- const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
8
- const output = resolve(root, 'lib/client.js')
9
- await mkdir(dirname(output), { recursive: true })
10
- const result = await build({
11
- absWorkingDir: root,
12
- entryPoints: [resolve(root, 'src/client.js')],
13
- bundle: true,
14
- platform: 'browser',
15
- format: 'iife',
16
- target: ['chrome120'],
17
- outfile: output,
18
- sourcemap: false,
19
- metafile: true,
20
- legalComments: 'eof',
21
- logLevel: 'info',
22
- define: { 'process.env.NODE_ENV': '"production"' },
23
- })
24
- await writeFile(output, (await readFile(output, 'utf8')).replace(/[\t ]+$/gmu, ''))
25
-
26
- const packages = new Map()
27
- for (const input of Object.keys(result.metafile.inputs)) {
28
- if (!input.includes('node_modules/')) continue
29
- let directory = dirname(resolve(root, input))
30
- while (directory.startsWith(join(root, 'node_modules'))) {
31
- const files = await readdir(directory)
32
- if (files.includes('package.json')) {
33
- const manifest = JSON.parse(await readFile(join(directory, 'package.json'), 'utf8'))
34
- const key = `${manifest.name}@${manifest.version}`
35
- if (!packages.has(key)) {
36
- const licenses = files.filter(name => /^(?:licen[cs]e|copying)(?:[.-]|$)/iu.test(name))
37
- const text = licenses.length
38
- ? (await Promise.all(licenses.map(name => readFile(join(directory, name), 'utf8')))).join('\n\n')
39
- : await readFile(join(root, 'scripts/licenses', `${manifest.name}.txt`), 'utf8')
40
- packages.set(key, `${key}\nLicense declaration: ${JSON.stringify(manifest.license)}\n\n${text.trim().replace(/[\t ]+$/gmu, '')}`)
41
- }
42
- break
43
- }
44
- directory = dirname(directory)
45
- }
46
- }
47
- // JSZip's browser entry is prebundled: esbuild cannot see its nested libraries.
48
- // Keep their original notices as well; do not mistake metafile inputs for the full license graph.
49
- const require = createRequire(import.meta.url)
50
- const zipRequire = createRequire(require.resolve('jszip/package.json'))
51
- const lieRequire = createRequire(zipRequire.resolve('lie/package.json'))
52
- for (const manifestPath of [
53
- zipRequire.resolve('pako/package.json'),
54
- zipRequire.resolve('lie/package.json'),
55
- zipRequire.resolve('setimmediate/package.json'),
56
- lieRequire.resolve('immediate/package.json'),
57
- ]) {
58
- const directory = dirname(manifestPath)
59
- const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))
60
- const names = (await readdir(directory)).filter(name => /^(?:licen[cs]e|copying)(?:[.-]|$)/iu.test(name))
61
- if (!names.length) throw new Error(`Missing bundled license: ${manifest.name}`)
62
- const texts = await Promise.all(names.map(name => readFile(join(directory, name), 'utf8')))
63
- if (manifest.name === 'pako') texts.push(await readFile(join(directory, 'lib/zlib/README'), 'utf8'))
64
- const key = `${manifest.name}@${manifest.version}`
65
- packages.set(key, `${key}\nBundled inside JSZip's browser distribution.\nLicense declaration: ${JSON.stringify(manifest.license)}\n\n${texts.join('\n\n').trim().replace(/[\t ]+$/gmu, '')}`)
66
- }
67
- const notices = ['Bundled browser dependencies (generated by scripts/build.mjs).', ...[...packages].sort(([a], [b]) => a.localeCompare(b)).map(([, text]) => text)]
68
- await writeFile(join(root, 'THIRD-PARTY-NOTICES.txt'), `${notices.join('\n\n' + '='.repeat(72) + '\n\n')}\n`)
69
- console.log(`Bundled licenses: ${packages.size}`)
@@ -1,246 +0,0 @@
1
- #!/usr/bin/env node
2
- // Read-only, offline probe of an installed DSH build. No server or user profile.
3
- // Usage: node scripts/check-host-contracts.mjs /absolute/path/to/@deepseek-ai/dsh
4
- import assert from 'node:assert/strict'
5
- import { existsSync } from 'node:fs'
6
- import { readFile, readdir } from 'node:fs/promises'
7
- import { isAbsolute, join, dirname } from 'node:path'
8
- import { fileURLToPath } from 'node:url'
9
- import vm from 'node:vm'
10
- import { build } from 'esbuild'
11
- import { JSDOM, VirtualConsole } from 'jsdom'
12
- import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'
13
-
14
- const project = fileURLToPath(new URL('../', import.meta.url))
15
- const host = process.argv[2] ?? process.env.HOST_ROOT
16
- const report = { hostVersion: null, checks: [], claims: null,
17
- claimsMeaning: 'Observed book progress after an untrusted click, not claimPassage invocation count.', limitations: [
18
- 'JSDOM, not a browser: no layout, animation, focus or trusted-user-event proof.',
19
- 'Private host exports are exposed only in memory; host boot/apply and full UI renderer are not started.',
20
- 'Identity ancestors and plugin-manager slot declaration are checked statically; small mounting/context facades are supplied by this probe.',
21
- 'Tool/Bash rows and the plugin-manager page are statically checked, not rendered; settings menus/modal are closed.',
22
- 'Plugin is built in memory from current src/client.js; lib/client.js freshness is not checked.',
23
- 'Only the supplied installation is tested; this is not proof for other or future versions.',
24
- ] }
25
- const check = (name, detail) => report.checks.push({ name, detail })
26
- const read = path => readFile(path, 'utf8')
27
- let dom
28
- try {
29
- assert.ok(host && isAbsolute(host), 'Pass an absolute DSH installation path (or HOST_ROOT).')
30
- report.hostVersion = JSON.parse(await read(join(host, 'package.json'))).version
31
- // Global installs nest the client packages under the dsh package, while a plain
32
- // `npm install @deepseek-ai/dsh` hoists them next to it. Accept both layouts.
33
- const siblingScope = dirname(host)
34
- const packageDir = name => {
35
- const nested = join(host, 'node_modules/@deepseek-ai', `dsh-${name}`)
36
- return existsSync(nested) ? nested : join(siblingScope, `dsh-${name}`)
37
- }
38
- const client = name => read(join(packageDir(name), 'lib/client.js'))
39
- const [chat, tool, conversation, manager] = await Promise.all([
40
- client('client-ui-chat'), client('client-ui-tool'), client('client-ui-conversation'), client('client-ui-plugin-manager'),
41
- ])
42
- for (const [source, markers] of [[chat, ['data-chat-node-key', 'data-chat-flow-kind']],
43
- [tool, ['data-chat-call-id', 'data-tool', 'data-variant', 'data-sample']], [conversation, ['data-conversation-session']]]) {
44
- for (const marker of markers) assert.ok(source.includes(`"${marker}"`), `Missing host DOM marker: ${marker}`)
45
- }
46
- const config = manager.match(/"plugins\.bundle\.config":\s*\{\s*kind:\s*"(\w+)",\s*scope:\s*"(\w+)"/)
47
- assert.ok(config, 'Missing plugins.bundle.config declaration')
48
- assert.equal(config[1], 'keyed')
49
- assert.match(manager, /renderSlot\("plugins\.bundle\.config",\s*\{\s*view:\s*"page"\s*\},\s*\{\s*entryKey:\s*pkg\.name/)
50
- check('static host markers and bundle-config seat', 'chat/tool/conversation markers; keyed config rendered by package name with view=page')
51
-
52
- // Built-in modules live in the shipped web shell, not separate npm packages.
53
- const assets = join(packageDir('web-frontend'), 'dist/assets')
54
- const candidates = (await readdir(assets)).filter(name => /^index-.*\.js$/.test(name))
55
- let entry, frontend, registry
56
- for (const candidate of candidates) {
57
- const source = await read(join(assets, candidate))
58
- const match = source.match(/function\s+([\w$]+)\(\)\s*\{\s*return\s*\{\s*react:/)
59
- if (match && source.includes('"@deepseek-ai/dsh-client-ui-primitives"')) {
60
- entry = join(assets, candidate); frontend = source; registry = match[1]; break
61
- }
62
- }
63
- assert.ok(registry, 'Cannot locate the shipped web static-module registry; probe needs an update')
64
- // Disable only the final application boot block, never component/module code.
65
- const boot = /try\s*\{\s*const\s+[\w$]+\s*=\s*document\.getElementById\("root"\)/
66
- assert.ok(boot.test(frontend), 'Cannot isolate web application boot; refusing to execute shell')
67
- frontend = frontend.replace(boot, match => `if (false) ${match}`)
68
- const errors = []
69
- const virtualConsole = new VirtualConsole()
70
- virtualConsole.on('jsdomError', error => errors.push(error.message))
71
- dom = new JSDOM('<!doctype html><html><head></head><body></body></html>', {
72
- url: 'http://host-contract.invalid/', runScripts: 'outside-only', pretendToBeVisual: true, virtualConsole,
73
- })
74
- Object.assign(dom.window, {
75
- TextEncoder, TextDecoder, indexedDB: new IDBFactory(), IDBKeyRange,
76
- fetch: () => { throw new Error('Network is forbidden in host-contract probe') },
77
- console: { ...console, error: error => { if (error?.message !== 'web app: missing #root') errors.push(String(error)) } },
78
- })
79
- const bundled = await build({ stdin: {
80
- contents: `${frontend}\nglobalThis.__hostContracts = ${registry}();`, resolveDir: dirname(entry), sourcefile: entry,
81
- }, bundle: true, write: false, format: 'iife', logLevel: 'silent' })
82
- vm.runInContext(bundled.outputFiles[0].text, dom.getInternalVMContext(), { filename: entry, timeout: 15000 })
83
- const modules = dom.window.__hostContracts
84
- const React = modules.react, h = React.createElement
85
- const primitives = modules['@deepseek-ai/dsh-client-ui-primitives']
86
- for (const name of ['DisclosureRow', 'TextShimmer', 'Switch', 'Button', 'Input', 'Menu', 'Modal', 'IconChevronDownOutlineRegular']) {
87
- assert.ok(primitives[name], `Missing real primitive ${name}`)
88
- }
89
- const core = new modules['@deepseek-ai/dsh-client-ui-slots'].SlotCore()
90
- const disposers = [], waiting = new Map()
91
- const register = (options, component) => {
92
- const off = core.register(options, component)
93
- disposers.push(off)
94
- for (const [name, callback] of waiting) if (core.spec(name)) { waiting.delete(name); callback() }
95
- return off
96
- }
97
- const ctx = {
98
- slots: { register, registerFactory: (...args) => { const off = core.registerFactory(...args); disposers.push(off); return off },
99
- inject: (name, callback) => core.spec(name) ? callback() : waiting.set(name, callback) },
100
- effect: callback => { const off = callback(); if (typeof off === 'function') disposers.push(off) },
101
- locale: { register: () => () => {}, bind: () => key => key },
102
- }
103
- // These two outer seats belong to much larger application trees. Their declarations
104
- // are checked in the original builds; all subsequent registrations use real SlotCore.
105
- assert.match(chat, /"conversation\.chat\.node":\s*\{\s*kind:\s*"keyed",\s*scope:\s*"session"/)
106
- register({ name: 'root', children: {
107
- 'conversation.chat.node': { kind: 'keyed', scope: 'session' },
108
- 'plugins.bundle.config': { kind: config[1], scope: config[2] },
109
- } }, () => null)
110
- const capture = (source, filename, expose = '') => {
111
- let definition
112
- dom.window.__ModuleLoader__ = { load: value => { definition = value } }
113
- if (expose) {
114
- assert.equal(source.split('return module.exports;').length, 2, 'Unknown host factory return shape')
115
- source = source.replace('return module.exports;', `module.exports.__probe = { ${expose} }; return module.exports;`)
116
- }
117
- vm.runInContext(source, dom.getInternalVMContext(), { filename, timeout: 10000 })
118
- assert.ok(definition?.factory, `No module factory captured from ${filename}`)
119
- const require = name => {
120
- assert.ok(modules[name], `Unexpected host import: ${name}`)
121
- return modules[name]
122
- }
123
- require.asset = path => `http://host-contract.invalid/assets/${path}` // CSS only; never fetched
124
- return definition.factory(require)
125
- }
126
- const hostChat = capture(chat, 'host-chat-client.js', 'registerChatNodeRenderers, ReasoningRow')
127
- hostChat.__probe.registerChatNodeRenderers(ctx, {}, {})
128
- assert.equal(core.spec('conversation.chat.reasoning.body')?.kind, 'single')
129
- assert.ok(core.factory('conversation.chat.reasoning.content'))
130
- const originalBody = core.entriesOfSlot('conversation.chat.reasoning.body')[0]
131
- const plugin = await build({ entryPoints: [join(project, 'src/client.js')], bundle: true, write: false,
132
- format: 'iife', logLevel: 'silent' })
133
- capture(plugin.outputFiles[0].text, 'novel-client-source.js').apply(ctx)
134
- const body = core.entriesOfSlot('conversation.chat.reasoning.body')[0]
135
- assert.notEqual(body, originalBody, 'Plugin body must shadow, not replace/delete, host body')
136
- assert.ok(core.entries('conversation.chat.reasoning.body').includes(originalBody))
137
- const settings = core.entriesOfSlot('plugins.bundle.config').find(entry => entry.options.key === '@gongfpp/dsh-novel-fish')
138
- assert.ok(settings)
139
- check('real SlotCore registrations', 'host registerChatNodeRenderers + plugin apply; body priority shadowing, content Factory and package-keyed settings')
140
-
141
- const injected = settings.inject()
142
- const state = injected.hooks.novelState
143
- await new Promise((resolve, reject) => {
144
- const timer = setTimeout(() => { off(); reject(new Error('IndexedDB hydration timed out')) }, 3000)
145
- const ready = () => { if (state.getSnapshot().hydrated) { clearTimeout(timer); off(); resolve() } }
146
- const off = state.subscribe(ready); ready()
147
- })
148
- assert.equal(state.getSnapshot().error, null)
149
- await injected.onSetOption('mainTitle', 'Contract title')
150
- await injected.onSetOption('extraTitle', 'Contract summary')
151
- await injected.onSetOption('enabled', false)
152
- const book = await injected.onImportFile({ name: 'contract.txt', arrayBuffer: async () => new TextEncoder().encode('Contract novel passage.').buffer })
153
- await injected.onSelectBook(book.id)
154
- const hooks = sources => Object.fromEntries(Object.entries(sources).map(([key, source]) => [
155
- modules['@deepseek-ai/dsh-client-ui-slots'].standardHookPropName(key),
156
- select => select(React.useSyncExternalStore(source.subscribe, source.getSnapshot)),
157
- ]))
158
- const t = key => key
159
- const slotCalls = []
160
- const renderFactorySlot = (name, props) => {
161
- slotCalls.push({ name, ...props })
162
- const factory = core.factory(name)
163
- assert.ok(factory, `Unknown Factory ${name}`)
164
- return h(factory.component, { ...props, t })
165
- }
166
- function ReasoningProbe() {
167
- const [expanded, setExpanded] = React.useState(false)
168
- return h(hostChat.__probe.ReasoningRow, {
169
- text: 'Native summary\n\nNative reasoning', running: true, t,
170
- usePresentation: select => select({ settledReasoningPreview: true }),
171
- useDisclosure: () => ({ expanded, toggle: () => setExpanded(value => !value) }),
172
- renderSlot: (name, props) => {
173
- assert.equal(name, 'conversation.chat.reasoning.body')
174
- const values = body.inject()
175
- return h(body.component, { ...props, sessionId: 'probe-session', ...hooks(values.hooks), renderFactorySlot, t })
176
- },
177
- })
178
- }
179
- const mount = dom.window.document.createElement('main')
180
- dom.window.document.body.append(mount)
181
- const root = modules['react-dom/client'].createRoot(mount)
182
- const flush = callback => modules['react-dom'].flushSync(callback)
183
- const render = () => flush(() => root.render(h(React.Fragment, null,
184
- h('div', { 'data-conversation-session': 'probe-session' },
185
- h('div', { 'data-chat-flow-kind': 'assistant-step', 'data-chat-node-key': 'probe-node' }, h(ReasoningProbe))),
186
- h(settings.component, { ...injected, ...hooks(injected.hooks), t, view: 'page' }),
187
- )))
188
- render()
189
- await new Promise(resolve => setTimeout(resolve, 25))
190
- const header = mount.querySelector('[data-disclosure-row]')
191
- assert.ok(header)
192
- assert.equal(header.getAttribute('role'), 'button')
193
- assert.equal(header.getAttribute('aria-expanded'), 'false')
194
- const nativeNodes = [...header.querySelectorAll('*')]
195
- const glyphs = [...header.querySelectorAll('svg')]
196
- const nativeGlyphs = glyphs.map(node => node.outerHTML)
197
- assert.ok(glyphs.length > 0)
198
- await injected.onSetOption('enabled', true)
199
- await new Promise(resolve => setTimeout(resolve, 25))
200
- assert.deepEqual([...header.querySelectorAll('*')], nativeNodes, 'Adapter must preserve native elements')
201
- assert.deepEqual(glyphs.map(node => node.outerHTML), nativeGlyphs, 'Adapter must not change native SVGs')
202
- assert.ok(header.textContent.includes('Contract title'))
203
- assert.ok(header.textContent.includes('Contract summary'))
204
- assert.deepEqual([...header.querySelectorAll('[data-shimmer-text]')].map(el => el.getAttribute('data-shimmer-text')), ['Contract title', 'Contract summary'])
205
- assert.equal(mount.querySelectorAll('[data-novel-append]').length, 0)
206
- check('real ReasoningRow / DisclosureRow / TextShimmer', 'plugin changes both native text and shimmer layers on actual shipped components; native SVGs remain')
207
- // This event is intentionally untrusted: it opens React's host row but must never claim a passage.
208
- flush(() => header.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })))
209
- await new Promise(resolve => setTimeout(resolve, 25))
210
- assert.equal(header.getAttribute('aria-expanded'), 'true')
211
- assert.ok(slotCalls.some(call => call.name === 'conversation.chat.reasoning.content' && call.text === 'Native summary\n\nNative reasoning' && call.running === true))
212
- assert.ok(mount.querySelector('[data-novel-original]').textContent.includes('Native reasoning'))
213
- report.claims = state.getSnapshot().books.find(item => item.id === book.id).progress
214
- assert.equal(report.claims, 0, 'Untrusted DOM click must not advance book progress')
215
- check('untrusted-event guard', 'actual host click expands the row but imported in-memory book progress stays at zero; no trusted input is simulated')
216
- assert.ok(mount.querySelector('[data-novel-settings] button'))
217
- assert.ok(mount.querySelector('[data-novel-settings] input[type="file"]'))
218
- check('real body Factory props and settings primitives', 'host row passes text/running; plugin calls actual MarkdownText Factory; settings mounts with real controls and memory IndexedDB')
219
- await injected.onSetOption('enabled', false)
220
- await new Promise(resolve => setTimeout(resolve, 25))
221
- assert.ok(header.textContent.includes('message.think'), 'Disabling must restore native title')
222
- assert.equal(mount.querySelector('[data-novel-target]'), null)
223
- check('restore on disable', 'native title restored and adapter target marker removed')
224
- // The adapter keeps the native row and only rewrites its text, so it depends on the
225
- // shipped title layers, disclosure row and folding anchors staying put.
226
- const anchors = {
227
- chat: { source: chat, markers: ['data-chat-flow-key', 'data-turn-process-member', 'data-turn-process-hidden', 'data-shimmer-decoration'] },
228
- conversation: { source: conversation, markers: ['data-conversation-session'] },
229
- shell: { source: frontend, markers: ['data-shimmer-text', 'data-disclosure-row'] },
230
- }
231
- for (const [name, { source, markers }] of Object.entries(anchors)) {
232
- for (const marker of markers) assert.ok(source.includes(`"${marker}"`), `Missing ${name} adapter anchor: ${marker}`)
233
- }
234
- check('adapter anchors for title layers and fold state', 'shimmer text/decoration, disclosure row, session identity and turn-process fold markers still ship; ambient DOM rescan has a contract to rescan')
235
- flush(() => root.unmount())
236
- for (const dispose of disposers.reverse()) dispose()
237
- assert.deepEqual(errors, [], 'Unexpected host/JSDOM runtime errors')
238
- report.ok = true
239
- } catch (error) {
240
- report.ok = false
241
- report.error = error.stack ?? String(error)
242
- process.exitCode = 1
243
- } finally {
244
- dom?.window.close()
245
- console.log(JSON.stringify(report, null, 2))
246
- }
@@ -1,28 +0,0 @@
1
- path-webpack 0.0.3
2
- Author: fchasen@gmail.com
3
- Published package license: MIT
4
- Repository: https://github.com/fchasen/path-webpack
5
-
6
- The package README identifies its source as Node.js v7.0.0 lib/path.js.
7
- Source: https://github.com/nodejs/node/blob/v7.0.0/lib/path.js
8
- License: https://github.com/nodejs/node/blob/v7.0.0/LICENSE
9
-
10
- Copyright Node.js contributors. All rights reserved.
11
-
12
- Permission is hereby granted, free of charge, to any person obtaining a copy
13
- of this software and associated documentation files (the "Software"), to
14
- deal in the Software without restriction, including without limitation the
15
- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
16
- sell copies of the Software, and to permit persons to whom the Software is
17
- furnished to do so, subject to the following conditions:
18
-
19
- The above copyright notice and this permission notice shall be included in
20
- all copies or substantial portions of the Software.
21
-
22
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27
- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
28
- IN THE SOFTWARE.
@@ -1,253 +0,0 @@
1
- import { passageSnapshotKey } from './store.js'
2
- import { NOVEL_STYLE, SEPARATOR_STYLE, novelContent } from './novel-content.js'
3
-
4
- const THOUGHT = '[data-chat-flow-kind="assistant-step"] [data-variant="think"]'
5
- const TOOL = '[data-chat-call-id] [data-tool], [data-chat-call-id] [data-sample="bash"]'
6
- const REGIONS = `${THOUGHT}, ${TOOL}`
7
- const EMPTY = Object.freeze({ kind: 'empty' })
8
-
9
- /** DSH 0.2.1 窄适配:保留原生控件和正文,只改标题文字并追加本地纯文本。 */
10
- export function registerChatAdapter(ctx, store, React, locale) {
11
- const t = ctx.locale?.bind(locale) ?? (key => key)
12
- ctx.slots.inject('conversation.chat.reasoning.body', () => ctx.slots.register({
13
- name: 'conversation.chat.reasoning.body', priority: -10, locale,
14
- inject: () => ({ hooks: { novelSettings: store.settingsSource, novelPassages: store.passageSource } }),
15
- }, createBody(React)))
16
-
17
- ctx.effect(() => {
18
- const decorated = new Map()
19
- const pending = new Map()
20
- const view = document.defaultView
21
- let disposed = false
22
-
23
- const restore = root => {
24
- const record = decorated.get(root)
25
- if (!record) return
26
- for (const [node, text] of record.texts) restoreText(node, text)
27
- record.append?.remove()
28
- root.removeAttribute('data-novel-target')
29
- decorated.delete(root)
30
- }
31
- const refresh = () => {
32
- const settings = store.getSettingsSnapshot()
33
- for (const [toggle, intent] of pending) {
34
- const id = identityOf(intent.root)
35
- if (!toggle.isConnected || !settings.enabled || settings.currentBookId !== intent.bookId
36
- || !isTarget(settings, id) || readingKey(id) !== intent.key || store.cacheGeneration !== intent.generation) {
37
- if (intent.frame !== null) view.cancelAnimationFrame(intent.frame)
38
- pending.delete(toggle)
39
- }
40
- }
41
- for (const root of decorated.keys()) {
42
- if (!root.isConnected || !settings.enabled || !isTarget(settings, identityOf(root))) restore(root)
43
- }
44
- for (const root of document.querySelectorAll(REGIONS)) {
45
- const id = identityOf(root)
46
- const header = headerOf(root)
47
- if (!header || !settings.enabled || !isTarget(settings, id)) continue
48
- let record = decorated.get(root)
49
- if (!record || record.header !== header) {
50
- restore(root)
51
- record = { header, texts: new Map(), append: null, signature: null }
52
- decorated.set(root, record)
53
- root.setAttribute('data-novel-target', '')
54
- }
55
- const desired = new Map()
56
- // 原生基础层和 shimmer 高亮层保持同一文字,不改变其样式、SVG或身份。
57
- const content = [...header.children].find(child => child.querySelector('[data-shimmer-decoration]'))
58
- const layers = [content?.firstElementChild, content?.querySelector('[inert]')?.firstElementChild?.firstElementChild]
59
- for (const layer of layers) {
60
- const title = layer?.firstElementChild
61
- if (!title) continue
62
- collectText(title, settings.mainTitle.trim(), desired)
63
- const separator = title.nextElementSibling
64
- if (separator?.hasAttribute('data-shimmer-decoration')) collectText(separator.nextElementSibling, settings.extraTitle.trim(), desired)
65
- }
66
- for (const [node, text] of record.texts) {
67
- if (!desired.has(node)) { restoreText(node, text); record.texts.delete(node) }
68
- }
69
- for (const [node, value] of desired) {
70
- const current = readText(node)
71
- const previous = record.texts.get(node)
72
- const native = previous && current === previous.shown ? previous.native : current
73
- record.texts.set(node, { native, shown: value })
74
- if (current !== value) writeText(node, value)
75
- }
76
- // 工具没有公开的“正文末尾”slot;只添加自己的兄弟节点,不接管工具 renderer。
77
- if (id.type !== 'reasoning') {
78
- const toggle = toggleOf(header)
79
- if (toggle?.getAttribute('aria-expanded') !== 'true') {
80
- record.append?.remove(); record.append = null; record.signature = null
81
- continue
82
- }
83
- const status = store.getPassageStatus(settings.currentBookId, readingKey(id))
84
- const model = novelContent(status, Boolean(settings.currentBookId), t)
85
- const signature = JSON.stringify(model)
86
- const container = root.matches('[data-sample="bash"]') ? root.parentElement : root
87
- if (!record.append || !container.contains(record.append)) {
88
- record.append = document.createElement('div')
89
- record.append.setAttribute('data-novel-append', '')
90
- container.append(record.append)
91
- record.signature = null
92
- }
93
- if (signature !== record.signature) {
94
- renderPlainAppend(record.append, model)
95
- record.signature = signature
96
- }
97
- }
98
- }
99
- }
100
-
101
- // Streaming text mutates the DOM far more often than a frame; merge observer
102
- // bursts into one scan so a long session cannot turn every token into a full
103
- // rescan. Settings/passage updates still refresh immediately.
104
- let queued = null
105
- const coalescedRefresh = () => {
106
- if (!queued) return
107
- queued = null
108
- if (!disposed) refresh()
109
- }
110
- const scheduleRefresh = () => {
111
- if (queued) return
112
- const entry = { frame: null }
113
- queued = entry
114
- if (view?.requestAnimationFrame) entry.frame = view.requestAnimationFrame(coalescedRefresh)
115
- else queueMicrotask(coalescedRefresh)
116
- }
117
-
118
- const activate = event => {
119
- if (!event.isTrusted || event.defaultPrevented) return
120
- if (event.type === 'keydown' && (event.repeat || !['Enter', ' '].includes(event.key))) return
121
- if (event.type === 'click' && event.button > 0) return
122
- const target = event.target instanceof Element ? event.target : event.target?.parentElement
123
- const header = target?.closest('[data-disclosure-row], [data-sample="bash"][aria-expanded]')
124
- const root = header?.matches('[data-sample="bash"]') ? header : header?.closest('[data-tool], [data-variant="think"]')
125
- if (!root?.matches(REGIONS)) return
126
- const toggle = toggleOf(header)
127
- if (!toggle || !toggle.contains(target) || toggle.getAttribute('aria-expanded') !== 'false') return
128
- const control = target.closest('button, [role="button"], a, input, select, textarea, [contenteditable="true"]')
129
- if (control && control !== toggle) return
130
- if (event.type === 'keydown' && target !== toggle) return
131
- const id = identityOf(root)
132
- const settings = store.getSettingsSnapshot()
133
- if (!settings.enabled || !isTarget(settings, id) || pending.has(toggle)) return
134
- const bookId = settings.currentBookId
135
- const intent = { frame: null, root, key: readingKey(id), bookId, generation: store.cacheGeneration }
136
- pending.set(toggle, intent)
137
- const verify = () => {
138
- if (pending.get(toggle) !== intent) return
139
- pending.delete(toggle)
140
- const current = store.getSettingsSnapshot()
141
- const currentId = identityOf(root)
142
- if (!disposed && toggle.isConnected && toggle.getAttribute('aria-expanded') === 'true'
143
- && current.enabled && current.currentBookId === bookId && isTarget(current, currentId)
144
- && store.cacheGeneration === intent.generation && readingKey(currentId) === intent.key) {
145
- if (current.continueOnReopen === true) void store.continuePassage(readingKey(id), id.type)
146
- else void store.claimPassage(readingKey(id), id.type)
147
- }
148
- }
149
- if (view?.requestAnimationFrame) intent.frame = view.requestAnimationFrame(verify)
150
- else queueMicrotask(verify)
151
- }
152
- const observer = new MutationObserver(scheduleRefresh)
153
- observer.observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true,
154
- attributeFilter: ['data-shimmer-text', 'aria-expanded', 'data-tool', 'data-state'] })
155
- document.addEventListener('click', activate, true)
156
- document.addEventListener('keydown', activate, true)
157
- const stopSettings = store.subscribeSettings(refresh)
158
- const stopPassages = store.subscribePassages(refresh)
159
- refresh()
160
- return () => {
161
- disposed = true
162
- observer.disconnect(); stopSettings(); stopPassages()
163
- document.removeEventListener('click', activate, true)
164
- document.removeEventListener('keydown', activate, true)
165
- if (queued && queued.frame !== null && view?.cancelAnimationFrame) view.cancelAnimationFrame(queued.frame)
166
- queued = null
167
- for (const intent of pending.values()) if (intent.frame !== null) view.cancelAnimationFrame(intent.frame)
168
- pending.clear()
169
- for (const root of decorated.keys()) restore(root)
170
- }
171
- }, 'novel-fish: native disclosure adapter')
172
- }
173
-
174
- function headerOf(root) {
175
- return root.matches('[data-sample="bash"]') ? root : root.querySelector('[data-disclosure-row]')
176
- }
177
- function toggleOf(header) {
178
- return header.matches('[role="button"][aria-expanded]') ? header : header.querySelector(':scope > button[aria-expanded]')
179
- }
180
- function collectText(element, value, desired) {
181
- if (!element || !value) return
182
- const walker = element.ownerDocument.createTreeWalker(element, 4)
183
- let first = true
184
- for (let node = walker.nextNode(); node; node = walker.nextNode()) {
185
- desired.set(node, first ? value : ''); first = false
186
- }
187
- for (const node of [element, ...element.querySelectorAll('[data-shimmer-text]')]) {
188
- if (node.hasAttribute('data-shimmer-text')) desired.set(node, value)
189
- }
190
- }
191
- function readText(node) { return node.nodeType === 3 ? node.nodeValue : node.getAttribute('data-shimmer-text') }
192
- function writeText(node, value) {
193
- if (node.nodeType === 3) node.nodeValue = value
194
- else node.setAttribute('data-shimmer-text', value)
195
- }
196
- function restoreText(node, text) { if (readText(node) === text.shown) writeText(node, text.native) }
197
-
198
- function createBody(React) {
199
- const h = React.createElement
200
- return function NovelBody({ text, running, sessionId, useNovelSettings, useNovelPassages, renderFactorySlot, t }) {
201
- const ref = React.useRef(null)
202
- const [identity, setIdentity] = React.useState(null)
203
- const settings = useNovelSettings(value => value)
204
- React.useEffect(() => { setIdentity(identityOf(ref.current)) }, [sessionId])
205
- const selected = settings.enabled && isTarget(settings, identity)
206
- const key = settings.currentBookId && identity ? passageSnapshotKey(settings.currentBookId, readingKey(identity)) : null
207
- const status = useNovelPassages(snapshot => key ? snapshot[key] : undefined) ?? EMPTY
208
- const model = selected ? novelContent(status, Boolean(settings.currentBookId), t) : null
209
- return h('div', { ref },
210
- h('div', { 'data-novel-original': true }, renderFactorySlot('conversation.chat.reasoning.content', { text, running })),
211
- model === null ? null : h('div', { 'data-novel-append': true, style: NOVEL_STYLE },
212
- h('hr', { style: SEPARATOR_STYLE }),
213
- 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
- )
216
- }
217
- }
218
- function renderPlainAppend(element, model) {
219
- Object.assign(element.style, NOVEL_STYLE)
220
- const divider = document.createElement('hr')
221
- Object.assign(divider.style, SEPARATOR_STYLE)
222
- const label = document.createElement('div')
223
- label.setAttribute('data-novel-label', '')
224
- label.textContent = model.chapter ? `${model.label} · ${model.chapter}` : model.label
225
- const content = document.createElement('div')
226
- if (model.index) content.setAttribute('data-novel-passage', model.index)
227
- if (model.role) content.setAttribute('role', model.role)
228
- content.textContent = model.text
229
- element.replaceChildren(divider, label, content)
230
- }
231
- function identityOf(element) {
232
- const root = element?.closest('[data-variant="think"], [data-tool], [data-sample="bash"]')
233
- const node = root?.closest('[data-chat-node-key]')
234
- const container = node?.closest('[data-conversation-session]')
235
- if (!root || !node || !container) return null
236
- const sessionId = container.getAttribute('data-conversation-session')
237
- const nodeKey = node.getAttribute('data-chat-node-key')
238
- if (!sessionId || !nodeKey) return null
239
- if (root.matches(THOUGHT)) {
240
- const regions = [...node.querySelectorAll('[data-variant="think"]')].filter(region => region.closest('[data-chat-node-key]') === node)
241
- const index = regions.indexOf(root)
242
- return index < 0 ? null : { sessionId, nodeKey, type: 'reasoning', index }
243
- }
244
- const call = root.closest('[data-chat-call-id]')
245
- if (!call || !call.getAttribute('data-chat-call-id')) return null
246
- const variant = root.getAttribute('data-variant')
247
- const name = root.getAttribute('data-tool')
248
- const type = variant === 'bash' ? 'command' : ['read', 'read_image'].includes(name) ? 'read-file'
249
- : ['grep', 'glob'].includes(name) ? 'file-search' : 'tool-call'
250
- return { sessionId, nodeKey, type, index: call.getAttribute('data-chat-call-id') }
251
- }
252
- function readingKey(identity) { return JSON.stringify([identity.sessionId, identity.nodeKey, identity.type, identity.index]) }
253
- function isTarget(settings, identity) { return identity !== null && settings.targetTypes?.includes(identity.type) }
package/src/client.js DELETED
@@ -1,55 +0,0 @@
1
- import { IndexedDbStorage } from './persistence.js'
2
- import { NovelStore } from './store.js'
3
- import { registerChatAdapter } from './chat-adapter.js'
4
- import { createSettingsRow } from './settings.js'
5
- import zh from '../locale/zh.json'
6
- import en from '../locale/en.json'
7
-
8
- const MODULE_ID = '@gongfpp/dsh-novel-fish'
9
- const LOCALE = 'novel-fish'
10
-
11
- function flatten(value, prefix = '') {
12
- return Object.fromEntries(Object.entries(value).flatMap(([key, item]) => {
13
- const path = prefix ? `${prefix}.${key}` : key
14
- return typeof item === 'string' ? [[path, item]] : Object.entries(flatten(item, path))
15
- }))
16
- }
17
-
18
- window.__ModuleLoader__.load({
19
- id: MODULE_ID,
20
- factory(require) {
21
- const React = require('react')
22
- const primitives = require('@deepseek-ai/dsh-client-ui-primitives')
23
- return {
24
- inject: ['slots', 'locale'],
25
- apply(ctx) {
26
- const storage = new IndexedDbStorage()
27
- const store = new NovelStore(storage)
28
- const SettingsRow = createSettingsRow(React, primitives)
29
- const settingsActions = {
30
- onSetOption: (key, value) => store.setOption(key, value),
31
- onSetNotice: notice => store.setNotice(notice),
32
- onSelectBook: bookId => store.selectBook(bookId),
33
- onDeleteBook: bookId => store.deleteBook(bookId),
34
- onImportFile: file => store.importFile(file),
35
- }
36
-
37
- ctx.effect(() => ctx.locale.register(LOCALE, { zh: flatten(zh), en: flatten(en) }), 'novel-fish: locale')
38
- ctx.effect(() => () => store.dispose(), 'novel-fish: store')
39
- ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
40
- name: 'plugins.bundle.config',
41
- key: MODULE_ID,
42
- locale: LOCALE,
43
- inject: () => ({
44
- hooks: {
45
- novelState: store.stateSource,
46
- novelUi: store.uiSource,
47
- },
48
- ...settingsActions,
49
- }),
50
- }, SettingsRow))
51
- registerChatAdapter(ctx, store, React, LOCALE)
52
- },
53
- }
54
- },
55
- })