-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
457 lines (425 loc) · 20.2 KB
/
Copy pathbackground.js
File metadata and controls
457 lines (425 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
if (typeof importScripts === 'function') {
importScripts('lib/browser-polyfill.js');
}
// Default shared fallback URL (public proxy) used for short-text when MyMemory has low confidence
const DEFAULT_SHARED_FALLBACK_URL = "";
// Optional shared token to access the public proxy (gate against anonymous abuse)
// If you rotate this token server-side, update here and rebuild the extension.
const SHARED_FALLBACK_TOKEN = "";
let remoteProxyConfig = { proxyForAll: false, proxyFirstOneWord: true, useRoundTrip: true, shortMaxWords: 4, shortMaxChars: 40 };
async function refreshRemoteProxyConfig() {
try {
const r = await fetch(DEFAULT_SHARED_FALLBACK_URL + '/config');
if (r && r.ok) {
const j = await r.json();
remoteProxyConfig = {
proxyForAll: Boolean(j && (j.proxyForAll === true || String(j.proxyForAll) === '1')),
proxyFirstOneWord: Boolean(j && (j.proxyFirstOneWord === true || String(j.proxyFirstOneWord) === '1')),
useRoundTrip: Boolean(j && (j.useRoundTrip === true || String(j.useRoundTrip) === '1')),
shortMaxWords: Math.max(1, Number((j && j.shortMaxWords) || 4)),
shortMaxChars: Math.max(8, Number((j && j.shortMaxChars) || 40))
};
}
} catch (_) {}
}
// fetch once on startup
refreshRemoteProxyConfig();
async function translateWithGoogle(text, apiKey, sourceLang, targetLang) {
if (!apiKey) throw new Error('Google API key não configurada');
const body = {
q: text,
target: targetLang,
format: 'text'
};
if (sourceLang !== 'auto') {
body.source = sourceLang;
}
const response = await fetch(`https://translation.googleapis.com/language/translate/v2?key=${apiKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!response.ok) {
let errMsg = 'Google Translate API error';
try {
const error = await response.json();
errMsg = `Google Translate API error: ${error.error && error.error.message || error.message || String(response.status)}`;
} catch (_) {}
throw new Error(errMsg);
}
const data = await response.json();
return data.data.translations[0].translatedText;
}
async function translateWithDeepL(text, apiKey, sourceLang, targetLang) {
const key = String(apiKey || '').trim();
const isFree = key.toLowerCase().endsWith(":fx");
const apiUrl = isFree ? 'https://api-free.deepl.com/v2/translate' : 'https://api.deepl.com/v2/translate';
const body = {
text: text,
target_lang: targetLang.toUpperCase()
};
if (sourceLang !== 'auto') {
body.source_lang = sourceLang.toUpperCase();
}
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Authorization': `DeepL-Auth-Key ${key}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams(body)
});
if (!response.ok) {
let msg = 'DeepL API error';
try { msg = `DeepL API error: ${await response.text()}`; } catch (_) {}
throw new Error(msg);
}
const data = await response.json();
return data.translations[0].text;
}
async function translateWithMyMemory(text, sourceLang, targetLang) {
if (sourceLang === 'auto') {
throw new Error("The MyMemory API (Free) does not support auto language detection. Please select a specific source language in the popup.");
}
const langpair = `${sourceLang}|${targetLang}`;
const response = await fetch(`https://api.mymemory.translated.net/get?q=${encodeURIComponent(text)}&langpair=${langpair}`);
if (!response.ok) {
throw new Error('MyMemory API error');
}
const data = await response.json();
const baseTranslated = (data && data.responseData && data.responseData.translatedText) || '';
if (!baseTranslated) return '';
// Heuristics for short single-word translations (pt->en) to avoid archaic terms like "chariot"
function normalize(str) { return String(str || '').trim().toLowerCase(); }
// Loose normalization: ignore basic punctuation for phrase matching and round-trip checks
function normalizeLoose(str) {
return normalize(str).replace(/[!?.,;:\-()\[\]{}"'`~]+/g, '');
}
function isShortSingleWord(s) {
const t = normalize(s);
return t.length > 0 && t.length <= 8 && !t.includes(' ');
}
// Curated single-word fixes (pt->en) for common greetings and frequent mistakes
const CURATED_PT_EN = new Map([
['oi','hi'],
['olá','hello'],
['ola','hello'],
['tchau','bye'],
['adeus','goodbye'],
['obrigado','thanks'],
['obrigada','thanks'],
['teste','test'],
['por favor','please'],
['bom dia','good morning'],
['boa tarde','good afternoon'],
['boa noite','good evening'],
['tudo bem','how are you?'],
['oi tudo bem','hi, how are you?'],
['olá tudo bem','hi, how are you?'],
['ola tudo bem','hi, how are you?']
]);
const RARE_OR_ARCHAIC = new Set(['chariot','charabanc','wain','carriage','cart','buggy']);
const COMMON_ENGLISH = new Set(['car','cars','bus','train','plane','dog','cat','house','street','road','book','table','phone','computer']);
function scoreCandidate(candidate, sourceNormalized, opts) {
const seg = normalize(candidate.segment);
const trRaw = String(candidate.translation || '');
const trans = normalize(trRaw);
const matchVal = typeof candidate.match === 'number' ? candidate.match : Number(candidate.match || 0);
const match = Math.max(0, Math.min(1, isNaN(matchVal) ? 0 : matchVal));
const qVal = parseFloat(candidate.quality);
const quality = Math.max(0, Math.min(1, isNaN(qVal) ? 0 : (qVal / 100)));
let score = 0;
if (seg === sourceNormalized) score += 2.0;
score += match; // leverage TM match
score += 0.5 * quality; // incorporate quality signal
if (COMMON_ENGLISH.has(trans)) score += 0.6;
if (RARE_OR_ARCHAIC.has(trans)) score -= 1.0;
if (trans.length <= 4 && COMMON_ENGLISH.has(trans)) score += 0.2;
if (opts && opts.avoidProperNoun) {
// Penalize Proper Noun candidates when user input is lower-case single word
if (/^[A-Z]/.test(trRaw) && !trRaw.includes(' ')) score -= 0.5;
}
return { trans, score };
}
function maybePluralize(base, sourceNormalized) {
if (sourceNormalized.endsWith('s') && !base.endsWith('s')) return base + 's';
if (!sourceNormalized.endsWith('s') && base.endsWith('s')) return base.slice(0, -1);
return base;
}
// Early curated phrases (pt->en), regardless of length
try {
if (normalize(targetLang) === 'en' && normalize(sourceLang) === 'pt') {
const curPhrase = CURATED_PT_EN.get(normalizeLoose(text));
if (curPhrase) return curPhrase;
}
} catch (_) {}
let chosen = baseTranslated;
try {
const srcNorm = normalize(text);
const tgtIsEn = normalize(targetLang) === 'en';
const srcIsPt = normalize(sourceLang) === 'pt';
const tokenCount = String(text || '').trim().split(/\s+/).length;
if (tgtIsEn && isShortSingleWord(text)) {
// Try back-translation validation across top candidates first
async function backTranslateOK(candidate, from, to, original) {
try {
const url = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(candidate)}&langpair=${from}|${to}`;
const resp = await fetch(url);
if (!resp.ok) return false;
const jd = await resp.json();
const bt = normalize(jd && jd.responseData && jd.responseData.translatedText);
// Accept if exact round-trip
if (bt === normalize(original)) return true;
// Small synonym set for greetings
const SYN_PT = new Set(['oi','olá','ola']);
if (SYN_PT.has(normalize(original)) && SYN_PT.has(bt)) return true;
return false;
} catch (_) { return false; }
}
let best = { trans: normalize(baseTranslated), score: 0.5 };
const matches = Array.isArray(data.matches) ? data.matches : [];
const avoidProper = (String(text).trim() === String(text).trim().toLowerCase());
const scored = [];
for (const m of matches) {
const s = scoreCandidate(m, srcNorm, { avoidProperNoun: avoidProper });
scored.push(s);
if (s.score > best.score) best = s;
}
// Sort and try round-trip on top candidates (limit to reduce API calls)
scored.sort((a,b) => b.score - a.score);
const top = scored.slice(0, 2);
for (const cand of top) {
const ok = await backTranslateOK(cand.trans, 'en', 'pt', text);
if (ok) { chosen = cand.trans; break; }
}
if (chosen === baseTranslated) {
// Curated shortcut only if round-trip did not resolve
const curated = CURATED_PT_EN.get(srcNorm);
if (curated) return curated;
const pick = maybePluralize(best.trans, srcNorm);
chosen = pick || baseTranslated;
}
} else if (tgtIsEn && srcIsPt && tokenCount <= 4) {
// Short phrase disambiguation: use confidence gating + one probe + one round-trip
const matches = Array.isArray(data.matches) ? data.matches : [];
const avoidProper = (String(text).trim() === String(text).trim().toLowerCase());
const scored = [];
for (const m of matches) {
const s = scoreCandidate(m, srcNorm, { avoidProperNoun: avoidProper });
scored.push(s);
}
scored.sort((a,b) => b.score - a.score);
const top1 = scored[0];
const top2 = scored[1] || { score: 0 };
const delta = (top1 ? top1.score : 0) - (top2 ? top2.score : 0);
if (top1 && delta < 0.35) {
try {
const probeText = `Eu disse ${text}.`;
const probeResp = await fetch(`https://api.mymemory.translated.net/get?q=${encodeURIComponent(probeText)}&langpair=${sourceLang}|${targetLang}`);
if (probeResp.ok) {
const probeJson = await probeResp.json();
const probeBase = normalize(probeJson && probeJson.responseData && probeJson.responseData.translatedText);
if (probeBase) {
const ok = await (async () => {
try {
const url = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(probeBase)}&langpair=en|pt`;
const r = await fetch(url);
if (!r.ok) return false;
const j = await r.json();
const bt = j && j.responseData && j.responseData.translatedText;
return normalizeLoose(bt) === normalizeLoose(text);
} catch (_) { return false; }
})();
if (ok) chosen = probeBase;
}
}
} catch (_) {}
}
}
} catch (e) {
chosen = baseTranslated;
}
return chosen;
}
browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'translate') {
const { text, settings } = request;
const configuredSource = settings.sourceLang || 'pt';
const targetLang = settings.targetLang || 'en';
// Hard guard: MyMemory não suporta auto. Se vier 'auto' por qualquer motivo, forçamos 'pt' por padrão.
// Isso cobre estados antigos de configuração, abas sem refresh ou updates que não chegaram ao content.
const sourceLang = (settings.api === 'mymemory' && String(configuredSource).toLowerCase() === 'auto') ? 'pt' : configuredSource;
const shortTextAccuracy = settings && typeof settings.shortTextAccuracy === 'boolean' ? settings.shortTextAccuracy : true;
const usageCaps = (settings && settings.usageCaps) || {};
(async () => {
try {
// Deterministic E2E stub (used only when tests set this flag in settings)
if (settings && typeof settings.e2eStubTranslation === 'string' && settings.e2eStubTranslation.length > 0) {
sendResponse({ success: true, translated: settings.e2eStubTranslation });
return;
}
let translated;
// Enforce usage caps per provider (monthly counters are simplistic: stored in local storage per month key)
async function canUseProvider(provider) {
try {
const cap = Number((usageCaps && usageCaps[provider]) || 0) || 0;
if (cap <= 0) return true; // no limit configured → allow
const monthKey = new Date().toISOString().slice(0,7); // YYYY-MM
const capsRaw = await browser.storage.local.get(['usageCounters']);
const map = capsRaw.usageCounters || {};
const key = `${monthKey}:${provider}`;
const used = Number(map[key] || 0);
return used < cap;
} catch (_) { return true; }
}
async function recordUsage(provider, textLen) {
try {
const cap = Number((usageCaps && usageCaps[provider]) || 0) || 0;
if (cap <= 0) return; // no limit configured → don't persist
const monthKey = new Date().toISOString().slice(0,7);
const capsRaw = await browser.storage.local.get(['usageCounters']);
const map = capsRaw.usageCounters || {};
const key = `${monthKey}:${provider}`;
map[key] = Number(map[key] || 0) + Number(textLen || 0);
await browser.storage.local.set({ usageCounters: map });
} catch (_) {}
}
async function handleCapExceeded(provider) {
const action = (usageCaps && usageCaps.action) === 'block' ? 'block' : 'fallback';
if (action === 'block') throw new Error(`${provider} cap reached`);
// fallback to MyMemory
return await translateWithMyMemory(text, sourceLang, targetLang);
}
// If shared fallback is configured and this is short text, try proxy before MyMemory
async function maybeSharedFallback(text, settings) {
try {
const sf = settings && settings.sharedFallback;
const words = String(text||'').trim().split(/\s+/).length;
const isShort = words <= (remoteProxyConfig.shortMaxWords || 4) || String(text||'').length <= (remoteProxyConfig.shortMaxChars || 40);
const url = (sf && sf.enabled && sf.url) ? sf.url : DEFAULT_SHARED_FALLBACK_URL;
if (!url || !isShort) return null;
const headers = { 'Content-Type': 'application/json' };
if (SHARED_FALLBACK_TOKEN && typeof SHARED_FALLBACK_TOKEN === 'string' && SHARED_FALLBACK_TOKEN.length > 0) {
headers['X-Shared-Token'] = SHARED_FALLBACK_TOKEN;
}
const resp = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify({ q: text, source: sourceLang, target: targetLang })
});
if (!resp.ok) return null;
const j = await resp.json();
const t = j && (j.translated || j.text || j.translation);
return typeof t === 'string' ? t : null;
} catch (_) { return null; }
}
switch (settings.api) {
case 'google':
if (!(await canUseProvider('google'))) {
translated = await handleCapExceeded('google');
} else {
translated = await translateWithGoogle(text, settings.apiKeys.google, sourceLang, targetLang);
await recordUsage('google', String(text||'').length);
}
break;
case 'deepl':
if (!settings.apiKeys.deepl) {
translated = await translateWithMyMemory(text, sourceLang, targetLang);
} else {
if (!(await canUseProvider('deepl'))) {
translated = await handleCapExceeded('deepl');
} else {
translated = await translateWithDeepL(text, settings.apiKeys.deepl, sourceLang, targetLang);
await recordUsage('deepl', String(text||'').length);
}
}
break;
default:
translated = await (async () => {
// Se o proxy estiver configurado para tudo, use direto
if (remoteProxyConfig && remoteProxyConfig.proxyForAll === true) {
const viaProxy = await maybeSharedFallback(text, settings);
if (typeof viaProxy === 'string' && viaProxy.trim().length > 0) return viaProxy;
}
// Proxy-first para 1 palavra (ajustável via Worker)
const wordCount = String(text||'').trim().split(/\s+/).length;
if (remoteProxyConfig && remoteProxyConfig.proxyFirstOneWord && wordCount === 1) {
const viaProxyFirst = await maybeSharedFallback(text, settings);
if (typeof viaProxyFirst === 'string' && viaProxyFirst.trim().length > 0) return viaProxyFirst;
}
// 1) Tenta MyMemory primeiro
const mm = await translateWithMyMemory(text, sourceLang, targetLang);
// Se MyMemory não mudar nada (provável falha), tentar proxy imediatamente
try {
const strip = (s) => String(s || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/\s+/g,' ').trim();
if (strip(mm) === strip(text)) {
const viaProxyNoChange = await maybeSharedFallback(text, settings);
if (typeof viaProxyNoChange === 'string' && viaProxyNoChange.trim().length > 0) return viaProxyNoChange;
}
} catch (_) {}
const orig = String(text || '').trim();
const isShort = orig.split(/\s+/).filter(Boolean).length <= 2 || orig.length <= 24;
// 2) Se texto curto, valida confiança via round-trip leve; só então usa fallback compartilhado
if (isShort && (remoteProxyConfig.useRoundTrip !== false)) {
try {
const resp = await fetch(`https://api.mymemory.translated.net/get?q=${encodeURIComponent(mm)}&langpair=${targetLang}|${sourceLang}`);
if (resp && resp.ok) {
const j = await resp.json();
const bt = String((j && j.responseData && j.responseData.translatedText) || '').trim().toLowerCase().replace(/[!?.,;:\-()\[\]{}"'`~]+/g, '');
const on = orig.toLowerCase().replace(/[!?.,;:\-()\[\]{}"'`~]+/g, '');
if (bt !== on) {
const viaProxy = await maybeSharedFallback(text, settings);
if (typeof viaProxy === 'string' && viaProxy.trim().length > 0) return viaProxy;
}
}
} catch (_) {}
}
return mm;
})();
}
sendResponse({ success: true, translated });
} catch (error) {
let code = 'ERR_GENERIC';
const msg = String(error && error.message || error || '');
if (msg.includes('MyMemory')) code = 'ERR_MYMEMORY';
else if (msg.toLowerCase().includes('deepl')) code = 'ERR_DEEPL';
else if (msg.toLowerCase().includes('google')) code = 'ERR_GOOGLE';
sendResponse({ success: false, error: msg, code });
}
// removed high-accuracy external path to minimize API calls; base function handles heuristics
})();
return true;
}
});
// Test-only hook to simulate context menu click in E2E (guarded by tests triggering it)
// Commands are now handled inside content.js via keydown listeners to avoid
// requiring the "tabs" permission in the background service worker.
// Context menu to translate selection in editable fields
try {
if (browser && browser.contextMenus && browser.contextMenus.create) {
try { browser.contextMenus.removeAll(); } catch (e) {}
browser.contextMenus.create({
id: 'translate-selection',
title: (browser.i18n && browser.i18n.getMessage('cmTranslateSelection')) || 'Translate selection',
contexts: ['editable', 'selection']
});
browser.contextMenus.onClicked.addListener(async (info, tab) => {
if (info && info.menuItemId === 'translate-selection') {
try {
const active = tab && tab.id;
if (!active) return;
if (info && info.editable === true) {
await browser.tabs.sendMessage(active, { action: 'translate-now' });
return;
}
const selected = (info && typeof info.selectionText === 'string') ? info.selectionText.trim() : '';
if (selected.length > 0) {
await browser.tabs.sendMessage(active, { action: 'translate-selection-text', text: selected });
return;
}
await browser.tabs.sendMessage(active, { action: 'translate-now' });
} catch (e) {}
}
});
}
} catch (e) {}