dsh-cait 1.0.3 → 1.0.5

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/lib/formats.js CHANGED
@@ -1,917 +1,972 @@
1
- /**
2
- * Dependency-free parsers/builders for the first-tier CAT exchange formats:
3
- * CSV, SRT, WebVTT, PO and a basic XLIFF 1.2 subset.
4
- *
5
- * These formats are intentionally shallow: inline markup is flattened to text,
6
- * complex subtitle styling and XLIFF extensions are not round-tripped. The
7
- * original source text is kept so the normal CAT/TM/glossary flow applies.
8
- */
9
- import { CatError } from './errors.js'
10
- import { decodeXml, escapeXml } from './xml.js'
11
-
12
- const SRT_TIME = /^(\d{1,3}):(\d{2}):(\d{2})[,.](\d{1,3})$/
13
- const VTT_TIME = /^(?:(\d{1,3}):)?(\d{1,2}):(\d{2})\.(\d{1,3})$/
14
- const INLINE_XML = /<\/?(?:bpt|ept|ph|g|x|bx|ex|mrk|sub|hi|span)\b[^>]*>/gi
15
- const INLINE_TOKEN = /\{(\d+)\}/g
16
-
17
- function formatError(code, message) {
18
- return new CatError(code, message)
19
- }
20
-
21
- function readXmlAttr(source, name) {
22
- const match = String(source ?? '').match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']*)["']`, 'i'))
23
- return match ? decodeXml(match[1]) : ''
24
- }
25
-
26
- /**
27
- * Convert XLIFF inline markup to stable {n} tokens while keeping the original
28
- * XML for export. This prevents <ph>, <bpt>/<ept> and <g> placeholders from
29
- * being silently dropped when a translation is written back.
30
- */
31
- function extractInline(raw) {
32
- const tokens = []
33
- const text = String(raw ?? '').replace(INLINE_XML, (xml) => {
34
- const token = `{${tokens.length + 1}}`
35
- tokens.push({ token, xml })
36
- return token
37
- })
38
- return { text: decodeXml(text).trim(), tokens }
39
- }
40
-
41
- /** Render a tokenised string back to XML, escaping only the text portions. */
42
- function renderInline(value, tokens) {
43
- const text = String(value ?? '')
44
- const map = new Map((Array.isArray(tokens) ? tokens : []).map((item) => [item.token, item.xml]))
45
- let output = ''
46
- let last = 0
47
- for (const match of text.matchAll(INLINE_TOKEN)) {
48
- output += escapeXml(text.slice(last, match.index))
49
- output += map.get(match[0]) ?? escapeXml(match[0])
50
- last = match.index + match[0].length
51
- }
52
- output += escapeXml(text.slice(last))
53
- return output
54
- }
55
-
56
- /** Tokens present in the source but missing from the target. */
57
- export function missingInlineTokens(tokens, target) {
58
- if (!Array.isArray(tokens) || !tokens.length) return []
59
- const value = String(target ?? '')
60
- return tokens.map((item) => item.token).filter((token) => !value.includes(token))
61
- }
62
-
63
- /** Append placeholders the translator omitted, so export never silently loses them. */
64
- function completeInline(value, tokens) {
65
- let output = String(value ?? '')
66
- for (const item of Array.isArray(tokens) ? tokens : []) {
67
- if (!output.includes(item.token)) output += `${output && !/\s$/.test(output) ? ' ' : ''}${item.token}`
68
- }
69
- return output
70
- }
71
-
72
- export function parseCsvRows(text) {
73
- const input = String(text ?? '').replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n')
74
- const rows = []
75
- let row = []
76
- let field = ''
77
- let quoted = false
78
-
79
- for (let index = 0; index < input.length; index += 1) {
80
- const char = input[index]
81
- if (quoted) {
82
- if (char === '"') {
83
- if (input[index + 1] === '"') {
84
- field += '"'
85
- index += 1
86
- } else {
87
- quoted = false
88
- }
89
- } else {
90
- field += char
91
- }
92
- continue
93
- }
94
-
95
- if (char === '"' && field === '') {
96
- quoted = true
97
- } else if (char === ',') {
98
- row.push(field)
99
- field = ''
100
- } else if (char === '\n') {
101
- row.push(field)
102
- rows.push(row)
103
- row = []
104
- field = ''
105
- } else {
106
- field += char
107
- }
108
- }
109
-
110
- if (quoted) throw formatError('CSV_PARSE', 'CSV 引号未闭合。')
111
- if (field.length || row.length) {
112
- row.push(field)
113
- rows.push(row)
114
- }
115
- return rows
116
- }
117
-
118
- export function parseCsv(text, { sourceColumn, targetColumn } = {}) {
119
- const rows = parseCsvRows(text)
120
- if (!rows.length) throw formatError('CSV_PARSE', 'CSV 中没有可用的行。')
121
-
122
- const normalize = (value) => String(value ?? '').trim().toLowerCase()
123
- const sourceAliases = new Set(['source', 'src', 'original', '原文', '源文', '源文本'])
124
- const targetAliases = new Set(['target', 'tgt', 'translation', '译文', '目標', '目标', '目标文本'])
125
- const first = rows[0].map(normalize)
126
- const hasHeader = first.some((value) => sourceAliases.has(value) || targetAliases.has(value))
127
- const resolveColumn = (rawValue, aliases, fallback) => {
128
- const value = String(rawValue ?? '').trim()
129
- if (!value) return fallback
130
- if (/^\d+$/.test(value)) {
131
- const index = Number(value) - 1
132
- if (index < 0) throw formatError('CSV_PARSE', 'CSV 列号从 1 开始。')
133
- return index
134
- }
135
- const index = first.findIndex((item) => item === value.toLowerCase())
136
- if (index < 0) throw formatError('CSV_PARSE', `CSV 中找不到列“${value}”。`)
137
- return index
138
- }
139
-
140
- let sourceIndex = first.findIndex((value) => sourceAliases.has(value))
141
- let targetIndex = first.findIndex((value) => targetAliases.has(value))
142
- let start = 0
143
-
144
- if (sourceColumn !== undefined || targetColumn !== undefined) {
145
- sourceIndex = resolveColumn(sourceColumn, sourceAliases, sourceIndex >= 0 ? sourceIndex : 0)
146
- targetIndex = resolveColumn(targetColumn, targetAliases, targetIndex)
147
- start = hasHeader ? 1 : 0
148
- } else if (sourceIndex >= 0 && targetIndex >= 0) {
149
- start = 1
150
- } else {
151
- sourceIndex = 0
152
- targetIndex = rows[0].length > 1 ? 1 : -1
153
- }
154
-
155
- const maxColumns = rows.reduce((max, row) => Math.max(max, row.length), 0)
156
- if (sourceIndex < 0 || sourceIndex >= maxColumns) {
157
- throw formatError('CSV_PARSE', 'CSV 源文列不存在。')
158
- }
159
- if (targetIndex >= maxColumns) {
160
- throw formatError('CSV_PARSE', 'CSV 译文列不存在。')
161
- }
162
-
163
- const segments = []
164
- for (let index = start; index < rows.length; index += 1) {
165
- const row = rows[index]
166
- const source = String(row[sourceIndex] ?? '').trim()
167
- if (!source) continue
168
- const target = targetIndex >= 0 ? String(row[targetIndex] ?? '').trim() : ''
169
- segments.push({
170
- source,
171
- target,
172
- paragraph: segments.length,
173
- meta: { format: 'csv' },
174
- })
175
- }
176
-
177
- if (!segments.length) throw formatError('CSV_NO_UNITS', 'CSV 中没有可用的源文行。')
178
- return { format: 'csv', segments, warnings: [] }
179
- }
180
-
181
- function parseSrtTime(value) {
182
- const match = String(value).trim().match(SRT_TIME)
183
- if (!match) return null
184
- const [, hours, minutes, seconds, millis] = match
185
- return Number(hours) * 3600000 + Number(minutes) * 60000 + Number(seconds) * 1000 + Number(millis.padEnd(3, '0'))
186
- }
187
-
188
- export function formatSrtTime(milliseconds) {
189
- const total = Math.max(0, Math.round(Number(milliseconds) || 0))
190
- const hours = Math.floor(total / 3600000)
191
- const minutes = Math.floor((total % 3600000) / 60000)
192
- const seconds = Math.floor((total % 60000) / 1000)
193
- const millis = total % 1000
194
- return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')},${String(millis).padStart(3, '0')}`
195
- }
196
-
197
- function stripSubtitleMarkup(value) {
198
- const assOverrides = String(value).match(/\{\\[^}]+\}/g) ?? []
199
- return {
200
- // Semantic tags such as <i>, <b>, <font> and WebVTT <c>/<v>/<ruby> are
201
- // meaningful translation content and stay in the string verbatim.
202
- text: decodeXml(String(value).replace(/<br\s*\/?>/gi, '\n').replace(/\{\\[^}]+\}/g, '')),
203
- count: assOverrides.length,
204
- }
205
- }
206
-
207
- function parseSubtitleBlocks(text, kind) {
208
- const input = String(text ?? '').replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n').trim()
209
- if (!input) throw formatError(`${kind.toUpperCase()}_PARSE`, `${kind.toUpperCase()} 文件内容为空。`)
210
-
211
- const blocks = input.split(/\n{2,}/)
212
- const segments = []
213
- const warnings = []
214
- let markupCount = 0
215
-
216
- for (const block of blocks) {
217
- const lines = block.split('\n')
218
- if (!lines.length) continue
219
- let cursor = 0
220
- if (lines[0].trim().toUpperCase().startsWith('WEBVTT')) {
221
- lines.shift()
222
- while (lines.length && !lines[0].trim()) lines.shift()
223
- if (!lines.length) continue
224
- }
225
- if (lines[0].trim().startsWith('NOTE') || lines[0].trim().startsWith('STYLE') || lines[0].trim().startsWith('REGION')) continue
226
-
227
- let identifier = ''
228
- if (!lines[cursor].includes('-->')) {
229
- identifier = lines[cursor].trim()
230
- cursor += 1
231
- }
232
- if (!lines[cursor]?.includes('-->')) continue
233
- const timing = lines[cursor].trim()
234
- cursor += 1
235
-
236
- const timingMatch = timing.match(/^(\S+)\s*-->\s*(\S+)(.*)$/)
237
- if (!timingMatch) {
238
- throw formatError(`${kind.toUpperCase()}_PARSE`, `字幕时间轴无效: ${timing}`)
239
- }
240
- const start = kind === 'srt' ? parseSrtTime(timingMatch[1]) : parseVttTime(timingMatch[1])
241
- const end = kind === 'srt' ? parseSrtTime(timingMatch[2]) : parseVttTime(timingMatch[2])
242
- if (start === null || end === null) {
243
- throw formatError(`${kind.toUpperCase()}_PARSE`, `字幕时间轴无效: ${timing}`)
244
- }
245
- if (end <= start) {
246
- throw formatError(
247
- `${kind.toUpperCase()}_PARSE`,
248
- `字幕结束时间必须晚于开始时间: ${timing}`,
249
- )
250
- }
251
-
252
- const rawText = lines.slice(cursor).join('\n').trim()
253
- if (!rawText) continue
254
- const stripped = stripSubtitleMarkup(rawText)
255
- markupCount += stripped.count
256
- const text = stripped.text.trim()
257
- if (!text) continue
258
- segments.push({
259
- source: text,
260
- target: '',
261
- paragraph: segments.length,
262
- meta: {
263
- format: kind,
264
- start,
265
- end,
266
- settings: timingMatch[3].trim(),
267
- identifier,
268
- },
269
- })
270
- }
271
-
272
- if (!segments.length) throw formatError(`${kind.toUpperCase()}_NO_UNITS`, `${kind.toUpperCase()} 中没有可用的字幕。`)
273
- if (markupCount) {
274
- warnings.push({
275
- code: `${kind.toUpperCase()}_INLINE_MARKUP_LOST`,
276
- count: markupCount,
277
- message: `${kind.toUpperCase()} 含 ${markupCount} 个 ASS 样式覆盖标记({\\...}),导入时已移除;语义标签已保留。`,
278
- })
279
- }
280
- return { format: kind, segments, warnings }
281
- }
282
-
283
- export function parseSrt(text) {
284
- return parseSubtitleBlocks(text, 'srt')
285
- }
286
-
287
- function parseVttTime(value) {
288
- const match = String(value).trim().match(VTT_TIME)
289
- if (!match) return null
290
- const [, hours, minutes, seconds, millis] = match
291
- return Number(hours || 0) * 3600000 + Number(minutes) * 60000 + Number(seconds) * 1000 + Number(millis.padEnd(3, '0'))
292
- }
293
-
294
- export function formatVttTime(milliseconds) {
295
- const total = Math.max(0, Math.round(Number(milliseconds) || 0))
296
- const hours = Math.floor(total / 3600000)
297
- const minutes = Math.floor((total % 3600000) / 60000)
298
- const seconds = Math.floor((total % 60000) / 1000)
299
- const millis = total % 1000
300
- return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}.${String(millis).padStart(3, '0')}`
301
- }
302
-
303
- export function parseVtt(text) {
304
- return parseSubtitleBlocks(text, 'vtt')
305
- }
306
-
307
- function subtitleText(segment) {
308
- return String(segment.target || segment.source || '').trim()
309
- }
310
-
311
- function cueTimes(segment, fallbackStart) {
312
- const start = Number(segment.meta?.start)
313
- const end = Number(segment.meta?.end)
314
- if (Number.isFinite(start) && start >= 0 && Number.isFinite(end) && end > start) {
315
- return { start, end }
316
- }
317
- // Text-only documents (and any cue without usable timing metadata) start
318
- // where the previous cue ended. This avoids the old index * 2000 fallback
319
- // overlapping an explicitly timed cue that sits earlier in the document.
320
- const safeStart = Number.isFinite(start) && start >= 0 ? start : fallbackStart
321
- return { start: safeStart, end: safeStart + 2000 }
322
- }
323
-
324
- function buildCues(segments) {
325
- let cursor = 0
326
- return segments.map((segment) => {
327
- const times = cueTimes(segment, cursor)
328
- cursor = Math.max(cursor, times.end)
329
- return { segment, times }
330
- })
331
- }
332
-
333
- export function buildSrt(doc) {
334
- return buildCues(doc.segments)
335
- .map(({ segment, times }, index) => [
336
- String(index + 1),
337
- `${formatSrtTime(times.start)} --> ${formatSrtTime(times.end)}`,
338
- subtitleText(segment),
339
- '',
340
- ].join('\n'))
341
- .join('\n')
342
- }
343
-
344
- export function buildVtt(doc) {
345
- const cues = buildCues(doc.segments).map(({ segment, times }) => {
346
- const identifier = segment.meta?.identifier ? `${segment.meta.identifier}\n` : ''
347
- return `${identifier}${formatVttTime(times.start)} --> ${formatVttTime(times.end)}\n${subtitleText(segment)}\n`
348
- })
349
- return `WEBVTT\n\n${cues.join('\n')}`
350
- }
351
-
352
- function parsePoQuoted(raw) {
353
- const match = String(raw).trim().match(/^"((?:\\.|[^"\\])*)"$/)
354
- if (!match) return null
355
- return match[1].replace(/\\(n|t|r|"|\\)/g, (all, char) => {
356
- if (char === 'n') return '\n'
357
- if (char === 't') return '\t'
358
- if (char === 'r') return '\r'
359
- return char
360
- })
361
- }
362
-
363
- function poField(line) {
364
- const match = line.match(/^(msgctxt|msgid_plural|msgid|msgstr(?:\[\d+\])?)\s+(.*)$/)
365
- if (!match) return null
366
- const value = parsePoQuoted(match[2])
367
- if (value === null) return null
368
- return { name: match[1], value }
369
- }
370
-
371
- export function parsePo(text) {
372
- const input = String(text ?? '').replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n')
373
- if (!input.trim()) throw formatError('PO_PARSE', 'PO 文件内容为空。')
374
-
375
- const segments = []
376
- const obsolete = []
377
- let entry = null
378
- let current = null
379
- let pendingComments = []
380
- let obsoleteBlock = null
381
-
382
- const flushObsolete = () => {
383
- if (!obsoleteBlock?.length) return
384
- const block = obsoleteBlock.join('\n').trimEnd()
385
- if (block) obsolete.push(block)
386
- obsoleteBlock = null
387
- }
388
-
389
- const flush = () => {
390
- if (!entry) return
391
- const source = String(entry.msgid ?? '').trim()
392
- if (source) {
393
- const msgidPlural = String(entry.msgid_plural ?? '').trim()
394
- const pluralKeys = Object.keys(entry.msgstr ?? {})
395
- .filter((key) => /^\d+$/.test(key))
396
- .sort((left, right) => Number(left) - Number(right))
397
- const plurals = pluralKeys
398
- .map((key) => String(entry.msgstr[key] ?? '').trim())
399
- .filter(Boolean)
400
- const target = String(entry.msgstr?.[''] ?? plurals[0] ?? '').trim()
401
- const comments = entry.comments.filter(Boolean)
402
- segments.push({
403
- source,
404
- target,
405
- paragraph: segments.length,
406
- meta: {
407
- format: 'po',
408
- context: String(entry.msgctxt ?? '').trim(),
409
- msgidPlural,
410
- plural: Boolean(msgidPlural),
411
- ...(comments.length ? { comments } : {}),
412
- ...(plurals.length ? { plurals } : {}),
413
- },
414
- })
415
- }
416
- entry = null
417
- current = null
418
- }
419
-
420
- for (const rawLine of input.split('\n')) {
421
- const line = rawLine.trim()
422
- if (!line) {
423
- flush()
424
- flushObsolete()
425
- continue
426
- }
427
- if (line.startsWith('#~')) {
428
- if (!obsoleteBlock) {
429
- flush()
430
- obsoleteBlock = []
431
- }
432
- obsoleteBlock.push(rawLine.replace(/^#~\s?/, ''))
433
- continue
434
- }
435
- if (obsoleteBlock) {
436
- obsoleteBlock.push(rawLine)
437
- continue
438
- }
439
- if (line.startsWith('#')) {
440
- const comment = line.replace(/^#[.,:|\s]*/, '').trim()
441
- if (comment) {
442
- if (entry) entry.comments.push(comment)
443
- else pendingComments.push(comment)
444
- }
445
- continue
446
- }
447
-
448
- const field = poField(line)
449
- if (field) {
450
- entry ??= { msgstr: {}, comments: pendingComments.splice(0) }
451
- current = field.name
452
- if (current.startsWith('msgstr')) {
453
- entry.msgstr[current === 'msgstr' ? '' : current.match(/\[(\d+)\]/)?.[1] ?? '0'] = field.value
454
- } else {
455
- entry[current] = field.value
456
- }
457
- continue
458
- }
459
- if (line.startsWith('"') && current) {
460
- const value = parsePoQuoted(line)
461
- if (value === null) continue
462
- if (current.startsWith('msgstr')) {
463
- const key = current === 'msgstr' ? '' : current.match(/\[(\d+)\]/)?.[1] ?? '0'
464
- entry.msgstr[key] = `${entry.msgstr[key] ?? ''}${value}`
465
- } else {
466
- entry[current] = `${entry[current] ?? ''}${value}`
467
- }
468
- }
469
- }
470
- flush()
471
- flushObsolete()
472
-
473
- if (!segments.length) throw formatError('PO_NO_UNITS', 'PO 中没有可用的 msgid/msgstr 条目。')
474
- return { format: 'po', segments, obsolete, warnings: [] }
475
- }
476
-
477
- function poEscape(value) {
478
- return String(value ?? '')
479
- .replace(/\\/g, '\\\\')
480
- .replace(/"/g, '\\"')
481
- .replace(/\n/g, '\\n')
482
- .replace(/\t/g, '\\t')
483
- .replace(/\r/g, '\\r')
484
- }
485
-
486
- function poLine(field, value) {
487
- return `${field} "${poEscape(value)}"`
488
- }
489
-
490
- export function buildPo(doc) {
491
- const header = [
492
- 'msgid ""',
493
- 'msgstr ""',
494
- '"Content-Type: text/plain; charset=UTF-8\\n"',
495
- `"Language: ${doc.targetLang}\\n"`,
496
- '',
497
- ].join('\n')
498
-
499
- const entries = doc.segments.map((segment) => {
500
- const context = String(segment.meta?.context ?? '').trim()
501
- const plural = String(segment.meta?.msgidPlural ?? '').trim()
502
- const target = String(segment.target || segment.source || '').trim()
503
- const comments = Array.isArray(segment.meta?.comments) ? segment.meta.comments : []
504
- const lines = comments.filter(Boolean).map((comment) => `#. ${comment}`)
505
- if (context) lines.push(poLine('msgctxt', context))
506
- lines.push(poLine('msgid', segment.source))
507
- if (plural) {
508
- const forms = Array.isArray(segment.meta?.plurals) ? segment.meta.plurals : []
509
- lines.push(poLine('msgid_plural', plural))
510
- lines.push(poLine('msgstr[0]', target))
511
- for (let index = 1; index < Math.max(forms.length, 2); index += 1) {
512
- lines.push(poLine(`msgstr[${index}]`, forms[index] || target))
513
- }
514
- } else {
515
- lines.push(poLine('msgstr', target))
516
- }
517
- return lines.join('\n')
518
- })
519
-
520
- const obsolete = Array.isArray(doc.formatMeta?.poObsolete)
521
- ? doc.formatMeta.poObsolete
522
- .filter((block) => typeof block === 'string' && block.trim())
523
- .map((block) => block.split('\n').map((line) => `#~ ${line}`).join('\n'))
524
- : []
525
-
526
- const blocks = [...entries, ...obsolete].filter(Boolean)
527
- return `${header}\n${blocks.join('\n\n')}\n`
528
- }
529
-
530
- function parseXliffUnit(body, attrs, format, tokens) {
531
- const sourceMatch = body.match(/<(?:[\w.-]+:)?source\b[^>]*>([\s\S]*?)<\/(?:[\w.-]+:)?source>/i)
532
- ?? body.match(/<(?:[\w.-]+:)?source\b[^>]*\/>/i)
533
- if (!sourceMatch) return null
534
- const sourceRaw = sourceMatch[1] ?? ''
535
- const source = extractInline(sourceRaw)
536
- if (!source.text) return null
537
- const targetMatch = body.match(/<(?:[\w.-]+:)?target\b[^>]*>([\s\S]*?)<\/(?:[\w.-]+:)?target>/i)
538
- ?? body.match(/<(?:[\w.-]+:)?target\b[^>]*\/>/i)
539
- const target = targetMatch ? extractInline(targetMatch[1] ?? '').text : ''
540
- tokens.push(...source.tokens)
541
- return {
542
- source: source.text,
543
- target,
544
- paragraph: 0,
545
- meta: {
546
- format,
547
- xliffId: readXmlAttr(attrs, 'id'),
548
- ...(source.tokens.length ? { inline: source.tokens } : {}),
549
- },
550
- }
551
- }
552
-
553
- function parseXliff2(input, rootAttrs) {
554
- const sourceLang = readXmlAttr(rootAttrs, 'srcLang') || readXmlAttr(rootAttrs, 'source-language')
555
- const targetLang = readXmlAttr(rootAttrs, 'trgLang') || readXmlAttr(rootAttrs, 'target-language')
556
- const units = []
557
- const inlineTokens = []
558
- const unitRe = /<(?:[\w.-]+:)?unit\b([^>]*)>([\s\S]*?)<\/(?:[\w.-]+:)?unit>/gi
559
- let match
560
- while ((match = unitRe.exec(input))) {
561
- const unit = parseXliffUnit(match[2], match[1], 'xliff2', inlineTokens)
562
- if (!unit) continue
563
- unit.paragraph = units.length
564
- units.push(unit)
565
- }
566
- if (!units.length) throw formatError('XLIFF_NO_UNITS', 'XLIFF 中没有可用的 unit/segment。')
567
- return { format: 'xliff2', sourceLang, targetLang, segments: units, warnings: [] }
568
- }
569
-
570
- export function parseXliff(text) {
571
- const input = String(text ?? '').replace(/^\uFEFF/, '')
572
- if (!input.trim()) throw formatError('XLIFF_PARSE', 'XLIFF 文件内容为空。')
573
-
574
- const rootTag = input.match(/<((?:[\w.-]+:)?xliff)\b([^>]*)>/i)
575
- const rootAttrs = rootTag?.[2] ?? ''
576
- const version = readXmlAttr(rootAttrs, 'version')
577
- const looksLikeXliff2 = /^2\./i.test(version)
578
- || (!/<(?:[\w.-]+:)?trans-unit\b/i.test(input) && /<(?:[\w.-]+:)?unit\b/i.test(input))
579
- if (looksLikeXliff2) return parseXliff2(input, rootAttrs)
580
-
581
- const fileTag = input.match(/<((?:[\w.-]+:)?file)\b([^>]*)>/i)
582
- const sourceLang = readXmlAttr(fileTag?.[2], 'source-language')
583
- const targetLang = readXmlAttr(fileTag?.[2], 'target-language')
584
-
585
- const units = []
586
- const unitRe = /<(?:[\w.-]+:)?trans-unit\b([^>]*)>([\s\S]*?)<\/(?:[\w.-]+:)?trans-unit>/gi
587
- let match
588
- while ((match = unitRe.exec(input))) {
589
- const unit = parseXliffUnit(match[2], match[1], 'xliff', [])
590
- if (!unit) continue
591
- unit.paragraph = units.length
592
- units.push(unit)
593
- }
594
-
595
- if (!units.length) throw formatError('XLIFF_NO_UNITS', 'XLIFF 中没有可用的 trans-unit。')
596
- return { format: 'xliff', sourceLang, targetLang, segments: units, warnings: [] }
597
- }
598
-
599
- export function buildXliff(doc) {
600
- const units = doc.segments.map((segment, index) => {
601
- const id = String(segment.meta?.xliffId || index + 1)
602
- const tokens = Array.isArray(segment.meta?.inline) ? segment.meta.inline : []
603
- const target = completeInline(segment.target || segment.source, tokens)
604
- return [
605
- ` <trans-unit id="${escapeXml(id)}">`,
606
- ` <source xml:lang="${escapeXml(doc.sourceLang)}">${renderInline(segment.source, tokens)}</source>`,
607
- ` <target xml:lang="${escapeXml(doc.targetLang)}">${renderInline(target, tokens)}</target>`,
608
- ' </trans-unit>',
609
- ].join('\n')
610
- })
611
- return [
612
- '<?xml version="1.0" encoding="UTF-8"?>',
613
- '<xliff version="1.2">',
614
- ` <file source-language="${escapeXml(doc.sourceLang)}" target-language="${escapeXml(doc.targetLang)}" datatype="plaintext" original="${escapeXml(doc.name)}">`,
615
- ' <body>',
616
- ...units,
617
- ' </body>',
618
- ' </file>',
619
- '</xliff>',
620
- '',
621
- ].join('\n')
622
- }
623
-
624
- export function buildXliff2(doc) {
625
- const units = doc.segments.map((segment, index) => {
626
- const id = String(segment.meta?.xliffId || index + 1)
627
- const tokens = Array.isArray(segment.meta?.inline) ? segment.meta.inline : []
628
- const target = completeInline(segment.target || segment.source, tokens)
629
- return [
630
- ` <unit id="${escapeXml(id)}">`,
631
- ' <segment>',
632
- ` <source>${renderInline(segment.source, tokens)}</source>`,
633
- ` <target>${renderInline(target, tokens)}</target>`,
634
- ' </segment>',
635
- ' </unit>',
636
- ].join('\n')
637
- })
638
- return [
639
- '<?xml version="1.0" encoding="UTF-8"?>',
640
- '<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0"',
641
- ` srcLang="${escapeXml(doc.sourceLang)}" trgLang="${escapeXml(doc.targetLang)}">`,
642
- ' <file id="f1">',
643
- ...units,
644
- ' </file>',
645
- '</xliff>',
646
- '',
647
- ].join('\n')
648
- }
649
-
650
- function htmlToText(input) {
651
- let text = String(input ?? '').replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n')
652
- text = text
653
- .replace(/<!--[\s\S]*?-->/g, '')
654
- .replace(/<(script|style|noscript|head)\b[\s\S]*?<\/\1>/gi, '')
655
- .replace(/<br\s*\/?>/gi, '\n')
656
- .replace(/<\/(?:p|div|li|h[1-6]|section|article|blockquote|pre|tr)>/gi, '\n\n')
657
- .replace(/<\/(?:td|th)>/gi, '\t')
658
- .replace(/<[^>]+>/g, '')
659
- return decodeXml(text)
660
- .replace(/[ \t]+\n/g, '\n')
661
- .replace(/\n{3,}/g, '\n\n')
662
- .trim()
663
- }
664
-
665
- export function parseHtml(text) {
666
- const input = String(text ?? '')
667
- if (!input.trim()) throw formatError('HTML_PARSE', 'HTML 文件内容为空。')
668
- const plain = htmlToText(input)
669
- if (!plain) throw formatError('HTML_NO_UNITS', 'HTML 中没有可用的正文。')
670
- const segments = plain
671
- .split(/\n{2,}/)
672
- .map((part) => part.trim())
673
- .filter(Boolean)
674
- .map((source, index) => ({
675
- source,
676
- target: '',
677
- paragraph: index,
678
- meta: { format: 'html' },
679
- }))
680
- if (!segments.length) throw formatError('HTML_NO_UNITS', 'HTML 中没有可用的正文。')
681
- return { format: 'html', segments, warnings: [] }
682
- }
683
-
684
- export function buildHtml(doc) {
685
- const groups = new Map()
686
- for (const segment of doc.segments) {
687
- const key = segment.paragraph ?? 0
688
- if (!groups.has(key)) groups.set(key, [])
689
- groups.get(key).push(String(segment.target || segment.source || '').trim())
690
- }
691
- const paragraphs = [...groups.values()]
692
- .map((parts) => parts.filter(Boolean).join(' '))
693
- .filter(Boolean)
694
- .map((text) => ` <p>${escapeXml(text)}</p>`)
695
- .join('\n')
696
- return [
697
- '<!doctype html>',
698
- '<html lang="' + escapeXml(doc.targetLang || 'en') + '">',
699
- '<head><meta charset="utf-8"><title>' + escapeXml(doc.name || 'CAIT export') + '</title></head>',
700
- '<body>',
701
- paragraphs,
702
- '</body>',
703
- '</html>',
704
- '',
705
- ].join('\n')
706
- }
707
-
708
- function escapeJsonPointer(value) {
709
- return String(value).replace(/~/g, '~0').replace(/\//g, '~1')
710
- }
711
-
712
- function unescapeJsonPointer(value) {
713
- return String(value).replace(/~1/g, '/').replace(/~0/g, '~')
714
- }
715
-
716
- function walkJsonStrings(value, pointer, visit) {
717
- if (typeof value === 'string') {
718
- visit(value, pointer)
719
- return
720
- }
721
- if (Array.isArray(value)) {
722
- value.forEach((item, index) => walkJsonStrings(item, `${pointer}/${index}`, visit))
723
- return
724
- }
725
- if (value && typeof value === 'object') {
726
- for (const [key, item] of Object.entries(value)) {
727
- walkJsonStrings(item, `${pointer}/${escapeJsonPointer(key)}`, visit)
728
- }
729
- }
730
- }
731
-
732
- function setJsonPointer(root, pointer, value) {
733
- const parts = String(pointer).split('/').slice(1).map(unescapeJsonPointer)
734
- if (!parts.length) return value
735
- let current = root
736
- for (let index = 0; index < parts.length - 1; index += 1) {
737
- if (current == null) throw new Error('JSON path does not exist')
738
- current = current[parts[index]]
739
- }
740
- if (current == null) throw new Error('JSON path does not exist')
741
- current[parts[parts.length - 1]] = value
742
- return root
743
- }
744
-
745
- export function parseJson(text) {
746
- const input = String(text ?? '')
747
- if (!input.trim()) throw formatError('JSON_PARSE', 'JSON 文件内容为空。')
748
- let root
749
- try {
750
- root = JSON.parse(input)
751
- } catch (error) {
752
- throw formatError('JSON_PARSE', `JSON 解析失败: ${error.message}`)
753
- }
754
- const segments = []
755
- walkJsonStrings(root, '', (source, pointer) => {
756
- if (!source.trim()) return
757
- segments.push({
758
- source,
759
- target: '',
760
- paragraph: segments.length,
761
- meta: { format: 'json', jsonPath: pointer },
762
- })
763
- })
764
- if (!segments.length) throw formatError('JSON_NO_UNITS', 'JSON 中没有可翻译的字符串。')
765
- return {
766
- format: 'json',
767
- segments,
768
- formatMeta: { jsonTemplate: JSON.stringify(root) },
769
- warnings: [],
770
- }
771
- }
772
-
773
- export function buildJson(doc) {
774
- let root
775
- try {
776
- root = doc.formatMeta?.jsonTemplate ? JSON.parse(doc.formatMeta.jsonTemplate) : {}
777
- } catch {
778
- root = {}
779
- }
780
- for (const segment of doc.segments) {
781
- const pointer = segment.meta?.jsonPath
782
- if (!pointer) continue
783
- const text = String(segment.target || segment.source || '')
784
- setJsonPointer(root, pointer, text)
785
- }
786
- return `${JSON.stringify(root, null, 2)}\n`
787
- }
788
-
789
- const RTF_DESTINATION_GROUP = /\{\\\*?\\?(?:fonttbl|colortbl|stylesheet|info|pict|header|footer|object|themedata|colorschememapping|datastore|latentstyles|rsidtbl|generator|xmlnstbl)\b[^{}]*(?:\{[^{}]*\}[^{}]*)*\}/gi
790
-
791
- function rtfUnicode(code) {
792
- const value = Number(code)
793
- return String.fromCharCode(value < 0 ? value + 65536 : value)
794
- }
795
-
796
- export function parseRtf(text) {
797
- let input = String(text ?? '').replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n')
798
- if (!input.trim()) throw formatError('RTF_PARSE', 'RTF 文件内容为空。')
799
- if (!input.trimStart().startsWith('{\\rtf')) {
800
- throw formatError('RTF_PARSE', 'RTF 文件缺少 {\\rtf 头。')
801
- }
802
- let previous
803
- do {
804
- previous = input
805
- input = input.replace(RTF_DESTINATION_GROUP, '')
806
- } while (previous !== input)
807
-
808
- let output = ''
809
- let index = 0
810
- let unicodeSkip = 1
811
- while (index < input.length) {
812
- const char = input[index]
813
- if (char === '{' || char === '}') {
814
- index += 1
815
- continue
816
- }
817
- if (char !== '\\') {
818
- output += char
819
- index += 1
820
- continue
821
- }
822
- const next = input[index + 1]
823
- if (next === '\\' || next === '{' || next === '}') {
824
- output += next
825
- index += 2
826
- continue
827
- }
828
- if (next === "'") {
829
- const hex = input.slice(index + 2, index + 4)
830
- if (!/^[0-9a-f]{2}$/i.test(hex)) throw formatError('RTF_PARSE', 'RTF 十六进制转义无效。')
831
- output += Buffer.from([Number.parseInt(hex, 16)]).toString('latin1')
832
- index += 4
833
- continue
834
- }
835
- if (next === '*') {
836
- index += 2
837
- continue
838
- }
839
- let cursor = index + 1
840
- let sign = 1
841
- if (input[cursor] === '-') {
842
- sign = -1
843
- cursor += 1
844
- }
845
- const wordStart = cursor
846
- while (/[a-z]/i.test(input[cursor] ?? '')) cursor += 1
847
- const word = input.slice(wordStart, cursor).toLowerCase()
848
- const numberStart = cursor
849
- while (/\d/.test(input[cursor] ?? '')) cursor += 1
850
- const number = input.slice(numberStart, cursor)
851
- if (input[cursor] === ' ') cursor += 1
852
- index = cursor
853
- if (!word) continue
854
- const value = number ? sign * Number(number) : null
855
- if (word === 'par') output += '\n\n'
856
- else if (word === 'line') output += '\n'
857
- else if (word === 'tab') output += '\t'
858
- else if (word === 'uc' && value !== null) unicodeSkip = Math.max(0, value)
859
- else if (word === 'u' && value !== null) {
860
- output += rtfUnicode(value)
861
- let skip = unicodeSkip
862
- while (skip > 0 && index < input.length) {
863
- index += 1
864
- skip -= 1
865
- }
866
- } else if (word === 'bin' && value !== null && value > 0) {
867
- index += value
868
- }
869
- }
870
-
871
- const segments = output
872
- .split(/\n{2,}/)
873
- .map((part) => part.replace(/^\n+|\n+$/g, '').trim())
874
- .filter(Boolean)
875
- .map((source, paragraph) => ({
876
- source,
877
- target: '',
878
- paragraph,
879
- meta: { format: 'rtf' },
880
- }))
881
- if (!segments.length) throw formatError('RTF_NO_UNITS', 'RTF 中没有可用的正文。')
882
- return { format: 'rtf', segments, warnings: [] }
883
- }
884
-
885
- function escapeRtf(value) {
886
- let output = ''
887
- for (const char of String(value)) {
888
- const code = char.codePointAt(0)
889
- if (char === '\\' || char === '{' || char === '}') output += `\\${char}`
890
- else if (char === '\n') output += '\\line '
891
- else if (char === '\t') output += '\\tab '
892
- else if (code >= 0x20 && code < 0x7f) output += char
893
- else if (code <= 0xffff) output += `\\u${code}?`
894
- else {
895
- const high = Math.floor((code - 0x10000) / 0x400) + 0xd800
896
- const low = ((code - 0x10000) % 0x400) + 0xdc00
897
- output += `\\u${high}?\\u${low}?`
898
- }
899
- }
900
- return output
901
- }
902
-
903
- export function buildRtf(doc) {
904
- const groups = new Map()
905
- for (const segment of doc.segments) {
906
- const key = segment.paragraph ?? 0
907
- if (!groups.has(key)) groups.set(key, [])
908
- groups.get(key).push(String(segment.target || segment.source || '').trim())
909
- }
910
- const body = [...groups.values()]
911
- .map((parts) => parts.filter(Boolean).join(' '))
912
- .filter(Boolean)
913
- .map((text) => `\\pard\\f0\\fs22 ${escapeRtf(text)}\\par`)
914
- .join('\n')
915
- return `{\\rtf1\\ansi\\deff0{\\fonttbl{\\f0 Calibri;}}\\viewkind4\\uc1\n${body}\n}\n`
916
- }
917
-
1
+ /**
2
+ * Dependency-free parsers/builders for the first-tier CAT exchange formats:
3
+ * CSV, SRT, WebVTT, PO and a basic XLIFF 1.2 subset.
4
+ *
5
+ * These formats are intentionally shallow: inline markup is flattened to text,
6
+ * complex subtitle styling and XLIFF extensions are not round-tripped. The
7
+ * original source text is kept so the normal CAT/TM/glossary flow applies.
8
+ */
9
+ import { CatError } from './errors.js'
10
+ import { decodeXml, escapeXml } from './xml.js'
11
+ import { parseHtmlBlocks, renderHtmlTokens } from './html.js'
12
+
13
+ const SRT_TIME = /^(\d{1,3}):(\d{2}):(\d{2})[,.](\d{1,3})$/
14
+ const VTT_TIME = /^(?:(\d{1,3}):)?(\d{1,2}):(\d{2})\.(\d{1,3})$/
15
+ const INLINE_XML = /<\/?(?:bpt|ept|ph|g|x|bx|ex|mrk|sub|hi|span)\b[^>]*>/gi
16
+ const INLINE_TOKEN = /\{(\d+)\}/g
17
+
18
+ function formatError(code, message) {
19
+ return new CatError(code, message)
20
+ }
21
+
22
+ function readXmlAttr(source, name) {
23
+ const match = String(source ?? '').match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']*)["']`, 'i'))
24
+ return match ? decodeXml(match[1]) : ''
25
+ }
26
+
27
+ /**
28
+ * Convert XLIFF inline markup to stable {n} tokens while keeping the original
29
+ * XML for export. This prevents <ph>, <bpt>/<ept> and <g> placeholders from
30
+ * being silently dropped when a translation is written back.
31
+ */
32
+ function extractInline(raw) {
33
+ const tokens = []
34
+ const text = String(raw ?? '').replace(INLINE_XML, (xml) => {
35
+ const token = `{${tokens.length + 1}}`
36
+ tokens.push({ token, xml })
37
+ return token
38
+ })
39
+ return { text: decodeXml(text).trim(), tokens }
40
+ }
41
+
42
+ /** Render a tokenised string back to XML, escaping only the text portions. */
43
+ function renderInline(value, tokens) {
44
+ const text = String(value ?? '')
45
+ const map = new Map((Array.isArray(tokens) ? tokens : []).map((item) => [item.token, item.xml]))
46
+ let output = ''
47
+ let last = 0
48
+ for (const match of text.matchAll(INLINE_TOKEN)) {
49
+ output += escapeXml(text.slice(last, match.index))
50
+ output += map.get(match[0]) ?? escapeXml(match[0])
51
+ last = match.index + match[0].length
52
+ }
53
+ output += escapeXml(text.slice(last))
54
+ return output
55
+ }
56
+
57
+ /** Tokens present in the source but missing from the target. */
58
+ export function missingInlineTokens(tokens, target) {
59
+ if (!Array.isArray(tokens) || !tokens.length) return []
60
+ const value = String(target ?? '')
61
+ return tokens.map((item) => item.token).filter((token) => !value.includes(token))
62
+ }
63
+
64
+ /** Append placeholders the translator omitted, so export never silently loses them. */
65
+ function completeInline(value, tokens) {
66
+ let output = String(value ?? '')
67
+ for (const item of Array.isArray(tokens) ? tokens : []) {
68
+ if (!output.includes(item.token)) output += `${output && !/\s$/.test(output) ? ' ' : ''}${item.token}`
69
+ }
70
+ return output
71
+ }
72
+
73
+ export function detectCsvDelimiter(text) {
74
+ const input = String(text ?? '').replace(/^\uFEFF/, '')
75
+ const candidates = [',', ';', '\t', '|']
76
+ const counts = new Map(candidates.map((candidate) => [candidate, 0]))
77
+ let quoted = false
78
+ let lines = 0
79
+
80
+ for (let index = 0; index < input.length; index += 1) {
81
+ const char = input[index]
82
+ if (char === '"') {
83
+ if (quoted && input[index + 1] === '"') {
84
+ index += 1
85
+ continue
86
+ }
87
+ quoted = !quoted
88
+ continue
89
+ }
90
+ if (quoted) continue
91
+ if (char === '\n') {
92
+ lines += 1
93
+ if (lines >= 5) break
94
+ continue
95
+ }
96
+ if (counts.has(char)) counts.set(char, counts.get(char) + 1)
97
+ }
98
+
99
+ let best = ','
100
+ let bestCount = 0
101
+ for (const candidate of candidates) {
102
+ if (counts.get(candidate) > bestCount) {
103
+ best = candidate
104
+ bestCount = counts.get(candidate)
105
+ }
106
+ }
107
+ return best
108
+ }
109
+
110
+ export function parseCsvRows(text, delimiter = ',') {
111
+ const input = String(text ?? '').replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n')
112
+ const rows = []
113
+ let row = []
114
+ let field = ''
115
+ let quoted = false
116
+
117
+ for (let index = 0; index < input.length; index += 1) {
118
+ const char = input[index]
119
+ if (quoted) {
120
+ if (char === '"') {
121
+ if (input[index + 1] === '"') {
122
+ field += '"'
123
+ index += 1
124
+ } else {
125
+ quoted = false
126
+ }
127
+ } else {
128
+ field += char
129
+ }
130
+ continue
131
+ }
132
+
133
+ if (char === '"' && field === '') {
134
+ quoted = true
135
+ } else if (char === delimiter) {
136
+ row.push(field)
137
+ field = ''
138
+ } else if (char === '\n') {
139
+ row.push(field)
140
+ rows.push(row)
141
+ row = []
142
+ field = ''
143
+ } else {
144
+ field += char
145
+ }
146
+ }
147
+
148
+ if (quoted) throw formatError('CSV_PARSE', 'CSV 引号未闭合。')
149
+ if (field.length || row.length) {
150
+ row.push(field)
151
+ rows.push(row)
152
+ }
153
+ return rows
154
+ }
155
+
156
+ export function parseCsv(text, { sourceColumn, targetColumn } = {}) {
157
+ const delimiter = detectCsvDelimiter(text)
158
+ const rows = parseCsvRows(text, delimiter)
159
+ if (!rows.length) throw formatError('CSV_PARSE', 'CSV 中没有可用的行。')
160
+
161
+ const normalize = (value) => String(value ?? '').trim().toLowerCase()
162
+ const sourceAliases = new Set(['source', 'src', 'original', '原文', '源文', '源文本'])
163
+ const targetAliases = new Set(['target', 'tgt', 'translation', '译文', '目標', '目标', '目标文本'])
164
+ const first = rows[0].map(normalize)
165
+ const hasHeader = first.some((value) => sourceAliases.has(value) || targetAliases.has(value))
166
+ const resolveColumn = (rawValue, aliases, fallback) => {
167
+ const value = String(rawValue ?? '').trim()
168
+ if (!value) return fallback
169
+ if (/^\d+$/.test(value)) {
170
+ const index = Number(value) - 1
171
+ if (index < 0) throw formatError('CSV_PARSE', 'CSV 列号从 1 开始。')
172
+ return index
173
+ }
174
+ const index = first.findIndex((item) => item === value.toLowerCase())
175
+ if (index < 0) throw formatError('CSV_PARSE', `CSV 中找不到列“${value}”。`)
176
+ return index
177
+ }
178
+
179
+ let sourceIndex = first.findIndex((value) => sourceAliases.has(value))
180
+ let targetIndex = first.findIndex((value) => targetAliases.has(value))
181
+ let start = 0
182
+
183
+ if (sourceColumn !== undefined || targetColumn !== undefined) {
184
+ sourceIndex = resolveColumn(sourceColumn, sourceAliases, sourceIndex >= 0 ? sourceIndex : 0)
185
+ targetIndex = resolveColumn(targetColumn, targetAliases, targetIndex)
186
+ start = hasHeader ? 1 : 0
187
+ } else if (sourceIndex >= 0 && targetIndex >= 0) {
188
+ start = 1
189
+ } else {
190
+ sourceIndex = 0
191
+ targetIndex = rows[0].length > 1 ? 1 : -1
192
+ }
193
+
194
+ const maxColumns = rows.reduce((max, row) => Math.max(max, row.length), 0)
195
+ if (sourceIndex < 0 || sourceIndex >= maxColumns) {
196
+ throw formatError('CSV_PARSE', 'CSV 源文列不存在。')
197
+ }
198
+ if (targetIndex >= maxColumns) {
199
+ throw formatError('CSV_PARSE', 'CSV 译文列不存在。')
200
+ }
201
+
202
+ const segments = []
203
+ for (let index = start; index < rows.length; index += 1) {
204
+ const row = rows[index]
205
+ const source = String(row[sourceIndex] ?? '').trim()
206
+ if (!source) continue
207
+ const target = targetIndex >= 0 ? String(row[targetIndex] ?? '').trim() : ''
208
+ segments.push({
209
+ source,
210
+ target,
211
+ paragraph: segments.length,
212
+ meta: { format: 'csv' },
213
+ })
214
+ }
215
+
216
+ if (!segments.length) throw formatError('CSV_NO_UNITS', 'CSV 中没有可用的源文行。')
217
+ return { format: 'csv', segments, warnings: [] }
218
+ }
219
+
220
+ function parseSrtTime(value) {
221
+ const match = String(value).trim().match(SRT_TIME)
222
+ if (!match) return null
223
+ const [, hours, minutes, seconds, millis] = match
224
+ return Number(hours) * 3600000 + Number(minutes) * 60000 + Number(seconds) * 1000 + Number(millis.padEnd(3, '0'))
225
+ }
226
+
227
+ export function formatSrtTime(milliseconds) {
228
+ const total = Math.max(0, Math.round(Number(milliseconds) || 0))
229
+ const hours = Math.floor(total / 3600000)
230
+ const minutes = Math.floor((total % 3600000) / 60000)
231
+ const seconds = Math.floor((total % 60000) / 1000)
232
+ const millis = total % 1000
233
+ return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')},${String(millis).padStart(3, '0')}`
234
+ }
235
+
236
+ function stripSubtitleMarkup(value) {
237
+ const assOverrides = String(value).match(/\{\\[^}]+\}/g) ?? []
238
+ return {
239
+ // Semantic tags such as <i>, <b>, <font> and WebVTT <c>/<v>/<ruby> are
240
+ // meaningful translation content and stay in the string verbatim.
241
+ text: decodeXml(String(value).replace(/<br\s*\/?>/gi, '\n').replace(/\{\\[^}]+\}/g, '')),
242
+ count: assOverrides.length,
243
+ }
244
+ }
245
+
246
+ function parseSubtitleBlocks(text, kind) {
247
+ const input = String(text ?? '').replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n').trim()
248
+ if (!input) throw formatError(`${kind.toUpperCase()}_PARSE`, `${kind.toUpperCase()} 文件内容为空。`)
249
+
250
+ const blocks = input.split(/\n{2,}/)
251
+ const segments = []
252
+ const warnings = []
253
+ let markupCount = 0
254
+
255
+ for (const block of blocks) {
256
+ const lines = block.split('\n')
257
+ if (!lines.length) continue
258
+ let cursor = 0
259
+ if (lines[0].trim().toUpperCase().startsWith('WEBVTT')) {
260
+ lines.shift()
261
+ while (lines.length && !lines[0].trim()) lines.shift()
262
+ if (!lines.length) continue
263
+ }
264
+ if (lines[0].trim().startsWith('NOTE') || lines[0].trim().startsWith('STYLE') || lines[0].trim().startsWith('REGION')) continue
265
+
266
+ let identifier = ''
267
+ if (!lines[cursor].includes('-->')) {
268
+ identifier = lines[cursor].trim()
269
+ cursor += 1
270
+ }
271
+ if (!lines[cursor]?.includes('-->')) continue
272
+ const timing = lines[cursor].trim()
273
+ cursor += 1
274
+
275
+ const timingMatch = timing.match(/^(\S+)\s*-->\s*(\S+)(.*)$/)
276
+ if (!timingMatch) {
277
+ throw formatError(`${kind.toUpperCase()}_PARSE`, `字幕时间轴无效: ${timing}`)
278
+ }
279
+ const start = kind === 'srt' ? parseSrtTime(timingMatch[1]) : parseVttTime(timingMatch[1])
280
+ const end = kind === 'srt' ? parseSrtTime(timingMatch[2]) : parseVttTime(timingMatch[2])
281
+ if (start === null || end === null) {
282
+ throw formatError(`${kind.toUpperCase()}_PARSE`, `字幕时间轴无效: ${timing}`)
283
+ }
284
+ if (end <= start) {
285
+ throw formatError(
286
+ `${kind.toUpperCase()}_PARSE`,
287
+ `字幕结束时间必须晚于开始时间: ${timing}`,
288
+ )
289
+ }
290
+
291
+ const rawText = lines.slice(cursor).join('\n').trim()
292
+ if (!rawText) continue
293
+ const stripped = stripSubtitleMarkup(rawText)
294
+ markupCount += stripped.count
295
+ const text = stripped.text.trim()
296
+ if (!text) continue
297
+ segments.push({
298
+ source: text,
299
+ target: '',
300
+ paragraph: segments.length,
301
+ meta: {
302
+ format: kind,
303
+ start,
304
+ end,
305
+ settings: timingMatch[3].trim(),
306
+ identifier,
307
+ },
308
+ })
309
+ }
310
+
311
+ if (!segments.length) throw formatError(`${kind.toUpperCase()}_NO_UNITS`, `${kind.toUpperCase()} 中没有可用的字幕。`)
312
+ if (markupCount) {
313
+ warnings.push({
314
+ code: `${kind.toUpperCase()}_INLINE_MARKUP_LOST`,
315
+ count: markupCount,
316
+ message: `${kind.toUpperCase()} 含 ${markupCount} 个 ASS 样式覆盖标记({\\...}),导入时已移除;语义标签已保留。`,
317
+ })
318
+ }
319
+ return { format: kind, segments, warnings }
320
+ }
321
+
322
+ export function parseSrt(text) {
323
+ return parseSubtitleBlocks(text, 'srt')
324
+ }
325
+
326
+ function parseVttTime(value) {
327
+ const match = String(value).trim().match(VTT_TIME)
328
+ if (!match) return null
329
+ const [, hours, minutes, seconds, millis] = match
330
+ return Number(hours || 0) * 3600000 + Number(minutes) * 60000 + Number(seconds) * 1000 + Number(millis.padEnd(3, '0'))
331
+ }
332
+
333
+ export function formatVttTime(milliseconds) {
334
+ const total = Math.max(0, Math.round(Number(milliseconds) || 0))
335
+ const hours = Math.floor(total / 3600000)
336
+ const minutes = Math.floor((total % 3600000) / 60000)
337
+ const seconds = Math.floor((total % 60000) / 1000)
338
+ const millis = total % 1000
339
+ return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}.${String(millis).padStart(3, '0')}`
340
+ }
341
+
342
+ export function parseVtt(text) {
343
+ return parseSubtitleBlocks(text, 'vtt')
344
+ }
345
+
346
+ function subtitleText(segment) {
347
+ return String(segment.target || segment.source || '').trim()
348
+ }
349
+
350
+ function cueTimes(segment, fallbackStart) {
351
+ const start = Number(segment.meta?.start)
352
+ const end = Number(segment.meta?.end)
353
+ if (Number.isFinite(start) && start >= 0 && Number.isFinite(end) && end > start) {
354
+ return { start, end }
355
+ }
356
+ // Text-only documents (and any cue without usable timing metadata) start
357
+ // where the previous cue ended. This avoids the old index * 2000 fallback
358
+ // overlapping an explicitly timed cue that sits earlier in the document.
359
+ const safeStart = Number.isFinite(start) && start >= 0 ? start : fallbackStart
360
+ return { start: safeStart, end: safeStart + 2000 }
361
+ }
362
+
363
+ function buildCues(segments) {
364
+ let cursor = 0
365
+ return segments.map((segment) => {
366
+ const times = cueTimes(segment, cursor)
367
+ cursor = Math.max(cursor, times.end)
368
+ return { segment, times }
369
+ })
370
+ }
371
+
372
+ export function buildSrt(doc) {
373
+ return buildCues(doc.segments)
374
+ .map(({ segment, times }, index) => [
375
+ String(index + 1),
376
+ `${formatSrtTime(times.start)} --> ${formatSrtTime(times.end)}`,
377
+ subtitleText(segment),
378
+ '',
379
+ ].join('\n'))
380
+ .join('\n')
381
+ }
382
+
383
+ export function buildVtt(doc) {
384
+ const cues = buildCues(doc.segments).map(({ segment, times }) => {
385
+ const identifier = segment.meta?.identifier ? `${segment.meta.identifier}\n` : ''
386
+ const settings = segment.meta?.settings ? ` ${segment.meta.settings}` : ''
387
+ return `${identifier}${formatVttTime(times.start)} --> ${formatVttTime(times.end)}${settings}\n${subtitleText(segment)}\n`
388
+ })
389
+ return `WEBVTT\n\n${cues.join('\n')}`
390
+ }
391
+
392
+ function parsePoQuoted(raw) {
393
+ const match = String(raw).trim().match(/^"((?:\\.|[^"\\])*)"$/)
394
+ if (!match) return null
395
+ return match[1].replace(/\\(n|t|r|"|\\)/g, (all, char) => {
396
+ if (char === 'n') return '\n'
397
+ if (char === 't') return '\t'
398
+ if (char === 'r') return '\r'
399
+ return char
400
+ })
401
+ }
402
+
403
+ function poField(line) {
404
+ const match = line.match(/^(msgctxt|msgid_plural|msgid|msgstr(?:\[\d+\])?)\s+(.*)$/)
405
+ if (!match) return null
406
+ const value = parsePoQuoted(match[2])
407
+ if (value === null) return null
408
+ return { name: match[1], value }
409
+ }
410
+
411
+ export function parsePo(text) {
412
+ const input = String(text ?? '').replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n')
413
+ if (!input.trim()) throw formatError('PO_PARSE', 'PO 文件内容为空。')
414
+
415
+ const segments = []
416
+ const obsolete = []
417
+ let entry = null
418
+ let current = null
419
+ let pendingComments = []
420
+ let obsoleteBlock = null
421
+
422
+ const flushObsolete = () => {
423
+ if (!obsoleteBlock?.length) return
424
+ const block = obsoleteBlock.join('\n').trimEnd()
425
+ if (block) obsolete.push(block)
426
+ obsoleteBlock = null
427
+ }
428
+
429
+ const flush = () => {
430
+ if (!entry) return
431
+ const source = String(entry.msgid ?? '').trim()
432
+ if (source) {
433
+ const msgidPlural = String(entry.msgid_plural ?? '').trim()
434
+ const pluralKeys = Object.keys(entry.msgstr ?? {})
435
+ .filter((key) => /^\d+$/.test(key))
436
+ .sort((left, right) => Number(left) - Number(right))
437
+ const plurals = pluralKeys
438
+ .map((key) => String(entry.msgstr[key] ?? '').trim())
439
+ .filter(Boolean)
440
+ const target = String(entry.msgstr?.[''] ?? plurals[0] ?? '').trim()
441
+ const comments = entry.comments.filter(Boolean)
442
+ segments.push({
443
+ source,
444
+ target,
445
+ paragraph: segments.length,
446
+ meta: {
447
+ format: 'po',
448
+ context: String(entry.msgctxt ?? '').trim(),
449
+ msgidPlural,
450
+ plural: Boolean(msgidPlural),
451
+ ...(comments.length ? { comments } : {}),
452
+ ...(plurals.length ? { plurals } : {}),
453
+ },
454
+ })
455
+ }
456
+ entry = null
457
+ current = null
458
+ }
459
+
460
+ for (const rawLine of input.split('\n')) {
461
+ const line = rawLine.trim()
462
+ if (!line) {
463
+ flush()
464
+ flushObsolete()
465
+ continue
466
+ }
467
+ if (line.startsWith('#~')) {
468
+ if (!obsoleteBlock) {
469
+ flush()
470
+ obsoleteBlock = []
471
+ }
472
+ obsoleteBlock.push(rawLine.replace(/^#~\s?/, ''))
473
+ continue
474
+ }
475
+ if (obsoleteBlock) {
476
+ obsoleteBlock.push(rawLine)
477
+ continue
478
+ }
479
+ if (line.startsWith('#')) {
480
+ const comment = line.replace(/^#[.,:|\s]*/, '').trim()
481
+ if (comment) {
482
+ if (entry) entry.comments.push(comment)
483
+ else pendingComments.push(comment)
484
+ }
485
+ continue
486
+ }
487
+
488
+ const field = poField(line)
489
+ if (field) {
490
+ entry ??= { msgstr: {}, comments: pendingComments.splice(0) }
491
+ current = field.name
492
+ if (current.startsWith('msgstr')) {
493
+ entry.msgstr[current === 'msgstr' ? '' : current.match(/\[(\d+)\]/)?.[1] ?? '0'] = field.value
494
+ } else {
495
+ entry[current] = field.value
496
+ }
497
+ continue
498
+ }
499
+ if (line.startsWith('"') && current) {
500
+ const value = parsePoQuoted(line)
501
+ if (value === null) continue
502
+ if (current.startsWith('msgstr')) {
503
+ const key = current === 'msgstr' ? '' : current.match(/\[(\d+)\]/)?.[1] ?? '0'
504
+ entry.msgstr[key] = `${entry.msgstr[key] ?? ''}${value}`
505
+ } else {
506
+ entry[current] = `${entry[current] ?? ''}${value}`
507
+ }
508
+ }
509
+ }
510
+ flush()
511
+ flushObsolete()
512
+
513
+ if (!segments.length) throw formatError('PO_NO_UNITS', 'PO 中没有可用的 msgid/msgstr 条目。')
514
+ return { format: 'po', segments, obsolete, warnings: [] }
515
+ }
516
+
517
+ function poEscape(value) {
518
+ return String(value ?? '')
519
+ .replace(/\\/g, '\\\\')
520
+ .replace(/"/g, '\\"')
521
+ .replace(/\n/g, '\\n')
522
+ .replace(/\t/g, '\\t')
523
+ .replace(/\r/g, '\\r')
524
+ }
525
+
526
+ function poLine(field, value) {
527
+ return `${field} "${poEscape(value)}"`
528
+ }
529
+
530
+ export function buildPo(doc) {
531
+ const header = [
532
+ 'msgid ""',
533
+ 'msgstr ""',
534
+ '"Content-Type: text/plain; charset=UTF-8\\n"',
535
+ `"Language: ${doc.targetLang}\\n"`,
536
+ '',
537
+ ].join('\n')
538
+
539
+ const entries = doc.segments.map((segment) => {
540
+ const context = String(segment.meta?.context ?? '').trim()
541
+ const plural = String(segment.meta?.msgidPlural ?? '').trim()
542
+ const target = String(segment.target || segment.source || '').trim()
543
+ const comments = Array.isArray(segment.meta?.comments) ? segment.meta.comments : []
544
+ const lines = comments.filter(Boolean).map((comment) => `#. ${comment}`)
545
+ if (context) lines.push(poLine('msgctxt', context))
546
+ lines.push(poLine('msgid', segment.source))
547
+ if (plural) {
548
+ const forms = Array.isArray(segment.meta?.plurals) ? segment.meta.plurals : []
549
+ lines.push(poLine('msgid_plural', plural))
550
+ lines.push(poLine('msgstr[0]', target))
551
+ for (let index = 1; index < Math.max(forms.length, 2); index += 1) {
552
+ lines.push(poLine(`msgstr[${index}]`, forms[index] || target))
553
+ }
554
+ } else {
555
+ lines.push(poLine('msgstr', target))
556
+ }
557
+ return lines.join('\n')
558
+ })
559
+
560
+ const obsolete = Array.isArray(doc.formatMeta?.poObsolete)
561
+ ? doc.formatMeta.poObsolete
562
+ .filter((block) => typeof block === 'string' && block.trim())
563
+ .map((block) => block.split('\n').map((line) => `#~ ${line}`).join('\n'))
564
+ : []
565
+
566
+ const blocks = [...entries, ...obsolete].filter(Boolean)
567
+ return `${header}\n${blocks.join('\n\n')}\n`
568
+ }
569
+
570
+ function parseXliffUnit(body, attrs, format, tokens) {
571
+ const sourceMatch = body.match(/<(?:[\w.-]+:)?source\b[^>]*>([\s\S]*?)<\/(?:[\w.-]+:)?source>/i)
572
+ ?? body.match(/<(?:[\w.-]+:)?source\b[^>]*\/>/i)
573
+ if (!sourceMatch) return null
574
+ const sourceRaw = sourceMatch[1] ?? ''
575
+ const source = extractInline(sourceRaw)
576
+ if (!source.text) return null
577
+ const targetMatch = body.match(/<(?:[\w.-]+:)?target\b[^>]*>([\s\S]*?)<\/(?:[\w.-]+:)?target>/i)
578
+ ?? body.match(/<(?:[\w.-]+:)?target\b[^>]*\/>/i)
579
+ const target = targetMatch ? extractInline(targetMatch[1] ?? '').text : ''
580
+ tokens.push(...source.tokens)
581
+ return {
582
+ source: source.text,
583
+ target,
584
+ paragraph: 0,
585
+ meta: {
586
+ format,
587
+ xliffId: readXmlAttr(attrs, 'id'),
588
+ ...(source.tokens.length ? { inline: source.tokens } : {}),
589
+ },
590
+ }
591
+ }
592
+
593
+ function parseXliff2(input, rootAttrs) {
594
+ const sourceLang = readXmlAttr(rootAttrs, 'srcLang') || readXmlAttr(rootAttrs, 'source-language')
595
+ const targetLang = readXmlAttr(rootAttrs, 'trgLang') || readXmlAttr(rootAttrs, 'target-language')
596
+ const units = []
597
+ const inlineTokens = []
598
+ const unitRe = /<(?:[\w.-]+:)?unit\b([^>]*)>([\s\S]*?)<\/(?:[\w.-]+:)?unit>/gi
599
+ let match
600
+ while ((match = unitRe.exec(input))) {
601
+ const unit = parseXliffUnit(match[2], match[1], 'xliff2', inlineTokens)
602
+ if (!unit) continue
603
+ unit.paragraph = units.length
604
+ units.push(unit)
605
+ }
606
+ if (!units.length) throw formatError('XLIFF_NO_UNITS', 'XLIFF 中没有可用的 unit/segment。')
607
+ return { format: 'xliff2', sourceLang, targetLang, segments: units, warnings: [] }
608
+ }
609
+
610
+ export function parseXliff(text) {
611
+ const input = String(text ?? '').replace(/^\uFEFF/, '')
612
+ if (!input.trim()) throw formatError('XLIFF_PARSE', 'XLIFF 文件内容为空。')
613
+
614
+ const rootTag = input.match(/<((?:[\w.-]+:)?xliff)\b([^>]*)>/i)
615
+ const rootAttrs = rootTag?.[2] ?? ''
616
+ const version = readXmlAttr(rootAttrs, 'version')
617
+ const looksLikeXliff2 = /^2\./i.test(version)
618
+ || (!/<(?:[\w.-]+:)?trans-unit\b/i.test(input) && /<(?:[\w.-]+:)?unit\b/i.test(input))
619
+ if (looksLikeXliff2) return parseXliff2(input, rootAttrs)
620
+
621
+ const fileTag = input.match(/<((?:[\w.-]+:)?file)\b([^>]*)>/i)
622
+ const sourceLang = readXmlAttr(fileTag?.[2], 'source-language')
623
+ const targetLang = readXmlAttr(fileTag?.[2], 'target-language')
624
+
625
+ const units = []
626
+ const unitRe = /<(?:[\w.-]+:)?trans-unit\b([^>]*)>([\s\S]*?)<\/(?:[\w.-]+:)?trans-unit>/gi
627
+ let match
628
+ while ((match = unitRe.exec(input))) {
629
+ const unit = parseXliffUnit(match[2], match[1], 'xliff', [])
630
+ if (!unit) continue
631
+ unit.paragraph = units.length
632
+ units.push(unit)
633
+ }
634
+
635
+ if (!units.length) throw formatError('XLIFF_NO_UNITS', 'XLIFF 中没有可用的 trans-unit。')
636
+ return { format: 'xliff', sourceLang, targetLang, segments: units, warnings: [] }
637
+ }
638
+
639
+ export function buildXliff(doc) {
640
+ const units = doc.segments.map((segment, index) => {
641
+ const id = String(segment.meta?.xliffId || index + 1)
642
+ const tokens = Array.isArray(segment.meta?.inline) ? segment.meta.inline : []
643
+ const target = completeInline(segment.target || segment.source, tokens)
644
+ return [
645
+ ` <trans-unit id="${escapeXml(id)}">`,
646
+ ` <source xml:lang="${escapeXml(doc.sourceLang)}">${renderInline(segment.source, tokens)}</source>`,
647
+ ` <target xml:lang="${escapeXml(doc.targetLang)}">${renderInline(target, tokens)}</target>`,
648
+ ' </trans-unit>',
649
+ ].join('\n')
650
+ })
651
+ return [
652
+ '<?xml version="1.0" encoding="UTF-8"?>',
653
+ '<xliff version="1.2">',
654
+ ` <file source-language="${escapeXml(doc.sourceLang)}" target-language="${escapeXml(doc.targetLang)}" datatype="plaintext" original="${escapeXml(doc.name)}">`,
655
+ ' <body>',
656
+ ...units,
657
+ ' </body>',
658
+ ' </file>',
659
+ '</xliff>',
660
+ '',
661
+ ].join('\n')
662
+ }
663
+
664
+ export function buildXliff2(doc) {
665
+ const units = doc.segments.map((segment, index) => {
666
+ const id = String(segment.meta?.xliffId || index + 1)
667
+ const tokens = Array.isArray(segment.meta?.inline) ? segment.meta.inline : []
668
+ const target = completeInline(segment.target || segment.source, tokens)
669
+ return [
670
+ ` <unit id="${escapeXml(id)}">`,
671
+ ' <segment>',
672
+ ` <source>${renderInline(segment.source, tokens)}</source>`,
673
+ ` <target>${renderInline(target, tokens)}</target>`,
674
+ ' </segment>',
675
+ ' </unit>',
676
+ ].join('\n')
677
+ })
678
+ return [
679
+ '<?xml version="1.0" encoding="UTF-8"?>',
680
+ '<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0"',
681
+ ` srcLang="${escapeXml(doc.sourceLang)}" trgLang="${escapeXml(doc.targetLang)}">`,
682
+ ' <file id="f1">',
683
+ ...units,
684
+ ' </file>',
685
+ '</xliff>',
686
+ '',
687
+ ].join('\n')
688
+ }
689
+
690
+ function htmlToText(input) {
691
+ const { runs } = parseHtmlBlocks(input)
692
+ return runs.map((run) => run.text).join('\n\n').trim()
693
+ }
694
+
695
+ export function parseHtml(text) {
696
+ const input = String(text ?? '')
697
+ if (!input.trim()) throw formatError('HTML_PARSE', 'HTML 文件内容为空。')
698
+ const { runs } = parseHtmlBlocks(input)
699
+ if (!runs.length) throw formatError('HTML_NO_UNITS', 'HTML 中没有可用的正文。')
700
+ const segments = runs.map((run, index) => ({
701
+ source: run.text,
702
+ target: '',
703
+ paragraph: index,
704
+ meta: {
705
+ format: 'html',
706
+ ...(run.tokens.length ? { inline: run.tokens } : {}),
707
+ },
708
+ }))
709
+ return { format: 'html', segments, warnings: [] }
710
+ }
711
+
712
+ function renderHtmlSegment(segment) {
713
+ const tokens = Array.isArray(segment?.meta?.inline) ? segment.meta.inline : []
714
+ let value = String(segment?.target || segment?.source || '')
715
+ if (tokens.length && tokens.some((item) => !value.includes(item.token))) {
716
+ value = String(segment?.source ?? '')
717
+ }
718
+ return tokens.length ? renderHtmlTokens(value, tokens) : escapeXml(value)
719
+ }
720
+
721
+ export function buildHtml(doc) {
722
+ const groups = new Map()
723
+ for (const segment of doc.segments) {
724
+ const key = segment.paragraph ?? 0
725
+ if (!groups.has(key)) groups.set(key, [])
726
+ groups.get(key).push(segment)
727
+ }
728
+ const paragraphs = [...groups.values()]
729
+ .map((parts) => parts.map((segment) => renderHtmlSegment(segment).trim()).filter(Boolean).join(' '))
730
+ .filter(Boolean)
731
+ .map((text) => ` <p>${text}</p>`)
732
+ .join('\n')
733
+ return [
734
+ '<!doctype html>',
735
+ '<html lang="' + escapeXml(doc.targetLang || 'en') + '">',
736
+ '<head><meta charset="utf-8"><title>' + escapeXml(doc.name || 'CAIT export') + '</title></head>',
737
+ '<body>',
738
+ paragraphs,
739
+ '</body>',
740
+ '</html>',
741
+ '',
742
+ ].join('\n')
743
+ }
744
+
745
+ function escapeJsonPointer(value) {
746
+ return String(value).replace(/~/g, '~0').replace(/\//g, '~1')
747
+ }
748
+
749
+ function unescapeJsonPointer(value) {
750
+ return String(value).replace(/~1/g, '/').replace(/~0/g, '~')
751
+ }
752
+
753
+ function walkJsonStrings(value, pointer, visit) {
754
+ if (typeof value === 'string') {
755
+ visit(value, pointer)
756
+ return
757
+ }
758
+ if (Array.isArray(value)) {
759
+ value.forEach((item, index) => walkJsonStrings(item, `${pointer}/${index}`, visit))
760
+ return
761
+ }
762
+ if (value && typeof value === 'object') {
763
+ for (const [key, item] of Object.entries(value)) {
764
+ walkJsonStrings(item, `${pointer}/${escapeJsonPointer(key)}`, visit)
765
+ }
766
+ }
767
+ }
768
+
769
+ function setJsonPointer(root, pointer, value) {
770
+ const parts = String(pointer).split('/').slice(1).map(unescapeJsonPointer)
771
+ if (!parts.length) return value
772
+ let current = root
773
+ for (let index = 0; index < parts.length - 1; index += 1) {
774
+ if (current == null) throw new Error('JSON path does not exist')
775
+ current = current[parts[index]]
776
+ }
777
+ if (current == null) throw new Error('JSON path does not exist')
778
+ current[parts[parts.length - 1]] = value
779
+ return root
780
+ }
781
+
782
+ export function parseJson(text) {
783
+ const input = String(text ?? '').replace(/^\uFEFF/, '')
784
+ if (!input.trim()) throw formatError('JSON_PARSE', 'JSON 文件内容为空。')
785
+ let root
786
+ try {
787
+ root = JSON.parse(input)
788
+ } catch (error) {
789
+ throw formatError('JSON_PARSE', `JSON 解析失败: ${error.message}`)
790
+ }
791
+ const segments = []
792
+ walkJsonStrings(root, '', (source, pointer) => {
793
+ if (!source.trim()) return
794
+ segments.push({
795
+ source,
796
+ target: '',
797
+ paragraph: segments.length,
798
+ meta: { format: 'json', jsonPath: pointer },
799
+ })
800
+ })
801
+ if (!segments.length) throw formatError('JSON_NO_UNITS', 'JSON 中没有可翻译的字符串。')
802
+ return {
803
+ format: 'json',
804
+ segments,
805
+ formatMeta: { jsonTemplate: JSON.stringify(root) },
806
+ warnings: [],
807
+ }
808
+ }
809
+
810
+ export function buildJson(doc) {
811
+ let root
812
+ try {
813
+ root = doc.formatMeta?.jsonTemplate ? JSON.parse(doc.formatMeta.jsonTemplate) : {}
814
+ } catch {
815
+ root = {}
816
+ }
817
+ for (const segment of doc.segments) {
818
+ const pointer = segment.meta?.jsonPath
819
+ if (!pointer) continue
820
+ const text = String(segment.target || segment.source || '')
821
+ setJsonPointer(root, pointer, text)
822
+ }
823
+ return `${JSON.stringify(root, null, 2)}\n`
824
+ }
825
+
826
+ const RTF_DESTINATION_GROUP = /\{\\\*?\\?(?:fonttbl|colortbl|stylesheet|info|pict|header|footer|object|themedata|colorschememapping|datastore|latentstyles|rsidtbl|generator|xmlnstbl)\b[^{}]*(?:\{[^{}]*\}[^{}]*)*\}/gi
827
+
828
+ function rtfUnicode(code) {
829
+ const value = Number(code)
830
+ return String.fromCharCode(value < 0 ? value + 65536 : value)
831
+ }
832
+
833
+ export function parseRtf(text) {
834
+ let input = String(text ?? '').replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n')
835
+ if (!input.trim()) throw formatError('RTF_PARSE', 'RTF 文件内容为空。')
836
+ if (!input.trimStart().startsWith('{\\rtf')) {
837
+ throw formatError('RTF_PARSE', 'RTF 文件缺少 {\\rtf 头。')
838
+ }
839
+ let previous
840
+ do {
841
+ previous = input
842
+ input = input.replace(RTF_DESTINATION_GROUP, '')
843
+ } while (previous !== input)
844
+
845
+ let output = ''
846
+ let index = 0
847
+ let unicodeSkip = 1
848
+ while (index < input.length) {
849
+ const char = input[index]
850
+ if (char === '{' || char === '}') {
851
+ index += 1
852
+ continue
853
+ }
854
+ if (char !== '\\') {
855
+ output += char
856
+ index += 1
857
+ continue
858
+ }
859
+ const next = input[index + 1]
860
+ if (next === '\\' || next === '{' || next === '}') {
861
+ output += next
862
+ index += 2
863
+ continue
864
+ }
865
+ if (next === "'") {
866
+ const hex = input.slice(index + 2, index + 4)
867
+ if (!/^[0-9a-f]{2}$/i.test(hex)) throw formatError('RTF_PARSE', 'RTF 十六进制转义无效。')
868
+ output += Buffer.from([Number.parseInt(hex, 16)]).toString('latin1')
869
+ index += 4
870
+ continue
871
+ }
872
+ if (next === '*') {
873
+ index += 2
874
+ continue
875
+ }
876
+ if (next === '~') {
877
+ output += ' '
878
+ index += 2
879
+ continue
880
+ }
881
+ if (next === '_') {
882
+ output += '-'
883
+ index += 2
884
+ continue
885
+ }
886
+ let cursor = index + 1
887
+ let sign = 1
888
+ if (input[cursor] === '-') {
889
+ sign = -1
890
+ cursor += 1
891
+ }
892
+ const wordStart = cursor
893
+ while (/[a-z]/i.test(input[cursor] ?? '')) cursor += 1
894
+ const word = input.slice(wordStart, cursor).toLowerCase()
895
+ const numberStart = cursor
896
+ while (/\d/.test(input[cursor] ?? '')) cursor += 1
897
+ const number = input.slice(numberStart, cursor)
898
+ if (input[cursor] === ' ') cursor += 1
899
+ index = cursor
900
+ if (!word) continue
901
+ const value = number ? sign * Number(number) : null
902
+ if (word === 'par') output += '\n\n'
903
+ else if (word === 'line') output += '\n'
904
+ else if (word === 'tab') output += '\t'
905
+ else if (word === 'cell') output += '\t'
906
+ else if (word === 'row') output += '\n'
907
+ else if (word === 'page' || word === 'sect') output += '\n\n'
908
+ else if (word === 'emdash') output += '—'
909
+ else if (word === 'endash') output += '–'
910
+ else if (word === 'bullet') output += '•'
911
+ else if (word === 'lquote' || word === 'rquote') output += "'"
912
+ else if (word === 'ldblquote' || word === 'rdblquote') output += '"'
913
+ else if (word === 'uc' && value !== null) unicodeSkip = Math.max(0, value)
914
+ else if (word === 'u' && value !== null) {
915
+ output += rtfUnicode(value)
916
+ let skip = unicodeSkip
917
+ while (skip > 0 && index < input.length) {
918
+ index += 1
919
+ skip -= 1
920
+ }
921
+ } else if (word === 'bin' && value !== null && value > 0) {
922
+ index += value
923
+ }
924
+ }
925
+
926
+ const segments = output
927
+ .split(/\n{2,}/)
928
+ .map((part) => part.replace(/^\n+|\n+$/g, '').trim())
929
+ .filter(Boolean)
930
+ .map((source, paragraph) => ({
931
+ source,
932
+ target: '',
933
+ paragraph,
934
+ meta: { format: 'rtf' },
935
+ }))
936
+ if (!segments.length) throw formatError('RTF_NO_UNITS', 'RTF 中没有可用的正文。')
937
+ return { format: 'rtf', segments, warnings: [] }
938
+ }
939
+
940
+ function escapeRtf(value) {
941
+ let output = ''
942
+ for (const char of String(value)) {
943
+ const code = char.codePointAt(0)
944
+ if (char === '\\' || char === '{' || char === '}') output += `\\${char}`
945
+ else if (char === '\n') output += '\\line '
946
+ else if (char === '\t') output += '\\tab '
947
+ else if (code >= 0x20 && code < 0x7f) output += char
948
+ else if (code <= 0xffff) output += `\\u${code}?`
949
+ else {
950
+ const high = Math.floor((code - 0x10000) / 0x400) + 0xd800
951
+ const low = ((code - 0x10000) % 0x400) + 0xdc00
952
+ output += `\\u${high}?\\u${low}?`
953
+ }
954
+ }
955
+ return output
956
+ }
957
+
958
+ export function buildRtf(doc) {
959
+ const groups = new Map()
960
+ for (const segment of doc.segments) {
961
+ const key = segment.paragraph ?? 0
962
+ if (!groups.has(key)) groups.set(key, [])
963
+ groups.get(key).push(String(segment.target || segment.source || '').trim())
964
+ }
965
+ const body = [...groups.values()]
966
+ .map((parts) => parts.filter(Boolean).join(' '))
967
+ .filter(Boolean)
968
+ .map((text) => `\\pard\\f0\\fs22 ${escapeRtf(text)}\\par`)
969
+ .join('\n')
970
+ return `{\\rtf1\\ansi\\deff0{\\fonttbl{\\f0 Calibri;}}\\viewkind4\\uc1\n${body}\n}\n`
971
+ }
972
+