-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
70 lines (66 loc) · 2.32 KB
/
background.js
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
import { createTranslator } from "./background/translator.js";
import { createCache } from "./background/cache.js";
import { loadSettings, saveSettings } from "./background/settings.js";
import { deepAssign } from "./background/utils.js";
const translator = createTranslator();
const cache = createCache(256);
async function cachedTranslate(text, settings) {
text = text.trim();
const key = JSON.stringify([
settings.backend,
settings[settings.backend],
settings.language,
text,
]);
{
const cached = cache.get(key);
if (cached) {
console.log("Cached:", { key, cached });
return cached;
}
}
const result = await translator.translate(text, settings);
cache.set(key, result);
console.log("Translated:", { key, result });
return result;
}
chrome.runtime.onInstalled.addListener(() => {
console.log("Service worker installed");
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log("Received:", { request, sender });
switch (request.action) {
case "translate":
loadSettings().then((settings) => {
cachedTranslate(request.text, settings.translator)
.then((result) => {
sendResponse({ result });
})
.catch((error) => {
console.error("Failed to translate:", error);
sendResponse({
error: typeof error === "string"
? error
: JSON.stringify(error),
});
});
});
return true;
case "backends":
sendResponse({ backends: translator.getBackends() });
return false;
case "settings":
const shouldUpdate = typeof request.settings === "object" &&
Object.keys(request.settings).length > 0;
loadSettings().then((settings) => {
if (shouldUpdate) {
deepAssign(settings, request.settings);
saveSettings(settings);
}
sendResponse({ settings });
});
return true;
default:
return false;
}
});