dsh-bilingual-reader 0.0.0-stage → 0.1.1

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/package.json CHANGED
@@ -1,6 +1,78 @@
1
1
  {
2
2
  "name": "dsh-bilingual-reader",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "面向 DeepSeek Harness 的双语阅读工作台:网页/文档 → 结构保留的双语对照,术语表与翻译缓存。",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./client": {
10
+ "default": "./client/client.js"
11
+ },
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "src",
17
+ "client",
18
+ "web",
19
+ "docs",
20
+ "cordis.patch.yml",
21
+ "README.md",
22
+ "README.en.md",
23
+ "LICENSE"
24
+ ],
25
+ "dsh": {
26
+ "bundle": {
27
+ "patch": "./cordis.patch.yml"
28
+ },
29
+ "client": {
30
+ "inject": [],
31
+ "platform": "web"
32
+ }
33
+ },
34
+ "engines": {
35
+ "node": ">=22.12.0",
36
+ "dsh": ">=0.2.0 <0.3.0"
37
+ },
38
+ "scripts": {
39
+ "pretest": "npm run build:client",
40
+ "test": "node --test",
41
+ "verify": "node scripts/verify.mjs",
42
+ "dev": "node scripts/dev-server.mjs",
43
+ "build:client": "node scripts/build-client.mjs",
44
+ "prepack": "node scripts/build-client.mjs"
45
+ },
46
+ "dependencies": {
47
+ "@mozilla/readability": "^0.6.0",
48
+ "iconv-lite": "^0.7.0",
49
+ "linkedom": "^0.18.15",
50
+ "marked": "^18.3.0",
51
+ "sanitize-html": "^2.18.2",
52
+ "turndown": "^7.2.5",
53
+ "turndown-plugin-gfm": "^1.0.2",
54
+ "undici": "^7.30.2"
55
+ },
56
+ "devDependencies": {
57
+ "esbuild": "^0.28.2"
58
+ },
59
+ "keywords": [
60
+ "dsh-plugin",
61
+ "deepseek-harness",
62
+ "bilingual",
63
+ "translation",
64
+ "reader",
65
+ "immersive-translate",
66
+ "glossary",
67
+ "markdown"
68
+ ],
69
+ "license": "MIT",
70
+ "repository": {
71
+ "type": "git",
72
+ "url": "git+https://github.com/Bit0620/dsh-bilingual-reader.git"
73
+ },
74
+ "publishConfig": {
75
+ "access": "public",
76
+ "registry": "https://registry.npmjs.org/"
77
+ }
78
+ }
package/src/cache.js ADDED
@@ -0,0 +1,76 @@
1
+ import { readJson, sha256, writeJsonAtomic } from './util.js'
2
+
3
+ const SCHEMA_VERSION = 1
4
+
5
+ export class TranslationCache {
6
+ constructor({ file, limit = 20_000 }) {
7
+ this.file = file
8
+ this.limit = limit
9
+ this.entries = new Map()
10
+ this.hits = 0
11
+ this.misses = 0
12
+ this.loaded = false
13
+ }
14
+
15
+ async ready() {
16
+ if (this.loaded) return
17
+ const data = await readJson(this.file, { schemaVersion: SCHEMA_VERSION, entries: {} })
18
+ const entries = data !== null && typeof data === 'object' && data.entries !== null && typeof data.entries === 'object'
19
+ ? data.entries
20
+ : {}
21
+ for (const [key, entry] of Object.entries(entries)) {
22
+ if (entry === null || typeof entry !== 'object' || typeof entry.translation !== 'string') continue
23
+ this.entries.set(key, {
24
+ translation: entry.translation,
25
+ createdAt: typeof entry.createdAt === 'string' ? entry.createdAt : new Date(0).toISOString(),
26
+ })
27
+ }
28
+ this.loaded = true
29
+ }
30
+
31
+ key(text, targetLang, glossaryHash) {
32
+ return sha256(`${targetLang}\u0000${glossaryHash}\u0000${text}`)
33
+ }
34
+
35
+ get(key) {
36
+ const entry = this.entries.get(key)
37
+ if (entry === undefined) {
38
+ this.misses += 1
39
+ return null
40
+ }
41
+ this.hits += 1
42
+ return entry.translation
43
+ }
44
+
45
+ set(key, translation) {
46
+ this.entries.set(key, { translation: String(translation), createdAt: new Date().toISOString() })
47
+ this.prune()
48
+ }
49
+
50
+ prune() {
51
+ if (this.entries.size <= this.limit) return
52
+ const sorted = [...this.entries.entries()].sort((a, b) => {
53
+ const left = Date.parse(a[1].createdAt) || 0
54
+ const right = Date.parse(b[1].createdAt) || 0
55
+ return left - right
56
+ })
57
+ const removeCount = Math.max(1, Math.ceil(this.entries.size * 0.1))
58
+ for (const [key] of sorted.slice(0, removeCount)) this.entries.delete(key)
59
+ }
60
+
61
+ stats() {
62
+ const total = this.hits + this.misses
63
+ return {
64
+ size: this.entries.size,
65
+ hits: this.hits,
66
+ misses: this.misses,
67
+ hitRate: total === 0 ? 0 : this.hits / total,
68
+ }
69
+ }
70
+
71
+ async flush() {
72
+ const entries = {}
73
+ for (const [key, entry] of this.entries) entries[key] = entry
74
+ await writeJsonAtomic(this.file, { schemaVersion: SCHEMA_VERSION, entries })
75
+ }
76
+ }
package/src/client.js ADDED
@@ -0,0 +1,59 @@
1
+ import { createElement as h } from 'react'
2
+
3
+ export const name = 'dsh-bilingual-reader-client'
4
+ export const inject = ['slots']
5
+
6
+ const ID = 'dsh-bilingual-reader'
7
+ const LABEL = '双语阅读'
8
+
9
+ function TranslateIcon(owner = {}) {
10
+ const size = owner.size ?? 16
11
+ return h('svg', {
12
+ width: size,
13
+ height: size,
14
+ viewBox: '0 0 24 24',
15
+ fill: 'none',
16
+ stroke: 'currentColor',
17
+ strokeWidth: 2,
18
+ strokeLinecap: 'round',
19
+ strokeLinejoin: 'round',
20
+ 'aria-hidden': 'true',
21
+ },
22
+ h('path', { d: 'M4 5h8M8 3v2c0 4-1.5 7-4 9' }),
23
+ h('path', { d: 'M5 11c2 2.5 4.5 4 7 5' }),
24
+ h('path', { d: 'M14 20l4-10 4 10' }),
25
+ h('path', { d: 'M15.5 16h5' }))
26
+ }
27
+
28
+ /**
29
+ * The sidebar row and the main panel. The panel is an iframe to the plugin's
30
+ * own same-origin route so the reader UI can live as plain HTML/CSS/JS without
31
+ * coupling to the host's React internals.
32
+ */
33
+ export function apply(ctx) {
34
+ const slots = ctx.slots
35
+
36
+ slots.inject('sidebar.panellist', () => slots.register({
37
+ name: 'sidebar.panellist',
38
+ id: ID,
39
+ order: 3,
40
+ label: () => LABEL,
41
+ }, TranslateIcon))
42
+
43
+ slots.inject('main', () => slots.register({
44
+ name: 'main',
45
+ id: ID,
46
+ key: ID,
47
+ order: 3,
48
+ }, () => h('iframe', {
49
+ src: '/dsh-bilingual-reader/',
50
+ title: LABEL,
51
+ style: {
52
+ display: 'block',
53
+ width: '100%',
54
+ height: '100%',
55
+ border: '0',
56
+ background: 'transparent',
57
+ },
58
+ })))
59
+ }
package/src/config.js ADDED
@@ -0,0 +1,74 @@
1
+ import { homedir } from 'node:os'
2
+ import { join, resolve } from 'node:path'
3
+
4
+ export const DEFAULT_DIR = join(homedir(), '.dsh-bilingual-reader')
5
+
6
+ export const TARGET_LANGUAGES = [
7
+ { code: 'zh-CN', label: '简体中文' },
8
+ { code: 'zh-TW', label: '繁體中文' },
9
+ { code: 'en', label: 'English' },
10
+ { code: 'ja', label: '日本語' },
11
+ { code: 'ko', label: '한국어' },
12
+ ]
13
+
14
+ const LANGUAGE_NAMES = {
15
+ 'zh-CN': 'Simplified Chinese',
16
+ 'zh-TW': 'Traditional Chinese',
17
+ en: 'English',
18
+ ja: 'Japanese',
19
+ ko: 'Korean',
20
+ }
21
+
22
+ function positiveInt(value, fallback) {
23
+ if (value === undefined || value === null || value === '') return fallback
24
+ const parsed = Number(value)
25
+ return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback
26
+ }
27
+
28
+ function expandHome(value) {
29
+ if (value === '~') return homedir()
30
+ if (value.startsWith('~/') || value.startsWith('~\\')) return join(homedir(), value.slice(2))
31
+ return value
32
+ }
33
+
34
+ export function normalizeTargetLang(value, fallback = 'zh-CN') {
35
+ const code = typeof value === 'string' ? value.trim() : ''
36
+ if (code === '') return fallback
37
+ const match = TARGET_LANGUAGES.find(item => item.code.toLowerCase() === code.toLowerCase())
38
+ return match === undefined ? fallback : match.code
39
+ }
40
+
41
+ export function targetLanguageName(code) {
42
+ return LANGUAGE_NAMES[code] ?? LANGUAGE_NAMES['zh-CN']
43
+ }
44
+
45
+ export function loadConfig(env = process.env) {
46
+ const dir = resolve(expandHome(env.DSH_BILINGUAL_READER_DIR || DEFAULT_DIR))
47
+ return {
48
+ dir,
49
+ targetLang: normalizeTargetLang(env.DSH_BILINGUAL_TARGET_LANG, 'zh-CN'),
50
+ timeoutMs: positiveInt(env.DSH_BILINGUAL_TIMEOUT_MS, 20_000),
51
+ maxBytes: positiveInt(env.DSH_BILINGUAL_MAX_BYTES, 5 * 1024 * 1024),
52
+ maxMarkdownChars: positiveInt(env.DSH_BILINGUAL_MAX_MARKDOWN_CHARS, 400_000),
53
+ maxRedirects: positiveInt(env.DSH_BILINGUAL_MAX_REDIRECTS, 5),
54
+ maxBlocks: positiveInt(env.DSH_BILINGUAL_MAX_BLOCKS, 400),
55
+ batchBlocks: positiveInt(env.DSH_BILINGUAL_BATCH_BLOCKS, 6),
56
+ batchChars: positiveInt(env.DSH_BILINGUAL_BATCH_CHARS, 3_500),
57
+ concurrency: positiveInt(env.DSH_BILINGUAL_CONCURRENCY, 2),
58
+ maxTranslateChars: positiveInt(env.DSH_BILINGUAL_MAX_TRANSLATE_CHARS, 20_000),
59
+ cacheLimit: positiveInt(env.DSH_BILINGUAL_CACHE_LIMIT, 20_000),
60
+ glossaryLimit: positiveInt(env.DSH_BILINGUAL_GLOSSARY_LIMIT, 500),
61
+ allowPrivate: env.DSH_BILINGUAL_ALLOW_PRIVATE === '1' || env.DSH_BILINGUAL_ALLOW_PRIVATE === 'true',
62
+ blockFakeIp: env.DSH_BILINGUAL_BLOCK_FAKE_IP === '1' || env.DSH_BILINGUAL_BLOCK_FAKE_IP === 'true',
63
+ userAgent:
64
+ env.DSH_BILINGUAL_USER_AGENT ||
65
+ 'dsh-bilingual-reader/0.1 (+https://github.com/Bit0620/dsh-bilingual-reader)',
66
+ proxy:
67
+ env.DSH_BILINGUAL_PROXY ||
68
+ env.HTTPS_PROXY ||
69
+ env.https_proxy ||
70
+ env.HTTP_PROXY ||
71
+ env.http_proxy ||
72
+ '',
73
+ }
74
+ }
package/src/extract.js ADDED
@@ -0,0 +1,259 @@
1
+ import { Readability } from '@mozilla/readability'
2
+ import { parseHTML } from 'linkedom'
3
+ import { marked } from 'marked'
4
+ import sanitizeHtml from 'sanitize-html'
5
+ import TurndownService from 'turndown'
6
+ import { gfm } from 'turndown-plugin-gfm'
7
+
8
+ function escapeHtmlAttribute(value) {
9
+ return String(value)
10
+ .replaceAll('&', '&amp;')
11
+ .replaceAll('"', '&quot;')
12
+ .replaceAll('<', '&lt;')
13
+ .replaceAll('>', '&gt;')
14
+ }
15
+
16
+ function withBaseHref(html, baseUrl) {
17
+ const base = `<base href="${escapeHtmlAttribute(baseUrl)}">`
18
+ if (/<head[^>]*>/i.test(html)) return html.replace(/<head([^>]*)>/i, `<head$1>${base}`)
19
+ if (/<html[^>]*>/i.test(html)) return html.replace(/<html([^>]*)>/i, `<html$1><head>${base}</head>`)
20
+ return `<!doctype html><html><head>${base}</head><body>${html}</body></html>`
21
+ }
22
+
23
+ function metaContent(document, selectors) {
24
+ for (const selector of selectors) {
25
+ const element = document.querySelector(selector)
26
+ if (element === null) continue
27
+ const value = element.getAttribute('content') ?? element.getAttribute('href') ?? element.textContent
28
+ if (typeof value === 'string' && value.trim() !== '') return value.trim()
29
+ }
30
+ return ''
31
+ }
32
+
33
+ function absoluteUrl(value, baseUrl) {
34
+ const raw = String(value ?? '').trim()
35
+ if (raw === '') return ''
36
+ if (raw.startsWith('#')) return raw
37
+ try {
38
+ return new URL(raw, baseUrl).toString()
39
+ } catch {
40
+ return ''
41
+ }
42
+ }
43
+
44
+ function isSafeHref(value) {
45
+ if (value.startsWith('#')) return true
46
+ try {
47
+ const parsed = new URL(value)
48
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:' || parsed.protocol === 'mailto:'
49
+ } catch {
50
+ return false
51
+ }
52
+ }
53
+
54
+ function makeTurndown(baseUrl) {
55
+ const turndown = new TurndownService({
56
+ headingStyle: 'atx',
57
+ codeBlockStyle: 'fenced',
58
+ bulletListMarker: '-',
59
+ emDelimiter: '*',
60
+ })
61
+ turndown.use(gfm)
62
+ turndown.remove(['script', 'style', 'noscript', 'iframe', 'form', 'button', 'input', 'select', 'textarea', 'svg', 'canvas'])
63
+
64
+ turndown.addRule('absoluteLinks', {
65
+ filter: 'a',
66
+ replacement(content, node) {
67
+ const href = absoluteUrl(node.getAttribute?.('href'), baseUrl)
68
+ const text = content.trim()
69
+ if (href === '' || !isSafeHref(href)) return text
70
+ if (text === '') return ''
71
+ return `[${text}](${href})`
72
+ },
73
+ })
74
+
75
+ turndown.addRule('absoluteImages', {
76
+ filter: 'img',
77
+ replacement(_content, node) {
78
+ const src = absoluteUrl(node.getAttribute?.('src'), baseUrl)
79
+ if (src === '' || !/^https?:/i.test(src)) return ''
80
+ const alt = String(node.getAttribute?.('alt') ?? '').replace(/\s+/g, ' ').trim()
81
+ const title = String(node.getAttribute?.('title') ?? '').trim()
82
+ return `![${alt}](${src}${title === '' ? '' : ` "${title.replaceAll('"', '\\"')}"`})`
83
+ },
84
+ })
85
+
86
+ return turndown
87
+ }
88
+
89
+ export function countWords(text) {
90
+ const cjk = (text.match(/[぀-ヿ㐀-䶿一-鿿가-힯]/g) || []).length
91
+ const latin = (text.replace(/[぀-ヿ㐀-䶿一-鿿가-힯]/g, ' ').match(/[A-Za-z0-9_]+/g) || []).length
92
+ return { wordCount: cjk + latin, charCount: text.length, cjk }
93
+ }
94
+
95
+ function detectLanguage(document, text, cjk) {
96
+ const declared = String(document?.documentElement?.getAttribute?.('lang') ?? '').trim().toLowerCase()
97
+ if (declared !== '') return declared.split('-')[0]
98
+ return cjk > 0 && cjk >= text.length * 0.05 ? 'zh' : 'en'
99
+ }
100
+
101
+ function cleanMarkdown(markdown) {
102
+ return markdown
103
+ .replace(/\]\((?:javascript|data|vbscript|file):[^)\s]*\)/gi, '](#)')
104
+ .replace(/[ \t]+\n/g, '\n')
105
+ .replace(/\n{3,}/g, '\n\n')
106
+ .trim()
107
+ }
108
+
109
+ function clampText(value, maxLength) {
110
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim()
111
+ return text.length > maxLength ? text.slice(0, maxLength) : text
112
+ }
113
+
114
+ /**
115
+ * Turn raw HTML into a clean article: metadata, a Turndown Markdown body and
116
+ * the final URL. Readability runs on a fresh document so meta extraction and
117
+ * the fallback path cannot see a half-mutated DOM.
118
+ */
119
+ export function parseArticle(html, options = {}) {
120
+ const url = options.url ?? 'https://example.invalid/'
121
+ const maxMarkdownChars = options.maxMarkdownChars ?? 400_000
122
+ const withBase = withBaseHref(String(html ?? ''), url)
123
+
124
+ const metaDocument = parseHTML(withBase).document
125
+ const metaTitle = metaContent(metaDocument, [
126
+ 'meta[property="og:title"]',
127
+ 'meta[name="twitter:title"]',
128
+ 'meta[name="title"]',
129
+ ]) || String(metaDocument.title ?? '').trim()
130
+ const byline = metaContent(metaDocument, [
131
+ 'meta[name="author"]',
132
+ 'meta[property="article:author"]',
133
+ 'meta[name="byl"]',
134
+ ])
135
+ const siteName = metaContent(metaDocument, [
136
+ 'meta[property="og:site_name"]',
137
+ 'meta[name="application-name"]',
138
+ ]) || (() => {
139
+ try { return new URL(url).hostname } catch { return '' }
140
+ })()
141
+ const published = metaContent(metaDocument, [
142
+ 'meta[property="article:published_time"]',
143
+ 'meta[name="date"]',
144
+ 'meta[name="pubdate"]',
145
+ 'meta[name="publishdate"]',
146
+ 'meta[name="dc.date"]',
147
+ ])
148
+ const keywords = metaContent(metaDocument, [
149
+ 'meta[name="keywords"]',
150
+ 'meta[name="news_keywords"]',
151
+ ])
152
+ const canonicalRaw = absoluteUrl(
153
+ metaContent(metaDocument, ['link[rel="canonical"]']),
154
+ url,
155
+ )
156
+ const canonical = canonicalRaw.length <= 2_048 ? canonicalRaw : ''
157
+
158
+ const articleBase = canonical !== '' ? canonical : url
159
+ const articleDocument = parseHTML(withBaseHref(String(html ?? ''), articleBase)).document
160
+ let article = null
161
+ try {
162
+ article = new Readability(articleDocument, {
163
+ charThreshold: 80,
164
+ keepClasses: false,
165
+ disableJSONLD: true,
166
+ }).parse()
167
+ } catch {
168
+ article = null
169
+ }
170
+
171
+ const body = articleDocument.body
172
+ const fallbackText = String(body?.textContent ?? '').replace(/\s+/g, ' ').trim()
173
+ const contentHtml = article?.content ?? body?.innerHTML ?? ''
174
+ const textContent = String(article?.textContent ?? fallbackText).replace(/\s+/g, ' ').trim()
175
+
176
+ if (contentHtml.trim() === '' || textContent.length < 40) {
177
+ return {
178
+ ok: false,
179
+ reason: '没有提取到正文。页面可能是登录页、SPA 或反爬页;请用浏览器打开后复制正文,或换一个来源。',
180
+ }
181
+ }
182
+
183
+ const title = clampText(article?.title ?? metaTitle ?? '', 300) || (() => {
184
+ try { return new URL(url).hostname } catch { return '未命名文章' }
185
+ })()
186
+ const turndown = makeTurndown(articleBase)
187
+ let markdown = cleanMarkdown(
188
+ turndown.turndown(contentHtml)
189
+ .replace(/^#\s+.*\n+/, ''),
190
+ )
191
+ let truncated = false
192
+ if (markdown.length > maxMarkdownChars) {
193
+ markdown = `${markdown.slice(0, maxMarkdownChars)}\n\n> 内容过长,已截断。`
194
+ truncated = true
195
+ }
196
+
197
+ const excerptSource = String(article?.excerpt ?? textContent).replace(/\s+/g, ' ').trim()
198
+ const excerpt = excerptSource.length > 240 ? `${excerptSource.slice(0, 240)}…` : excerptSource
199
+ const counts = countWords(textContent)
200
+
201
+ return {
202
+ ok: true,
203
+ title,
204
+ byline: clampText(article?.byline ?? byline, 200),
205
+ siteName: clampText(article?.siteName ?? siteName, 200),
206
+ published: clampText(published, 64),
207
+ excerpt,
208
+ markdown,
209
+ textContent,
210
+ canonicalUrl: canonical,
211
+ keywords: clampText(keywords, 1_000)
212
+ .split(',')
213
+ .map(value => clampText(value, 40))
214
+ .filter(Boolean)
215
+ .slice(0, 10),
216
+ wordCount: counts.wordCount,
217
+ charCount: counts.charCount,
218
+ lang: detectLanguage(articleDocument, textContent, counts.cjk),
219
+ truncated,
220
+ }
221
+ }
222
+
223
+ const RENDER_ALLOWED_TAGS = [
224
+ 'a', 'abbr', 'b', 'blockquote', 'br', 'caption', 'code', 'col', 'colgroup', 'dd', 'del',
225
+ 'details', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5',
226
+ 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 's', 'section',
227
+ 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th',
228
+ 'thead', 'tr', 'u', 'ul',
229
+ ]
230
+
231
+ export function renderMarkdown(markdown) {
232
+ const raw = marked.parse(String(markdown ?? ''), { gfm: true, breaks: false, async: false })
233
+ return sanitizeHtml(raw, {
234
+ allowedTags: RENDER_ALLOWED_TAGS,
235
+ allowedAttributes: {
236
+ a: ['href', 'title', 'target', 'rel'],
237
+ img: ['src', 'alt', 'title', 'loading'],
238
+ code: ['class'],
239
+ th: ['align'],
240
+ td: ['align'],
241
+ },
242
+ allowedSchemes: ['http', 'https', 'mailto'],
243
+ allowedSchemesByTag: { img: ['http', 'https'] },
244
+ transformTags: {
245
+ a: (tagName, attribs) => ({
246
+ tagName,
247
+ attribs: {
248
+ ...attribs,
249
+ target: '_blank',
250
+ rel: 'noopener noreferrer',
251
+ },
252
+ }),
253
+ img: (tagName, attribs) => ({
254
+ tagName,
255
+ attribs: { ...attribs, loading: 'lazy' },
256
+ }),
257
+ },
258
+ })
259
+ }