dsh-bilingual-reader 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.en.md +138 -0
- package/README.md +137 -2
- package/client/client.js +88 -0
- package/cordis.patch.yml +7 -0
- package/docs/architecture.md +66 -0
- package/docs/demo.jpg +0 -0
- package/index.js +82 -0
- package/package.json +76 -4
- package/src/cache.js +76 -0
- package/src/client.js +59 -0
- package/src/config.js +73 -0
- package/src/extract.js +259 -0
- package/src/fetch.js +183 -0
- package/src/glossary.js +74 -0
- package/src/prompt.js +125 -0
- package/src/protect.js +71 -0
- package/src/routes.js +317 -0
- package/src/security.js +169 -0
- package/src/segment.js +116 -0
- package/src/store.js +316 -0
- package/src/tools.js +220 -0
- package/src/translator.js +335 -0
- package/src/util.js +62 -0
- package/web/app.js +400 -0
- package/web/favicon.svg +5 -0
- package/web/index.html +98 -0
- package/web/style.css +475 -0
package/src/security.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import dns from 'node:dns/promises'
|
|
2
|
+
import net from 'node:net'
|
|
3
|
+
|
|
4
|
+
const BLOCKED_HOST_SUFFIXES = [
|
|
5
|
+
'.localhost',
|
|
6
|
+
'.local',
|
|
7
|
+
'.internal',
|
|
8
|
+
'.home.arpa',
|
|
9
|
+
'.lan',
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
const BLOCKED_HOSTS = new Set([
|
|
13
|
+
'localhost',
|
|
14
|
+
'metadata.google.internal',
|
|
15
|
+
'metadata',
|
|
16
|
+
])
|
|
17
|
+
|
|
18
|
+
function ipv4Parts(ip) {
|
|
19
|
+
const parts = ip.split('.').map(Number)
|
|
20
|
+
return parts.length === 4 && parts.every(part => Number.isInteger(part) && part >= 0 && part <= 255)
|
|
21
|
+
? parts
|
|
22
|
+
: null
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function isPrivateIpv4(ip, options = {}) {
|
|
26
|
+
const parts = ipv4Parts(ip)
|
|
27
|
+
if (parts === null) return false
|
|
28
|
+
const [a, b] = parts
|
|
29
|
+
if (a === 0 || a === 10 || a === 127) return true
|
|
30
|
+
if (a === 100 && b >= 64 && b <= 127) return true
|
|
31
|
+
if (a === 169 && b === 254) return true
|
|
32
|
+
if (a === 172 && b >= 16 && b <= 31) return true
|
|
33
|
+
if (a === 192 && b === 0) return true
|
|
34
|
+
if (a === 192 && b === 168) return true
|
|
35
|
+
// 198.18.0.0/15 is RFC 2544 benchmarking space, but Clash/Mihomo TUN mode
|
|
36
|
+
// hands out fake IPs from this range for every domain. Blocking it by
|
|
37
|
+
// default would break fetching for a large share of Chinese DSH users.
|
|
38
|
+
// Set DSH_BILINGUAL_BLOCK_FAKE_IP=1 to reject it and keep the strict SSRF
|
|
39
|
+
// guarantee (at the cost of breaking fake-IP TUN mode).
|
|
40
|
+
if (a === 198 && (b === 18 || b === 19)) return options.blockFakeIp === true
|
|
41
|
+
if (a >= 224) return true
|
|
42
|
+
return false
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function ipv6Hextets(rawIp) {
|
|
46
|
+
const text = rawIp.toLowerCase().split('%')[0]
|
|
47
|
+
if (net.isIP(text) !== 6) return null
|
|
48
|
+
const halves = text.split('::')
|
|
49
|
+
if (halves.length > 2) return null
|
|
50
|
+
|
|
51
|
+
function parsePart(part) {
|
|
52
|
+
if (part === '') return []
|
|
53
|
+
const pieces = []
|
|
54
|
+
for (const piece of part.split(':')) {
|
|
55
|
+
if (piece.includes('.')) {
|
|
56
|
+
const v4 = ipv4Parts(piece)
|
|
57
|
+
if (v4 === null) return null
|
|
58
|
+
pieces.push((v4[0] << 8) | v4[1], (v4[2] << 8) | v4[3])
|
|
59
|
+
} else {
|
|
60
|
+
if (!/^[0-9a-f]{1,4}$/.test(piece)) return null
|
|
61
|
+
pieces.push(Number.parseInt(piece, 16))
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return pieces
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const head = parsePart(halves[0])
|
|
68
|
+
if (head === null) return null
|
|
69
|
+
if (halves.length === 1) return head.length === 8 ? head : null
|
|
70
|
+
const tail = parsePart(halves[1])
|
|
71
|
+
if (tail === null) return null
|
|
72
|
+
const missing = 8 - head.length - tail.length
|
|
73
|
+
if (missing < 0) return null
|
|
74
|
+
return [...head, ...Array(missing).fill(0), ...tail]
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function embeddedIpv4(high, low) {
|
|
78
|
+
return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function isPrivateIpv6(rawIp, options = {}) {
|
|
82
|
+
const h = ipv6Hextets(rawIp)
|
|
83
|
+
if (h === null) return false
|
|
84
|
+
const zeroPrefix = count => h.slice(0, count).every(value => value === 0)
|
|
85
|
+
|
|
86
|
+
if (zeroPrefix(7)) return h[7] === 0 || h[7] === 1
|
|
87
|
+
// IPv4-mapped ::ffff:0:0/96. WHATWG URL canonicalizes every mapped form
|
|
88
|
+
// (::ffff:127.0.0.1, 0:0:0:0:0:ffff:7f00:1) to ::ffff:7f00:1.
|
|
89
|
+
if (zeroPrefix(5) && h[5] === 0xffff) {
|
|
90
|
+
return isPrivateIpv4(embeddedIpv4(h[6], h[7]), options)
|
|
91
|
+
}
|
|
92
|
+
// IPv4-compatible ::/96 (deprecated, but still routable on some stacks).
|
|
93
|
+
if (zeroPrefix(6)) return isPrivateIpv4(embeddedIpv4(h[6], h[7]), options)
|
|
94
|
+
// NAT64 64:ff9b::/96.
|
|
95
|
+
if (h[0] === 0x64 && h[1] === 0xff9b && h.slice(2, 6).every(value => value === 0)) {
|
|
96
|
+
return isPrivateIpv4(embeddedIpv4(h[6], h[7]), options)
|
|
97
|
+
}
|
|
98
|
+
// 6to4 2002::/16 embeds the IPv4 address in the next two hextets.
|
|
99
|
+
if (h[0] === 0x2002) return isPrivateIpv4(embeddedIpv4(h[1], h[2]), options)
|
|
100
|
+
// Unique local fc00::/7, link-local fe80::/10, deprecated site-local fec0::/10.
|
|
101
|
+
if ((h[0] & 0xfe00) === 0xfc00) return true
|
|
102
|
+
if ((h[0] & 0xffc0) === 0xfe80) return true
|
|
103
|
+
if ((h[0] & 0xffc0) === 0xfec0) return true
|
|
104
|
+
// Multicast ff00::/8.
|
|
105
|
+
if ((h[0] & 0xff00) === 0xff00) return true
|
|
106
|
+
// Documentation 2001:db8::/32.
|
|
107
|
+
if (h[0] === 0x2001 && h[1] === 0x0db8) return true
|
|
108
|
+
return false
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function isPrivateIp(ip, options = {}) {
|
|
112
|
+
const version = net.isIP(ip)
|
|
113
|
+
if (version === 4) return isPrivateIpv4(ip, options)
|
|
114
|
+
if (version === 6) return isPrivateIpv6(ip, options)
|
|
115
|
+
return false
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function bareHostname(hostname) {
|
|
119
|
+
return hostname.toLowerCase().replace(/^\[/, '').replace(/\]$/, '').replace(/\.$/, '')
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Resolve and reject hosts that point at loopback, private networks,
|
|
124
|
+
* link-local, CGNAT, multicast, or cloud metadata endpoints. The URL can come
|
|
125
|
+
* from a model, so it must be treated as hostile.
|
|
126
|
+
*/
|
|
127
|
+
export async function assertPublicUrl(rawUrl, config = {}) {
|
|
128
|
+
let url
|
|
129
|
+
try {
|
|
130
|
+
url = new URL(rawUrl)
|
|
131
|
+
} catch {
|
|
132
|
+
throw new Error('URL 格式不正确,需要以 http:// 或 https:// 开头')
|
|
133
|
+
}
|
|
134
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
135
|
+
throw new Error(`不支持的协议:${url.protocol};只允许 http/https`)
|
|
136
|
+
}
|
|
137
|
+
const host = bareHostname(url.hostname)
|
|
138
|
+
if (host === '') throw new Error('URL 缺少主机名')
|
|
139
|
+
if (config.allowPrivate === true) return url
|
|
140
|
+
|
|
141
|
+
if (BLOCKED_HOSTS.has(host)) throw new Error(`拒绝访问本机/内网地址:${host}`)
|
|
142
|
+
for (const suffix of BLOCKED_HOST_SUFFIXES) {
|
|
143
|
+
if (host.endsWith(suffix)) throw new Error(`拒绝访问本机/内网地址:${host}`)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const ipOptions = { blockFakeIp: config.blockFakeIp === true }
|
|
147
|
+
if (net.isIP(host) !== 0) {
|
|
148
|
+
if (isPrivateIp(host, ipOptions)) throw new Error(`拒绝访问本机/内网地址:${host}`)
|
|
149
|
+
return url
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let addresses
|
|
153
|
+
try {
|
|
154
|
+
addresses = await dns.lookup(host, { all: true, verbatim: true })
|
|
155
|
+
} catch {
|
|
156
|
+
throw new Error(`无法解析域名:${host}`)
|
|
157
|
+
}
|
|
158
|
+
if (addresses.length === 0) throw new Error(`域名没有可用地址:${host}`)
|
|
159
|
+
for (const { address } of addresses) {
|
|
160
|
+
if (isPrivateIp(address, ipOptions)) {
|
|
161
|
+
throw new Error(`域名 ${host} 解析到内网地址 ${address},已拒绝`)
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return url
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export async function assertResponseUrl(responseUrl, config) {
|
|
168
|
+
return assertPublicUrl(responseUrl, config)
|
|
169
|
+
}
|
package/src/segment.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
const TRANSLATABLE_TYPES = new Set(['heading', 'paragraph', 'list', 'table', 'blockquote'])
|
|
2
|
+
|
|
3
|
+
function detectType(raw) {
|
|
4
|
+
const lines = raw.split('\n')
|
|
5
|
+
const first = lines[0].trim()
|
|
6
|
+
if (/^(```|~~~)/.test(first)) return 'code'
|
|
7
|
+
if (lines.length > 1 && lines.filter(line => /^\s*\|.*\|\s*$/.test(line)).length >= 2) return 'table'
|
|
8
|
+
if (/^#{1,6}\s+/.test(first)) return 'heading'
|
|
9
|
+
if (/^\s*>/.test(first)) return 'blockquote'
|
|
10
|
+
if (/^\s*([-*+]|\d+\.)\s+/.test(first)) return 'list'
|
|
11
|
+
if (/^(\*\s*){3,}$|^(-\s*){3,}$|^(_\s*){3,}$/.test(first)) return 'hr'
|
|
12
|
+
if (/^!\[[^\]]*\]\([^)]*\)\s*$/.test(first)) return 'image'
|
|
13
|
+
return 'paragraph'
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* True when a block has enough prose to be worth a model request. Code,
|
|
18
|
+
* horizontal rules, image-only blocks and pure markdown scaffolding are
|
|
19
|
+
* skipped. Inline code, URLs and HTML tags are stripped before counting.
|
|
20
|
+
*/
|
|
21
|
+
export function isTranslatable(raw, type = detectType(raw)) {
|
|
22
|
+
if (!TRANSLATABLE_TYPES.has(type)) return false
|
|
23
|
+
const stripped = String(raw ?? '')
|
|
24
|
+
.replace(/```[\s\S]*?```/g, ' ')
|
|
25
|
+
.replace(/`[^`\n]*`/g, ' ')
|
|
26
|
+
.replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
|
|
27
|
+
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
|
|
28
|
+
.replace(/<[^>\n]+>/g, ' ')
|
|
29
|
+
.replace(/https?:\/\/\S+/g, ' ')
|
|
30
|
+
.replace(/[#>*_~|=-]/g, ' ')
|
|
31
|
+
const cjk = (stripped.match(/[-ヿ㐀-䶿一-鿿가-]/g) || []).length
|
|
32
|
+
const latin = (stripped.match(/[A-Za-z]/g) || []).length
|
|
33
|
+
return cjk + latin >= 2
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function makeBlock(raw) {
|
|
37
|
+
const original = String(raw ?? '').trim()
|
|
38
|
+
if (original === '') return null
|
|
39
|
+
const type = detectType(original)
|
|
40
|
+
return {
|
|
41
|
+
type,
|
|
42
|
+
original,
|
|
43
|
+
translatable: isTranslatable(original, type),
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Split Markdown into block-level units. Fenced code stays atomic and is never
|
|
49
|
+
* translated; headings, paragraphs, list blocks, blockquotes and tables are
|
|
50
|
+
* kept together so the model sees the same structure the reader does.
|
|
51
|
+
*/
|
|
52
|
+
export function segmentMarkdown(markdown, options = {}) {
|
|
53
|
+
const maxBlocks = options.maxBlocks ?? 400
|
|
54
|
+
const lines = String(markdown ?? '').replace(/\r\n/g, '\n').split('\n')
|
|
55
|
+
const blocks = []
|
|
56
|
+
let buffer = []
|
|
57
|
+
let fence = null
|
|
58
|
+
|
|
59
|
+
function flush() {
|
|
60
|
+
if (buffer.length === 0) return
|
|
61
|
+
const block = makeBlock(buffer.join('\n'))
|
|
62
|
+
buffer = []
|
|
63
|
+
if (block !== null) blocks.push(block)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
for (const line of lines) {
|
|
67
|
+
const fenceMatch = /^\s*(```+|~~~+)/.exec(line)
|
|
68
|
+
if (fence !== null) {
|
|
69
|
+
buffer.push(line)
|
|
70
|
+
if (line.trim().startsWith(fence)) {
|
|
71
|
+
flush()
|
|
72
|
+
fence = null
|
|
73
|
+
}
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
if (fenceMatch !== null) {
|
|
77
|
+
flush()
|
|
78
|
+
fence = fenceMatch[1]
|
|
79
|
+
buffer.push(line)
|
|
80
|
+
continue
|
|
81
|
+
}
|
|
82
|
+
if (line.trim() === '') {
|
|
83
|
+
flush()
|
|
84
|
+
continue
|
|
85
|
+
}
|
|
86
|
+
buffer.push(line)
|
|
87
|
+
}
|
|
88
|
+
flush()
|
|
89
|
+
|
|
90
|
+
if (blocks.length > maxBlocks) {
|
|
91
|
+
return { blocks: blocks.slice(0, maxBlocks), truncated: true }
|
|
92
|
+
}
|
|
93
|
+
return { blocks, truncated: false }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function bilingualMarkdown(blocks) {
|
|
97
|
+
const parts = []
|
|
98
|
+
for (const block of blocks) {
|
|
99
|
+
if (block.translatable && typeof block.translation === 'string' && block.translation.trim() !== '') {
|
|
100
|
+
parts.push(block.original, block.translation)
|
|
101
|
+
} else {
|
|
102
|
+
parts.push(block.original)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return parts.join('\n\n').trim()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function translationMarkdown(blocks) {
|
|
109
|
+
const parts = blocks.map(block => {
|
|
110
|
+
if (block.translatable && typeof block.translation === 'string' && block.translation.trim() !== '') {
|
|
111
|
+
return block.translation
|
|
112
|
+
}
|
|
113
|
+
return block.original
|
|
114
|
+
})
|
|
115
|
+
return parts.join('\n\n').trim()
|
|
116
|
+
}
|
package/src/store.js
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import fs from 'node:fs/promises'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { TranslationCache } from './cache.js'
|
|
4
|
+
import { normalizeTargetLang, targetLanguageName } from './config.js'
|
|
5
|
+
import { parseArticle } from './extract.js'
|
|
6
|
+
import { fetchHtml } from './fetch.js'
|
|
7
|
+
import { Glossary } from './glossary.js'
|
|
8
|
+
import { bilingualMarkdown, segmentMarkdown } from './segment.js'
|
|
9
|
+
import { Translator } from './translator.js'
|
|
10
|
+
import { nowIso, readJson, sha256, writeJsonAtomic, writeTextAtomic } from './util.js'
|
|
11
|
+
|
|
12
|
+
const TERMINAL = new Set(['done', 'partial', 'failed', 'interrupted'])
|
|
13
|
+
const ID_PATTERN = /^[a-z0-9-]+$/i
|
|
14
|
+
|
|
15
|
+
function sleep(ms) {
|
|
16
|
+
return new Promise(resolve => setTimeout(resolve, ms))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class BilingualStore {
|
|
20
|
+
constructor(config, { complete = null } = {}) {
|
|
21
|
+
this.config = config
|
|
22
|
+
this.dir = config.dir
|
|
23
|
+
this.docsDir = join(config.dir, 'docs')
|
|
24
|
+
this.cache = new TranslationCache({ file: join(config.dir, 'cache.json'), limit: config.cacheLimit })
|
|
25
|
+
this.glossary = new Glossary({ file: join(config.dir, 'glossary.json'), limit: config.glossaryLimit })
|
|
26
|
+
this.translator = new Translator({
|
|
27
|
+
config,
|
|
28
|
+
cache: this.cache,
|
|
29
|
+
glossary: this.glossary,
|
|
30
|
+
complete,
|
|
31
|
+
})
|
|
32
|
+
this.jobs = new Map()
|
|
33
|
+
this.loaded = false
|
|
34
|
+
this.readyPromise = null
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
get aiEnabled() {
|
|
38
|
+
return this.translator.enabled
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
docDir(id) {
|
|
42
|
+
if (!ID_PATTERN.test(String(id ?? ''))) throw new Error('无效的文档 id')
|
|
43
|
+
return join(this.docsDir, String(id))
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
docFile(id) {
|
|
47
|
+
return join(this.docDir(id), 'doc.json')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async ready() {
|
|
51
|
+
if (this.loaded) return
|
|
52
|
+
if (this.readyPromise !== null) return this.readyPromise
|
|
53
|
+
this.readyPromise = (async () => {
|
|
54
|
+
await fs.mkdir(this.docsDir, { recursive: true })
|
|
55
|
+
await this.cache.ready()
|
|
56
|
+
await this.glossary.ready()
|
|
57
|
+
await this.recover()
|
|
58
|
+
this.loaded = true
|
|
59
|
+
})().catch(error => {
|
|
60
|
+
this.readyPromise = null
|
|
61
|
+
throw error
|
|
62
|
+
})
|
|
63
|
+
return this.readyPromise
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async recover() {
|
|
67
|
+
let entries = []
|
|
68
|
+
try {
|
|
69
|
+
entries = await fs.readdir(this.docsDir, { withFileTypes: true })
|
|
70
|
+
} catch {
|
|
71
|
+
return
|
|
72
|
+
}
|
|
73
|
+
for (const entry of entries) {
|
|
74
|
+
if (!entry.isDirectory()) continue
|
|
75
|
+
const doc = await this.getDoc(entry.name)
|
|
76
|
+
if (doc !== null && doc.status === 'running') {
|
|
77
|
+
doc.status = 'interrupted'
|
|
78
|
+
doc.error = '进程重启,翻译已中断;可以在界面里重试'
|
|
79
|
+
await this.saveDoc(doc)
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async createDocFromUrl(url, options = {}) {
|
|
85
|
+
await this.ready()
|
|
86
|
+
const targetLang = normalizeTargetLang(options.targetLang, this.config.targetLang)
|
|
87
|
+
const fetched = await fetchHtml(url, this.config, { signal: options.signal })
|
|
88
|
+
const article = parseArticle(fetched.html, {
|
|
89
|
+
url: fetched.finalUrl,
|
|
90
|
+
maxMarkdownChars: this.config.maxMarkdownChars,
|
|
91
|
+
})
|
|
92
|
+
if (article.ok !== true) throw new Error(article.reason)
|
|
93
|
+
return this.createDoc({
|
|
94
|
+
markdown: article.markdown,
|
|
95
|
+
title: article.title,
|
|
96
|
+
url: fetched.finalUrl,
|
|
97
|
+
meta: {
|
|
98
|
+
siteName: article.siteName,
|
|
99
|
+
byline: article.byline,
|
|
100
|
+
published: article.published,
|
|
101
|
+
lang: article.lang,
|
|
102
|
+
excerpt: article.excerpt,
|
|
103
|
+
wordCount: article.wordCount,
|
|
104
|
+
charCount: article.charCount,
|
|
105
|
+
canonicalUrl: article.canonicalUrl,
|
|
106
|
+
requestedUrl: url,
|
|
107
|
+
fetchedAt: nowIso(),
|
|
108
|
+
httpStatus: fetched.status,
|
|
109
|
+
charset: fetched.charset,
|
|
110
|
+
bytes: fetched.bytes,
|
|
111
|
+
contentType: fetched.contentType,
|
|
112
|
+
},
|
|
113
|
+
}, { targetLang })
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async createDoc({ markdown, title, url = '', meta = {} }, options = {}) {
|
|
117
|
+
await this.ready()
|
|
118
|
+
const targetLang = normalizeTargetLang(options.targetLang, this.config.targetLang)
|
|
119
|
+
const { blocks, truncated } = segmentMarkdown(markdown, { maxBlocks: this.config.maxBlocks })
|
|
120
|
+
if (blocks.length === 0) throw new Error('正文为空,无法创建双语文档')
|
|
121
|
+
const id = sha256(`${url}\u0000${title}\u0000${Date.now()}\u0000${Math.random()}`).slice(0, 12)
|
|
122
|
+
const translatable = blocks.filter(block => block.translatable).length
|
|
123
|
+
const doc = {
|
|
124
|
+
schemaVersion: 1,
|
|
125
|
+
id,
|
|
126
|
+
title: title || '未命名文章',
|
|
127
|
+
url,
|
|
128
|
+
targetLang,
|
|
129
|
+
createdAt: nowIso(),
|
|
130
|
+
updatedAt: nowIso(),
|
|
131
|
+
status: 'pending',
|
|
132
|
+
error: '',
|
|
133
|
+
progress: 0,
|
|
134
|
+
truncated: Boolean(truncated || meta.truncated),
|
|
135
|
+
meta: { ...meta },
|
|
136
|
+
stats: {
|
|
137
|
+
requests: 0,
|
|
138
|
+
cacheHits: 0,
|
|
139
|
+
blocks: blocks.length,
|
|
140
|
+
translatable,
|
|
141
|
+
done: 0,
|
|
142
|
+
cached: 0,
|
|
143
|
+
failed: 0,
|
|
144
|
+
pending: translatable,
|
|
145
|
+
chars: markdown.length,
|
|
146
|
+
translatedChars: 0,
|
|
147
|
+
},
|
|
148
|
+
blocks: blocks.map((block, index) => ({
|
|
149
|
+
id: index,
|
|
150
|
+
type: block.type,
|
|
151
|
+
original: block.original,
|
|
152
|
+
translatable: block.translatable,
|
|
153
|
+
translation: '',
|
|
154
|
+
status: block.translatable ? 'pending' : 'skipped',
|
|
155
|
+
warning: '',
|
|
156
|
+
error: '',
|
|
157
|
+
})),
|
|
158
|
+
}
|
|
159
|
+
await writeTextAtomic(join(this.docDir(id), 'article.md'), markdown)
|
|
160
|
+
await this.saveDoc(doc)
|
|
161
|
+
return doc
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async saveDoc(doc) {
|
|
165
|
+
doc.updatedAt = nowIso()
|
|
166
|
+
await writeJsonAtomic(this.docFile(doc.id), doc)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async getDoc(id) {
|
|
170
|
+
try {
|
|
171
|
+
const doc = await readJson(this.docFile(id), null)
|
|
172
|
+
if (doc === null || typeof doc !== 'object' || !Array.isArray(doc.blocks)) return null
|
|
173
|
+
return doc
|
|
174
|
+
} catch {
|
|
175
|
+
return null
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async listDocs(options = {}) {
|
|
180
|
+
await this.ready()
|
|
181
|
+
const limit = options.limit ?? 30
|
|
182
|
+
let entries = []
|
|
183
|
+
try {
|
|
184
|
+
entries = await fs.readdir(this.docsDir, { withFileTypes: true })
|
|
185
|
+
} catch {
|
|
186
|
+
return []
|
|
187
|
+
}
|
|
188
|
+
const docs = []
|
|
189
|
+
for (const entry of entries) {
|
|
190
|
+
if (!entry.isDirectory()) continue
|
|
191
|
+
const doc = await this.getDoc(entry.name)
|
|
192
|
+
if (doc === null) continue
|
|
193
|
+
docs.push({
|
|
194
|
+
id: doc.id,
|
|
195
|
+
title: doc.title,
|
|
196
|
+
url: doc.url,
|
|
197
|
+
siteName: doc.meta?.siteName ?? '',
|
|
198
|
+
targetLang: doc.targetLang,
|
|
199
|
+
status: doc.status,
|
|
200
|
+
progress: doc.progress ?? 0,
|
|
201
|
+
createdAt: doc.createdAt,
|
|
202
|
+
updatedAt: doc.updatedAt,
|
|
203
|
+
stats: doc.stats,
|
|
204
|
+
})
|
|
205
|
+
}
|
|
206
|
+
docs.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
207
|
+
return docs.slice(0, limit)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async deleteDoc(id) {
|
|
211
|
+
await fs.rm(this.docDir(id), { recursive: true, force: true })
|
|
212
|
+
this.jobs.delete(id)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Start a translation in the background. Returns the doc immediately; callers
|
|
217
|
+
* can poll with waitForJob or re-read getDoc. The job is kept in memory only;
|
|
218
|
+
* a restart marks the doc interrupted during recover().
|
|
219
|
+
*/
|
|
220
|
+
async startJob(idOrDoc) {
|
|
221
|
+
const doc = typeof idOrDoc === 'string' ? await this.getDoc(idOrDoc) : idOrDoc
|
|
222
|
+
if (doc === null || doc === undefined) throw new Error('找不到文档')
|
|
223
|
+
if (doc.status === 'done') return doc
|
|
224
|
+
if (this.jobs.has(doc.id)) return doc
|
|
225
|
+
|
|
226
|
+
const job = { startedAt: nowIso(), promise: null }
|
|
227
|
+
job.promise = (async () => {
|
|
228
|
+
try {
|
|
229
|
+
await this.translator.translateDoc(doc, {
|
|
230
|
+
onProgress: async current => {
|
|
231
|
+
await this.saveDoc(current)
|
|
232
|
+
},
|
|
233
|
+
})
|
|
234
|
+
} catch (error) {
|
|
235
|
+
doc.status = 'failed'
|
|
236
|
+
doc.error = error instanceof Error ? error.message : String(error)
|
|
237
|
+
}
|
|
238
|
+
this.translator.refreshStats(doc)
|
|
239
|
+
await this.saveDoc(doc)
|
|
240
|
+
this.jobs.delete(doc.id)
|
|
241
|
+
})().catch(() => {})
|
|
242
|
+
this.jobs.set(doc.id, job)
|
|
243
|
+
return doc
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async waitForJob(id, options = {}) {
|
|
247
|
+
const timeoutMs = options.timeoutMs ?? 120_000
|
|
248
|
+
const intervalMs = options.intervalMs ?? 300
|
|
249
|
+
const deadline = Date.now() + timeoutMs
|
|
250
|
+
let doc = await this.getDoc(id)
|
|
251
|
+
if (doc === null) throw new Error('找不到文档')
|
|
252
|
+
while (!TERMINAL.has(doc.status) && Date.now() < deadline) {
|
|
253
|
+
await sleep(intervalMs)
|
|
254
|
+
doc = await this.getDoc(id)
|
|
255
|
+
if (doc === null) throw new Error('文档已被删除')
|
|
256
|
+
}
|
|
257
|
+
return doc
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async retryDoc(id) {
|
|
261
|
+
const doc = await this.getDoc(id)
|
|
262
|
+
if (doc === null) throw new Error('找不到文档')
|
|
263
|
+
for (const block of doc.blocks) {
|
|
264
|
+
if (block.translatable && block.status !== 'done' && block.status !== 'cached') {
|
|
265
|
+
block.status = 'pending'
|
|
266
|
+
block.error = ''
|
|
267
|
+
block.warning = ''
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
doc.status = 'pending'
|
|
271
|
+
doc.error = ''
|
|
272
|
+
this.translator.refreshStats(doc)
|
|
273
|
+
await this.saveDoc(doc)
|
|
274
|
+
await this.startJob(doc)
|
|
275
|
+
return doc
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async exportMarkdown(id) {
|
|
279
|
+
const doc = await this.getDoc(id)
|
|
280
|
+
if (doc === null) throw new Error('找不到文档')
|
|
281
|
+
const lines = [
|
|
282
|
+
`# ${doc.title}`,
|
|
283
|
+
'',
|
|
284
|
+
`> 原文:${doc.url || '(本地文本)'}`,
|
|
285
|
+
`> 目标语言:${targetLanguageName(doc.targetLang)}`,
|
|
286
|
+
`> 生成时间:${nowIso()}`,
|
|
287
|
+
'',
|
|
288
|
+
'---',
|
|
289
|
+
'',
|
|
290
|
+
bilingualMarkdown(doc.blocks),
|
|
291
|
+
'',
|
|
292
|
+
]
|
|
293
|
+
return lines.join('\n')
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async translateText(text, options = {}) {
|
|
297
|
+
await this.ready()
|
|
298
|
+
const value = String(text ?? '')
|
|
299
|
+
if (value.length > this.config.maxTranslateChars) {
|
|
300
|
+
throw new Error(`文本超过 ${this.config.maxTranslateChars} 字符上限`)
|
|
301
|
+
}
|
|
302
|
+
return this.translator.translateText(value, {
|
|
303
|
+
targetLang: normalizeTargetLang(options.targetLang, this.config.targetLang),
|
|
304
|
+
title: options.title,
|
|
305
|
+
signal: options.signal,
|
|
306
|
+
})
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
stats() {
|
|
310
|
+
return {
|
|
311
|
+
jobs: this.jobs.size,
|
|
312
|
+
cache: this.cache.stats(),
|
|
313
|
+
glossary: this.glossary.list().length,
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|