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/src/fetch.js ADDED
@@ -0,0 +1,183 @@
1
+ import dns from 'node:dns'
2
+ import iconv from 'iconv-lite'
3
+ import { Agent, ProxyAgent, fetch as undiciFetch } from 'undici'
4
+ import { assertPublicUrl, isPrivateIp } from './security.js'
5
+
6
+ const proxyAgents = new Map()
7
+ const validatingAgents = new Map()
8
+
9
+ function proxyDispatcher(proxyUrl) {
10
+ if (!proxyUrl) return undefined
11
+ let agent = proxyAgents.get(proxyUrl)
12
+ if (agent === undefined) {
13
+ agent = new ProxyAgent(proxyUrl)
14
+ proxyAgents.set(proxyUrl, agent)
15
+ }
16
+ return agent
17
+ }
18
+
19
+ function validatingAgent(blockFakeIp) {
20
+ const key = blockFakeIp ? 'block-fake-ip' : 'allow-fake-ip'
21
+ let agent = validatingAgents.get(key)
22
+ if (agent !== undefined) return agent
23
+ agent = new Agent({
24
+ connect: {
25
+ // assertPublicUrl checks the hostname once, but the socket resolves it
26
+ // again. This lookup is the enforcement point that closes the DNS
27
+ // rebinding window.
28
+ lookup(hostname, options, callback) {
29
+ dns.lookup(hostname, { all: true, verbatim: true }, (error, addresses) => {
30
+ if (error) {
31
+ callback(error)
32
+ return
33
+ }
34
+ const allowed = addresses.filter(({ address }) => !isPrivateIp(address, { blockFakeIp }))
35
+ if (allowed.length === 0) {
36
+ callback(new Error(`拒绝连接:${hostname} 解析到内网地址`))
37
+ return
38
+ }
39
+ if (options?.all === true) callback(null, allowed)
40
+ else callback(null, allowed[0].address, allowed[0].family)
41
+ })
42
+ },
43
+ },
44
+ })
45
+ validatingAgents.set(key, agent)
46
+ return agent
47
+ }
48
+
49
+ function dispatcherFor(config, hasInjectedFetch) {
50
+ if (hasInjectedFetch) return undefined
51
+ if (config.allowPrivate === true) return undefined
52
+ if (config.proxy) return proxyDispatcher(config.proxy)
53
+ return validatingAgent(config.blockFakeIp === true)
54
+ }
55
+
56
+ const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308])
57
+ const HTML_TYPES = ['text/html', 'application/xhtml+xml']
58
+
59
+ function signalWithTimeout(signal, timeoutMs) {
60
+ const timeout = AbortSignal.timeout(timeoutMs)
61
+ if (signal === undefined || signal === null) return timeout
62
+ return AbortSignal.any([signal, timeout])
63
+ }
64
+
65
+ function charsetFromContentType(contentType) {
66
+ const match = /charset\s*=\s*["']?([^;"'\s]+)/i.exec(contentType || '')
67
+ return match ? match[1].toLowerCase() : undefined
68
+ }
69
+
70
+ function charsetFromHtml(buffer) {
71
+ const head = buffer.subarray(0, 4096).toString('latin1')
72
+ const meta = /<meta[^>]+charset\s*=\s*["']?([^"'\s/>]+)/i.exec(head)
73
+ if (meta !== null) return meta[1].toLowerCase()
74
+ const httpEquiv = /<meta[^>]+http-equiv\s*=\s*["']?content-type["']?[^>]+content\s*=\s*["'][^"']*charset=([^"'\s;]+)/i.exec(head)
75
+ return httpEquiv !== null ? httpEquiv[1].toLowerCase() : undefined
76
+ }
77
+
78
+ function decodeBody(buffer, contentType) {
79
+ const charset = charsetFromContentType(contentType) || charsetFromHtml(buffer) || 'utf-8'
80
+ try {
81
+ return { text: iconv.decode(buffer, charset), charset }
82
+ } catch {
83
+ return { text: buffer.toString('utf8'), charset: 'utf-8' }
84
+ }
85
+ }
86
+
87
+ async function readCapped(response, maxBytes) {
88
+ if (response.body === null) return Buffer.alloc(0)
89
+ const reader = response.body.getReader()
90
+ const chunks = []
91
+ let total = 0
92
+ try {
93
+ for (;;) {
94
+ const { done, value } = await reader.read()
95
+ if (done) break
96
+ total += value.byteLength
97
+ if (total > maxBytes) {
98
+ await reader.cancel().catch(() => {})
99
+ throw new Error(`页面超过大小上限(${Math.floor(maxBytes / 1024)} KB)`)
100
+ }
101
+ chunks.push(Buffer.from(value))
102
+ }
103
+ } finally {
104
+ reader.releaseLock?.()
105
+ }
106
+ return Buffer.concat(chunks, total)
107
+ }
108
+
109
+ function escapeHtml(text) {
110
+ return String(text)
111
+ .replaceAll('&', '&amp;')
112
+ .replaceAll('<', '&lt;')
113
+ .replaceAll('>', '&gt;')
114
+ .replaceAll('"', '&quot;')
115
+ }
116
+
117
+ /**
118
+ * Fetch an article with a manual redirect loop, per-hop SSRF validation, a
119
+ * byte cap, and charset detection (GBK/Big5 pages are common on the Chinese
120
+ * web). Returns HTML plus the final URL after redirects.
121
+ */
122
+ export async function fetchHtml(rawUrl, config, options = {}) {
123
+ const dispatcher = dispatcherFor(config, options.fetchImpl !== undefined)
124
+ const fetchImpl = options.fetchImpl ?? undiciFetch
125
+ const signal = signalWithTimeout(options.signal, config.timeoutMs)
126
+ let current = rawUrl
127
+
128
+ for (let hop = 0; hop <= config.maxRedirects; hop += 1) {
129
+ const url = await assertPublicUrl(current, config)
130
+ const response = await fetchImpl(url, {
131
+ redirect: 'manual',
132
+ signal,
133
+ ...(dispatcher === undefined ? {} : { dispatcher }),
134
+ headers: {
135
+ 'user-agent': config.userAgent,
136
+ accept: 'text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.1',
137
+ 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
138
+ },
139
+ })
140
+
141
+ if (REDIRECT_STATUS.has(response.status)) {
142
+ const location = response.headers.get('location')
143
+ if (location === null) throw new Error(`HTTP ${response.status} 重定向缺少 Location`)
144
+ current = new URL(location, url).toString()
145
+ if (hop === config.maxRedirects) throw new Error('重定向次数过多')
146
+ continue
147
+ }
148
+
149
+ if (!response.ok) {
150
+ throw new Error(`抓取失败:HTTP ${response.status} ${response.statusText}`.trim())
151
+ }
152
+
153
+ const contentType = (response.headers.get('content-type') || '').toLowerCase()
154
+ const buffer = await readCapped(response, config.maxBytes)
155
+ const finalUrl = response.url || url.toString()
156
+
157
+ if (HTML_TYPES.some(type => contentType.includes(type)) || contentType === '') {
158
+ const decoded = decodeBody(buffer, contentType)
159
+ return {
160
+ html: decoded.text,
161
+ finalUrl,
162
+ contentType,
163
+ charset: decoded.charset,
164
+ status: response.status,
165
+ bytes: buffer.length,
166
+ }
167
+ }
168
+ if (contentType.includes('text/plain')) {
169
+ const decoded = decodeBody(buffer, contentType)
170
+ return {
171
+ html: `<!doctype html><html><head><meta charset="utf-8"></head><body><pre>${escapeHtml(decoded.text)}</pre></body></html>`,
172
+ finalUrl,
173
+ contentType,
174
+ charset: decoded.charset,
175
+ status: response.status,
176
+ bytes: buffer.length,
177
+ }
178
+ }
179
+ throw new Error(`不支持的内容类型:${contentType.split(';')[0]};目前只支持 HTML/纯文本`)
180
+ }
181
+
182
+ throw new Error('重定向次数过多')
183
+ }
@@ -0,0 +1,74 @@
1
+ import { clampText, readJson, sha256, writeJsonAtomic } from './util.js'
2
+
3
+ const SCHEMA_VERSION = 1
4
+
5
+ function cleanTerm(value, maxLength = 80) {
6
+ return clampText(value, maxLength)
7
+ }
8
+
9
+ export class Glossary {
10
+ constructor({ file, limit = 500 }) {
11
+ this.file = file
12
+ this.limit = limit
13
+ this.terms = []
14
+ this.loaded = false
15
+ }
16
+
17
+ async ready() {
18
+ if (this.loaded) return
19
+ const data = await readJson(this.file, { schemaVersion: SCHEMA_VERSION, terms: [] })
20
+ this.terms = Array.isArray(data?.terms)
21
+ ? data.terms
22
+ .filter(term => term !== null && typeof term === 'object')
23
+ .map(term => ({
24
+ source: cleanTerm(term.source),
25
+ target: cleanTerm(term.target),
26
+ note: cleanTerm(term.note, 160),
27
+ }))
28
+ .filter(term => term.source !== '' && term.target !== '')
29
+ .slice(0, this.limit)
30
+ : []
31
+ this.loaded = true
32
+ }
33
+
34
+ list() {
35
+ return this.terms.map(term => ({ ...term }))
36
+ }
37
+
38
+ add(source, target, note = '') {
39
+ const cleanSource = cleanTerm(source)
40
+ const cleanTarget = cleanTerm(target)
41
+ if (cleanSource === '') throw new Error('术语 source 不能为空')
42
+ if (cleanTarget === '') throw new Error('术语 target 不能为空')
43
+ if (this.terms.length >= this.limit) throw new Error(`术语表最多 ${this.limit} 条`)
44
+ const existing = this.terms.find(term => term.source.toLowerCase() === cleanSource.toLowerCase())
45
+ if (existing !== undefined) {
46
+ existing.target = cleanTarget
47
+ existing.note = cleanTerm(note, 160)
48
+ } else {
49
+ this.terms.push({ source: cleanSource, target: cleanTarget, note: cleanTerm(note, 160) })
50
+ }
51
+ this.terms.sort((a, b) => a.source.localeCompare(b.source))
52
+ return this.list()
53
+ }
54
+
55
+ remove(source) {
56
+ const cleanSource = cleanTerm(source)
57
+ if (cleanSource === '') throw new Error('术语 source 不能为空')
58
+ const before = this.terms.length
59
+ this.terms = this.terms.filter(term => term.source.toLowerCase() !== cleanSource.toLowerCase())
60
+ if (this.terms.length === before) throw new Error(`术语表里没有:${cleanSource}`)
61
+ return this.list()
62
+ }
63
+
64
+ hash() {
65
+ return sha256(this.terms
66
+ .map(term => `${term.source}\u0000${term.target}`)
67
+ .sort()
68
+ .join('\n'))
69
+ }
70
+
71
+ async flush() {
72
+ await writeJsonAtomic(this.file, { schemaVersion: SCHEMA_VERSION, terms: this.terms })
73
+ }
74
+ }
package/src/prompt.js ADDED
@@ -0,0 +1,125 @@
1
+ import { targetLanguageName } from './config.js'
2
+ import { sha256 } from './util.js'
3
+
4
+ const MAX_GLOSSARY_TERMS = 40
5
+
6
+ export function glossaryHash(terms = []) {
7
+ return sha256(terms
8
+ .map(term => `${term.source}\u0000${term.target}`)
9
+ .sort()
10
+ .join('\n'))
11
+ }
12
+
13
+ export function selectGlossary(terms, text) {
14
+ const haystack = String(text ?? '').toLowerCase()
15
+ return terms
16
+ .filter(term => term.source !== '' && haystack.includes(term.source.toLowerCase()))
17
+ .slice(0, MAX_GLOSSARY_TERMS)
18
+ }
19
+
20
+ export function chunkBlocks(blocks, options = {}) {
21
+ const maxBlocks = options.maxBlocks ?? 6
22
+ const maxChars = options.maxChars ?? 3_500
23
+ const batches = []
24
+ let current = []
25
+ let chars = 0
26
+
27
+ for (const block of blocks) {
28
+ const length = String(block.text ?? block.original ?? '').length
29
+ if (current.length > 0 && (current.length >= maxBlocks || chars + length > maxChars)) {
30
+ batches.push(current)
31
+ current = []
32
+ chars = 0
33
+ }
34
+ current.push(block)
35
+ chars += length
36
+ }
37
+ if (current.length > 0) batches.push(current)
38
+ return batches
39
+ }
40
+
41
+ export function buildBatchPrompt({ blocks, targetLang, glossary = [], context = {} }) {
42
+ const language = targetLanguageName(targetLang)
43
+ const glossaryText = glossary.length === 0
44
+ ? ''
45
+ : glossary.map(term => `${term.source} => ${term.target}`).join('\n')
46
+ let system = [
47
+ `You are a precise translator. Translate every block into ${language}.`,
48
+ 'Preserve Markdown structure exactly: headings, list markers, blockquotes, table pipes, fenced code blocks, inline code, links, URLs, LaTeX and placeholder tokens such as ⟦0⟧.',
49
+ 'Never translate code, URLs, LaTeX or placeholder tokens. Never merge or split blocks.',
50
+ 'Translate only the prose. Do not add explanations, notes or commentary.',
51
+ 'Return only JSON: {"translations":["...", "..."]} with exactly one string per input block, in the same order.',
52
+ ].join(' ')
53
+ if (glossaryText !== '') {
54
+ system += ` Terminology (source => target), use the target consistently:\n${glossaryText}`
55
+ }
56
+
57
+ const payload = {
58
+ targetLanguage: language,
59
+ title: context.title ?? '',
60
+ contextBefore: context.before ?? '',
61
+ contextAfter: context.after ?? '',
62
+ glossary,
63
+ blocks: blocks.map(block => String(block.text ?? block.original ?? '')),
64
+ }
65
+ return { system, user: JSON.stringify(payload) }
66
+ }
67
+
68
+ function extractJson(raw) {
69
+ const cleaned = String(raw ?? '').trim()
70
+ .replace(/^```(?:json)?\s*/i, '')
71
+ .replace(/\s*```$/, '')
72
+ .trim()
73
+ try {
74
+ return JSON.parse(cleaned)
75
+ } catch {
76
+ const arrayStart = cleaned.indexOf('[')
77
+ const arrayEnd = cleaned.lastIndexOf(']')
78
+ if (arrayStart !== -1 && arrayEnd > arrayStart) {
79
+ try { return JSON.parse(cleaned.slice(arrayStart, arrayEnd + 1)) } catch { /* fall through */ }
80
+ }
81
+ const objectStart = cleaned.indexOf('{')
82
+ const objectEnd = cleaned.lastIndexOf('}')
83
+ if (objectStart !== -1 && objectEnd > objectStart) {
84
+ try { return JSON.parse(cleaned.slice(objectStart, objectEnd + 1)) } catch { /* fall through */ }
85
+ }
86
+ return null
87
+ }
88
+ }
89
+
90
+ function toStringArray(value) {
91
+ if (!Array.isArray(value)) return null
92
+ return value.map(item => {
93
+ if (typeof item === 'string') return item
94
+ if (item !== null && typeof item === 'object') {
95
+ if (typeof item.translation === 'string') return item.translation
96
+ if (typeof item.text === 'string') return item.text
97
+ }
98
+ return null
99
+ })
100
+ }
101
+
102
+ /**
103
+ * Accept a JSON array, {"translations":[...]}, or {"blocks":[...]}; tolerate
104
+ * fenced output and surrounding prose. Missing entries are returned as null so
105
+ * the caller can retry only those blocks.
106
+ */
107
+ export function parseBatchResponse(raw, expectedCount) {
108
+ const parsed = extractJson(raw)
109
+ let values = null
110
+ if (Array.isArray(parsed)) values = toStringArray(parsed)
111
+ else if (parsed !== null && typeof parsed === 'object') {
112
+ values = toStringArray(parsed.translations) ?? toStringArray(parsed.blocks)
113
+ }
114
+ if (values === null) {
115
+ if (expectedCount === 1) {
116
+ const plain = String(raw ?? '').trim().replace(/^```[a-z]*\s*/i, '').replace(/\s*```$/, '')
117
+ if (plain !== '') return [plain]
118
+ }
119
+ throw new Error('模型返回不是可解析的译文 JSON')
120
+ }
121
+ const result = values.slice(0, expectedCount)
122
+ while (result.length < expectedCount) result.push(null)
123
+ if (result.every(value => value === null)) throw new Error('模型没有返回任何译文')
124
+ return result
125
+ }
package/src/protect.js ADDED
@@ -0,0 +1,71 @@
1
+ const TOKEN_START = '⟦'
2
+ const TOKEN_END = '⟧'
3
+ const TOKEN_PATTERN = /⟦(\d+)⟧/g
4
+
5
+ function tokenFor(index) {
6
+ return `${TOKEN_START}${index}${TOKEN_END}`
7
+ }
8
+
9
+ /**
10
+ * Protect inline code, LaTeX, link targets, raw URLs and HTML tags before a
11
+ * block is sent to the model. The model is told to keep the tokens verbatim;
12
+ * restoreInline puts the original fragments back. If the model drops a token,
13
+ * the caller can retry that block instead of silently deleting a link or a
14
+ * code fragment.
15
+ */
16
+ export function protectInline(text) {
17
+ const values = []
18
+ let output = String(text ?? '')
19
+
20
+ function protect(regex, replacement) {
21
+ output = output.replace(regex, (...args) => {
22
+ const index = values.length
23
+ values.push(replacement(...args))
24
+ return tokenFor(index)
25
+ })
26
+ }
27
+
28
+ // Inline code and fenced fragments that survived block segmentation.
29
+ protect(/`[^`\n]*`/g, match => match)
30
+ // Display and inline LaTeX.
31
+ protect(/\$\$[\s\S]*?\$\$/g, match => match)
32
+ protect(/\$[^$\n]+\$/g, match => match)
33
+ // Keep link targets verbatim while allowing the link text to be translated.
34
+ protect(/\]\((https?:\/\/[^)\s]+|mailto:[^)\s]+)(\s+"[^"]*")?\)/g, (match, url, title = '') => `](${url}${title})`)
35
+ // Bare URLs.
36
+ protect(/https?:\/\/[^\s<>")\]]+/g, match => match)
37
+ // Inline HTML.
38
+ protect(/<[^>\n]+>/g, match => match)
39
+
40
+ return {
41
+ text: output,
42
+ values,
43
+ restore(translated) {
44
+ const seen = new Set()
45
+ const invalid = []
46
+ const restored = String(translated ?? '').replace(TOKEN_PATTERN, (_match, rawIndex) => {
47
+ const index = Number(rawIndex)
48
+ seen.add(index)
49
+ if (!Number.isInteger(index) || values[index] === undefined) {
50
+ invalid.push(rawIndex)
51
+ return ''
52
+ }
53
+ return values[index]
54
+ })
55
+ const dropped = values
56
+ .map((_value, index) => index)
57
+ .filter(index => !seen.has(index))
58
+ .map(String)
59
+ return { text: restored, missing: [...dropped, ...invalid] }
60
+ },
61
+ }
62
+ }
63
+
64
+ export function missingTokens(translated) {
65
+ const missing = []
66
+ String(translated ?? '').replace(TOKEN_PATTERN, (_match, rawIndex) => {
67
+ missing.push(rawIndex)
68
+ return ''
69
+ })
70
+ return missing
71
+ }