M2: TranslationAdapter/AdapterRegistry with documented Hy-MT3 prompts and publisher sampling; all 102 languages with BCP-47 variants, RTL and dense-script flags; normalisation, NLLanguage detection, content classification and exact-join script-aware chunking; protected-token scanning and output validation; prompt policy with one documented fallback; shared TranslationPipeline with Core error mapping. The CLI now reports sourceLanguage and warning codes. M3: pure DoubleCopyDetector, 120 ms PasteboardWatcher with 750 ms own-write suppression, SystemPasteboard snapshot/restore and markers, CapturePolicy for the 4000/2000 limits, ServicesProvider and the menu-bar action. T3.5 (10-app manual matrix) remains intentionally open. Docs: ARCHITECTURE, TRANSLATION_OUTPUT, HYMT3_MODEL (§7 spike), SELECTION_AND_CLIPBOARD, PROGRESS; ADR-016 superseded by ADR-017/018. Verified: make verify green (format, strict lint, scripts, privacy, Debug+Release signatures, package tests); live 7B CLI en→de/de→en/Markdown/JSON/placeholders; empty input exits 2 and unreachable exits 3.
92 lines
3.6 KiB
Swift
92 lines
3.6 KiB
Swift
import Foundation
|
|
|
|
/// Finds URLs, e-mail addresses, placeholders, code spans, HTML tags, JSON keys and paths that
|
|
/// must survive translation (`docs/TRANSLATION_OUTPUT.md` §4).
|
|
public struct ProtectedTokenScanner: Sendable {
|
|
private struct Rule {
|
|
let kind: ProtectedTokenKind
|
|
let regex: NSRegularExpression
|
|
let group: Int
|
|
}
|
|
|
|
private static let rules: [Rule] = {
|
|
func rule(
|
|
_ kind: ProtectedTokenKind,
|
|
_ pattern: String,
|
|
group: Int = 0,
|
|
options: NSRegularExpression.Options = []
|
|
) -> Rule? {
|
|
guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else {
|
|
return nil
|
|
}
|
|
return Rule(kind: kind, regex: regex, group: group)
|
|
}
|
|
let rules: [Rule?] = [
|
|
rule(.fencedCode, "```[\\s\\S]*?```"),
|
|
rule(.codeSpan, "`[^`\\n]+`"),
|
|
rule(.htmlTag, "</?[A-Za-z][^>\\n]*>"),
|
|
rule(.url, "(?:https?://|www\\.)[^\\s<>\"']+"),
|
|
rule(.email, "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"),
|
|
rule(.mustache, "\\{\\{\\s*[^{}\\n]+\\s*\\}\\}"),
|
|
rule(.templateLiteral, "\\$\\{[^{}\\n]+\\}"),
|
|
rule(.printf, "%(?:\\d+\\$)?[-+0#]*\\d*(?:\\.\\d+)?[sd@]"),
|
|
rule(.jsonKey, "(\"(?:[^\"\\\\]|\\\\.)*\")\\s*:", group: 1),
|
|
rule(.filePath, "(?:/(?:Users|home|var|usr|opt|tmp)/[^\\s,;:\"'<>]+|[A-Za-z]:\\\\[^\\s,;:\"'<>]+)"),
|
|
]
|
|
return rules.compactMap(\.self)
|
|
}()
|
|
|
|
/// Creates a scanner.
|
|
public init() {}
|
|
|
|
/// Scans `text` and returns the protected tokens in source order, without duplicates.
|
|
public func scan(_ text: String) -> [ProtectedToken] {
|
|
let nsText = text as NSString
|
|
let fullRange = NSRange(location: 0, length: nsText.length)
|
|
var occupied: [NSRange] = []
|
|
var tokens: [(range: NSRange, token: ProtectedToken)] = []
|
|
|
|
for rule in Self.rules {
|
|
for match in rule.regex.matches(in: text, options: [], range: fullRange) {
|
|
let range = match.range(at: rule.group)
|
|
guard range.location != NSNotFound else { continue }
|
|
if occupied.contains(where: { NSIntersectionRange($0, range).length > 0 }) {
|
|
continue
|
|
}
|
|
var value = nsText.substring(with: range)
|
|
if rule.kind == .url {
|
|
value = trimURLTail(value)
|
|
if value.count < 4 {
|
|
continue
|
|
}
|
|
}
|
|
let token = ProtectedToken(kind: rule.kind, value: value)
|
|
if tokens.contains(where: { $0.token == token }) {
|
|
continue
|
|
}
|
|
tokens.append((range, token))
|
|
occupied.append(range)
|
|
}
|
|
}
|
|
|
|
return tokens.sorted { $0.range.location < $1.range.location }.map(\.token)
|
|
}
|
|
|
|
/// Removes sentence punctuation that a URL pattern may have swallowed. A balanced closing
|
|
/// parenthesis is kept, so Wikipedia-style URLs remain intact.
|
|
private func trimURLTail(_ value: String) -> String {
|
|
var result = value
|
|
while let last = result.last, ".,;:!?".contains(last) {
|
|
result.removeLast()
|
|
}
|
|
while let last = result.last, ")]}".contains(last) {
|
|
let open: Character = last == ")" ? "(" : (last == "]" ? "[" : "{")
|
|
let opens = result.filter { $0 == open }.count
|
|
let closes = result.filter { $0 == last }.count
|
|
guard closes > opens else { break }
|
|
result.removeLast()
|
|
}
|
|
return result
|
|
}
|
|
}
|