@weglot/translate-react 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +6 -0
- package/README.md +199 -2
- package/build/_virtual/rolldown_runtime.cjs +29 -0
- package/build/_virtual/rolldown_runtime.mjs +7 -0
- package/build/index.cjs +0 -0
- package/build/index.d.cts +2 -0
- package/build/index.d.mts +2 -0
- package/build/index.mjs +1 -0
- package/build/locale.d.cts +6 -0
- package/build/locale.d.cts.map +1 -0
- package/build/locale.d.mts +6 -0
- package/build/locale.d.mts.map +1 -0
- package/build/metadata/manager.cjs +119 -0
- package/build/metadata/manager.mjs +114 -0
- package/build/metadata/manager.mjs.map +1 -0
- package/build/plugin/build-translator.cjs +210 -0
- package/build/plugin/build-translator.mjs +208 -0
- package/build/plugin/build-translator.mjs.map +1 -0
- package/build/plugin/cleanup.cjs +20 -0
- package/build/plugin/cleanup.mjs +20 -0
- package/build/plugin/cleanup.mjs.map +1 -0
- package/build/plugin/index.cjs +0 -0
- package/build/plugin/index.d.cts +2 -0
- package/build/plugin/index.d.mts +2 -0
- package/build/plugin/index.mjs +1 -0
- package/build/plugin/next-compiler-loader.cjs +40 -0
- package/build/plugin/next-compiler-loader.d.cts +12 -0
- package/build/plugin/next-compiler-loader.d.cts.map +1 -0
- package/build/plugin/next-compiler-loader.d.mts +13 -0
- package/build/plugin/next-compiler-loader.d.mts.map +1 -0
- package/build/plugin/next-compiler-loader.mjs +41 -0
- package/build/plugin/next-compiler-loader.mjs.map +1 -0
- package/build/plugin/next-config-loader.cjs +13 -0
- package/build/plugin/next-config-loader.d.cts +8 -0
- package/build/plugin/next-config-loader.d.cts.map +1 -0
- package/build/plugin/next-config-loader.d.mts +9 -0
- package/build/plugin/next-config-loader.d.mts.map +1 -0
- package/build/plugin/next-config-loader.mjs +14 -0
- package/build/plugin/next-config-loader.mjs.map +1 -0
- package/build/plugin/next-locale-client-loader.cjs +9 -0
- package/build/plugin/next-locale-client-loader.d.cts +8 -0
- package/build/plugin/next-locale-client-loader.d.cts.map +1 -0
- package/build/plugin/next-locale-client-loader.d.mts +9 -0
- package/build/plugin/next-locale-client-loader.d.mts.map +1 -0
- package/build/plugin/next-locale-client-loader.mjs +10 -0
- package/build/plugin/next-locale-client-loader.mjs.map +1 -0
- package/build/plugin/next-locale-server-loader.cjs +9 -0
- package/build/plugin/next-locale-server-loader.d.cts +8 -0
- package/build/plugin/next-locale-server-loader.d.cts.map +1 -0
- package/build/plugin/next-locale-server-loader.d.mts +9 -0
- package/build/plugin/next-locale-server-loader.d.mts.map +1 -0
- package/build/plugin/next-locale-server-loader.mjs +10 -0
- package/build/plugin/next-locale-server-loader.mjs.map +1 -0
- package/build/plugin/next.cjs +227 -0
- package/build/plugin/next.d.cts +9 -0
- package/build/plugin/next.d.cts.map +1 -0
- package/build/plugin/next.d.mts +9 -0
- package/build/plugin/next.d.mts.map +1 -0
- package/build/plugin/next.mjs +229 -0
- package/build/plugin/next.mjs.map +1 -0
- package/build/plugin/transform/babel-compat.cjs +13 -0
- package/build/plugin/transform/babel-compat.mjs +10 -0
- package/build/plugin/transform/babel-compat.mjs.map +1 -0
- package/build/plugin/transform/expression-strings.cjs +145 -0
- package/build/plugin/transform/expression-strings.mjs +140 -0
- package/build/plugin/transform/expression-strings.mjs.map +1 -0
- package/build/plugin/transform/index.cjs +45 -0
- package/build/plugin/transform/index.mjs +43 -0
- package/build/plugin/transform/index.mjs.map +1 -0
- package/build/plugin/transform/metadata.cjs +142 -0
- package/build/plugin/transform/metadata.mjs +141 -0
- package/build/plugin/transform/metadata.mjs.map +1 -0
- package/build/plugin/transform/process-file.cjs +525 -0
- package/build/plugin/transform/process-file.mjs +524 -0
- package/build/plugin/transform/process-file.mjs.map +1 -0
- package/build/plugin/transform/use-i18n.cjs +8 -0
- package/build/plugin/transform/use-i18n.mjs +7 -0
- package/build/plugin/transform/use-i18n.mjs.map +1 -0
- package/build/plugin/transform/utils.cjs +237 -0
- package/build/plugin/transform/utils.mjs +219 -0
- package/build/plugin/transform/utils.mjs.map +1 -0
- package/build/plugin/unplugin.cjs +188 -0
- package/build/plugin/unplugin.d.cts +8 -0
- package/build/plugin/unplugin.d.cts.map +1 -0
- package/build/plugin/unplugin.d.mts +8 -0
- package/build/plugin/unplugin.d.mts.map +1 -0
- package/build/plugin/unplugin.mjs +188 -0
- package/build/plugin/unplugin.mjs.map +1 -0
- package/build/plugin/vite.cjs +27 -0
- package/build/plugin/vite.d.cts +9 -0
- package/build/plugin/vite.d.cts.map +1 -0
- package/build/plugin/vite.d.mts +9 -0
- package/build/plugin/vite.d.mts.map +1 -0
- package/build/plugin/vite.mjs +28 -0
- package/build/plugin/vite.mjs.map +1 -0
- package/build/plugin/webpack.cjs +26 -0
- package/build/plugin/webpack.d.cts +8 -0
- package/build/plugin/webpack.d.cts.map +1 -0
- package/build/plugin/webpack.d.mts +8 -0
- package/build/plugin/webpack.d.mts.map +1 -0
- package/build/plugin/webpack.mjs +27 -0
- package/build/plugin/webpack.mjs.map +1 -0
- package/build/react/client/index.cjs +9 -0
- package/build/react/client/index.d.cts +5 -0
- package/build/react/client/index.d.mts +5 -0
- package/build/react/client/index.mjs +6 -0
- package/build/react/client/useTranslation.cjs +71 -0
- package/build/react/client/useTranslation.d.cts +42 -0
- package/build/react/client/useTranslation.d.cts.map +1 -0
- package/build/react/client/useTranslation.d.mts +42 -0
- package/build/react/client/useTranslation.d.mts.map +1 -0
- package/build/react/client/useTranslation.mjs +71 -0
- package/build/react/client/useTranslation.mjs.map +1 -0
- package/build/react/next/client.cjs +25 -0
- package/build/react/next/client.d.cts +9 -0
- package/build/react/next/client.d.cts.map +1 -0
- package/build/react/next/client.d.mts +9 -0
- package/build/react/next/client.d.mts.map +1 -0
- package/build/react/next/client.mjs +24 -0
- package/build/react/next/client.mjs.map +1 -0
- package/build/react/next/cookie-locale-resolver.cjs +29 -0
- package/build/react/next/cookie-locale-resolver.d.cts +33 -0
- package/build/react/next/cookie-locale-resolver.d.cts.map +1 -0
- package/build/react/next/cookie-locale-resolver.d.mts +33 -0
- package/build/react/next/cookie-locale-resolver.d.mts.map +1 -0
- package/build/react/next/cookie-locale-resolver.mjs +29 -0
- package/build/react/next/cookie-locale-resolver.mjs.map +1 -0
- package/build/react/next/server.cjs +21 -0
- package/build/react/next/server.d.cts +13 -0
- package/build/react/next/server.d.cts.map +1 -0
- package/build/react/next/server.d.mts +14 -0
- package/build/react/next/server.d.mts.map +1 -0
- package/build/react/next/server.mjs +20 -0
- package/build/react/next/server.mjs.map +1 -0
- package/build/react/server/ServerWeglotProvider.cjs +19 -0
- package/build/react/server/ServerWeglotProvider.d.cts +12 -0
- package/build/react/server/ServerWeglotProvider.d.cts.map +1 -0
- package/build/react/server/ServerWeglotProvider.d.mts +12 -0
- package/build/react/server/ServerWeglotProvider.d.mts.map +1 -0
- package/build/react/server/ServerWeglotProvider.mjs +19 -0
- package/build/react/server/ServerWeglotProvider.mjs.map +1 -0
- package/build/react/server/index.cjs +7 -0
- package/build/react/server/index.d.cts +4 -0
- package/build/react/server/index.d.mts +4 -0
- package/build/react/server/index.mjs +5 -0
- package/build/react/server/useTranslation.cjs +60 -0
- package/build/react/server/useTranslation.d.cts +36 -0
- package/build/react/server/useTranslation.d.cts.map +1 -0
- package/build/react/server/useTranslation.d.mts +36 -0
- package/build/react/server/useTranslation.d.mts.map +1 -0
- package/build/react/server/useTranslation.mjs +60 -0
- package/build/react/server/useTranslation.mjs.map +1 -0
- package/build/react/server-only/index.cjs +42 -0
- package/build/react/server-only/index.d.cts +38 -0
- package/build/react/server-only/index.d.cts.map +1 -0
- package/build/react/server-only/index.d.mts +38 -0
- package/build/react/server-only/index.d.mts.map +1 -0
- package/build/react/server-only/index.mjs +42 -0
- package/build/react/server-only/index.mjs.map +1 -0
- package/build/react/server-only/translations.cjs +86 -0
- package/build/react/server-only/translations.mjs +86 -0
- package/build/react/server-only/translations.mjs.map +1 -0
- package/build/react/shared/LocaleSwitcher.cjs +61 -0
- package/build/react/shared/LocaleSwitcher.d.cts +71 -0
- package/build/react/shared/LocaleSwitcher.d.cts.map +1 -0
- package/build/react/shared/LocaleSwitcher.d.mts +71 -0
- package/build/react/shared/LocaleSwitcher.d.mts.map +1 -0
- package/build/react/shared/LocaleSwitcher.mjs +61 -0
- package/build/react/shared/LocaleSwitcher.mjs.map +1 -0
- package/build/react/shared/WeglotContext.cjs +14 -0
- package/build/react/shared/WeglotContext.d.cts +34 -0
- package/build/react/shared/WeglotContext.d.cts.map +1 -0
- package/build/react/shared/WeglotContext.d.mts +34 -0
- package/build/react/shared/WeglotContext.d.mts.map +1 -0
- package/build/react/shared/WeglotContext.mjs +13 -0
- package/build/react/shared/WeglotContext.mjs.map +1 -0
- package/build/react/shared/WeglotProvider.cjs +250 -0
- package/build/react/shared/WeglotProvider.d.cts +60 -0
- package/build/react/shared/WeglotProvider.d.cts.map +1 -0
- package/build/react/shared/WeglotProvider.d.mts +60 -0
- package/build/react/shared/WeglotProvider.d.mts.map +1 -0
- package/build/react/shared/WeglotProvider.mjs +250 -0
- package/build/react/shared/WeglotProvider.mjs.map +1 -0
- package/build/react/shared/render-rich-text.cjs +56 -0
- package/build/react/shared/render-rich-text.d.cts +16 -0
- package/build/react/shared/render-rich-text.d.cts.map +1 -0
- package/build/react/shared/render-rich-text.d.mts +16 -0
- package/build/react/shared/render-rich-text.d.mts.map +1 -0
- package/build/react/shared/render-rich-text.mjs +55 -0
- package/build/react/shared/render-rich-text.mjs.map +1 -0
- package/build/react/shared/utils.cjs +34 -0
- package/build/react/shared/utils.mjs +35 -0
- package/build/react/shared/utils.mjs.map +1 -0
- package/build/react/types.d.cts +16 -0
- package/build/react/types.d.cts.map +1 -0
- package/build/react/types.d.mts +16 -0
- package/build/react/types.d.mts.map +1 -0
- package/build/runtime/html/segmenter.cjs +226 -0
- package/build/runtime/html/segmenter.mjs +225 -0
- package/build/runtime/html/segmenter.mjs.map +1 -0
- package/build/runtime/index.cjs +6 -0
- package/build/runtime/index.d.cts +2 -0
- package/build/runtime/index.d.mts +2 -0
- package/build/runtime/index.mjs +3 -0
- package/build/runtime/translate-dynamic.cjs +144 -0
- package/build/runtime/translate-dynamic.d.cts +29 -0
- package/build/runtime/translate-dynamic.d.cts.map +1 -0
- package/build/runtime/translate-dynamic.d.mts +29 -0
- package/build/runtime/translate-dynamic.d.mts.map +1 -0
- package/build/runtime/translate-dynamic.mjs +141 -0
- package/build/runtime/translate-dynamic.mjs.map +1 -0
- package/build/translation-server/logger.cjs +37 -0
- package/build/translation-server/logger.mjs +37 -0
- package/build/translation-server/logger.mjs.map +1 -0
- package/build/translation-server/translation-server.cjs +451 -0
- package/build/translation-server/translation-server.mjs +448 -0
- package/build/translation-server/translation-server.mjs.map +1 -0
- package/build/translators/api.cjs +12 -0
- package/build/translators/api.mjs +12 -0
- package/build/translators/api.mjs.map +1 -0
- package/build/translators/cache-factory.cjs +26 -0
- package/build/translators/cache-factory.mjs +27 -0
- package/build/translators/cache-factory.mjs.map +1 -0
- package/build/translators/local-cache.cjs +132 -0
- package/build/translators/local-cache.mjs +130 -0
- package/build/translators/local-cache.mjs.map +1 -0
- package/build/translators/translation-service.cjs +139 -0
- package/build/translators/translation-service.mjs +140 -0
- package/build/translators/translation-service.mjs.map +1 -0
- package/build/translators/weglot/api-client.cjs +131 -0
- package/build/translators/weglot/api-client.mjs +130 -0
- package/build/translators/weglot/api-client.mjs.map +1 -0
- package/build/translators/weglot/definitions/definitions.generated.cjs +53 -0
- package/build/translators/weglot/definitions/definitions.generated.mjs +52 -0
- package/build/translators/weglot/definitions/definitions.generated.mjs.map +1 -0
- package/build/translators/weglot/engine.cjs +43 -0
- package/build/translators/weglot/engine.mjs +40 -0
- package/build/translators/weglot/engine.mjs.map +1 -0
- package/build/translators/weglot/translator.cjs +67 -0
- package/build/translators/weglot/translator.mjs +68 -0
- package/build/translators/weglot/translator.mjs.map +1 -0
- package/build/translators/weglot/wire-format.cjs +128 -0
- package/build/translators/weglot/wire-format.mjs +129 -0
- package/build/translators/weglot/wire-format.mjs.map +1 -0
- package/build/types.d.cts +153 -0
- package/build/types.d.cts.map +1 -0
- package/build/types.d.mts +153 -0
- package/build/types.d.mts.map +1 -0
- package/build/utils/config-factory.cjs +100 -0
- package/build/utils/config-factory.mjs +97 -0
- package/build/utils/config-factory.mjs.map +1 -0
- package/build/utils/hash.cjs +17 -0
- package/build/utils/hash.mjs +16 -0
- package/build/utils/hash.mjs.map +1 -0
- package/build/utils/is-valid-locale.cjs +13 -0
- package/build/utils/is-valid-locale.mjs +13 -0
- package/build/utils/is-valid-locale.mjs.map +1 -0
- package/build/utils/logger.cjs +51 -0
- package/build/utils/logger.mjs +50 -0
- package/build/utils/logger.mjs.map +1 -0
- package/build/utils/path-helpers.cjs +49 -0
- package/build/utils/path-helpers.mjs +47 -0
- package/build/utils/path-helpers.mjs.map +1 -0
- package/build/utils/timeout.cjs +42 -0
- package/build/utils/timeout.mjs +41 -0
- package/build/utils/timeout.mjs.map +1 -0
- package/build/virtual/code-generator.cjs +58 -0
- package/build/virtual/code-generator.mjs +57 -0
- package/build/virtual/code-generator.mjs.map +1 -0
- package/build/virtual/config.cjs +19 -0
- package/build/virtual/config.d.cts +15 -0
- package/build/virtual/config.d.cts.map +1 -0
- package/build/virtual/config.d.mts +15 -0
- package/build/virtual/config.d.mts.map +1 -0
- package/build/virtual/config.mjs +14 -0
- package/build/virtual/config.mjs.map +1 -0
- package/build/virtual/locale/client.cjs +23 -0
- package/build/virtual/locale/client.d.cts +19 -0
- package/build/virtual/locale/client.d.cts.map +1 -0
- package/build/virtual/locale/client.d.mts +19 -0
- package/build/virtual/locale/client.d.mts.map +1 -0
- package/build/virtual/locale/client.mjs +22 -0
- package/build/virtual/locale/client.mjs.map +1 -0
- package/build/virtual/locale/server.cjs +13 -0
- package/build/virtual/locale/server.d.cts +13 -0
- package/build/virtual/locale/server.d.cts.map +1 -0
- package/build/virtual/locale/server.d.mts +13 -0
- package/build/virtual/locale/server.d.mts.map +1 -0
- package/build/virtual/locale/server.mjs +13 -0
- package/build/virtual/locale/server.mjs.map +1 -0
- package/package.json +260 -4
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_timeout = require('../utils/timeout.cjs');
|
|
3
|
+
const require_api = require('./api.cjs');
|
|
4
|
+
let fs_promises = require("fs/promises");
|
|
5
|
+
fs_promises = require_rolldown_runtime.__toESM(fs_promises);
|
|
6
|
+
let path = require("path");
|
|
7
|
+
path = require_rolldown_runtime.__toESM(path);
|
|
8
|
+
|
|
9
|
+
//#region src/translators/local-cache.ts
|
|
10
|
+
/**
|
|
11
|
+
* Local disk-based translation cache implementation
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Local file system cache for translations
|
|
15
|
+
* Stores translations as JSON files in weglot/cache/
|
|
16
|
+
*/
|
|
17
|
+
var LocalTranslationCache = class {
|
|
18
|
+
config;
|
|
19
|
+
/** One chain per locale: read-modify-write must not interleave. */
|
|
20
|
+
writes = /* @__PURE__ */ new Map();
|
|
21
|
+
writeCount = 0;
|
|
22
|
+
constructor(config, logger) {
|
|
23
|
+
this.logger = logger;
|
|
24
|
+
this.config = config;
|
|
25
|
+
}
|
|
26
|
+
enqueue(locale, task) {
|
|
27
|
+
const next = (this.writes.get(locale) ?? Promise.resolve()).then(task, task);
|
|
28
|
+
this.writes.set(locale, next.catch(() => {}));
|
|
29
|
+
return next;
|
|
30
|
+
}
|
|
31
|
+
getCachePath(locale) {
|
|
32
|
+
return path.join(this.config.cacheDir, `${locale}.json`);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Read dictionary file from disk
|
|
36
|
+
* Times out after 10 seconds to prevent indefinite hangs
|
|
37
|
+
*/
|
|
38
|
+
async getDictionary(locale) {
|
|
39
|
+
try {
|
|
40
|
+
const cachePath = this.getCachePath(locale);
|
|
41
|
+
const content = await require_timeout.withTimeout(fs_promises.readFile(cachePath, "utf-8"), require_timeout.DEFAULT_TIMEOUTS.FILE_IO, `Read cache for ${locale}`);
|
|
42
|
+
return JSON.parse(content);
|
|
43
|
+
} catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Write dictionary file to disk
|
|
49
|
+
* Times out after 10 seconds to prevent indefinite hangs
|
|
50
|
+
*/
|
|
51
|
+
async setDictionary(locale, dictionary) {
|
|
52
|
+
try {
|
|
53
|
+
const cachePath = this.getCachePath(locale);
|
|
54
|
+
const cacheDir = path.dirname(cachePath);
|
|
55
|
+
await require_timeout.withTimeout(fs_promises.mkdir(cacheDir, { recursive: true }), require_timeout.DEFAULT_TIMEOUTS.FILE_IO, `Create cache directory for ${locale}`);
|
|
56
|
+
const tempPath = `${cachePath}.${process.pid}.${this.writeCount++}.tmp`;
|
|
57
|
+
try {
|
|
58
|
+
await require_timeout.withTimeout(fs_promises.writeFile(tempPath, JSON.stringify(dictionary, null, 2), "utf-8"), require_timeout.DEFAULT_TIMEOUTS.FILE_IO, `Write cache for ${locale}`);
|
|
59
|
+
await fs_promises.rename(tempPath, cachePath);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
await fs_promises.unlink(tempPath).catch(() => {});
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
} catch (error) {
|
|
65
|
+
this.logger.error(`Failed to write cache for locale ${locale}:`, error);
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Get cached translations for a locale
|
|
71
|
+
*/
|
|
72
|
+
async get(locale, hashes) {
|
|
73
|
+
const dictionary = await this.getDictionary(locale);
|
|
74
|
+
if (!dictionary) return {};
|
|
75
|
+
if (hashes) return hashes.reduce((acc, hash) => ({
|
|
76
|
+
...acc,
|
|
77
|
+
[hash]: dictionary.entries[hash]
|
|
78
|
+
}), {});
|
|
79
|
+
return dictionary.entries || {};
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Update cache with new translations (merge)
|
|
83
|
+
*/
|
|
84
|
+
async update(locale, translations) {
|
|
85
|
+
await this.enqueue(locale, async () => {
|
|
86
|
+
const existing = await this.get(locale);
|
|
87
|
+
await this.setDictionary(locale, require_api.dictionaryFrom(locale, {
|
|
88
|
+
...existing,
|
|
89
|
+
...translations
|
|
90
|
+
}));
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Replace entire cache for a locale
|
|
95
|
+
*/
|
|
96
|
+
async set(locale, translations) {
|
|
97
|
+
await this.enqueue(locale, () => this.setDictionary(locale, require_api.dictionaryFrom(locale, translations)));
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Check if cache exists for a locale
|
|
101
|
+
*/
|
|
102
|
+
async has(locale) {
|
|
103
|
+
try {
|
|
104
|
+
const cachePath = this.getCachePath(locale);
|
|
105
|
+
await fs_promises.access(cachePath);
|
|
106
|
+
return true;
|
|
107
|
+
} catch {
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Clear cache for a specific locale
|
|
113
|
+
*/
|
|
114
|
+
async clear(locale) {
|
|
115
|
+
try {
|
|
116
|
+
const cachePath = this.getCachePath(locale);
|
|
117
|
+
await fs_promises.unlink(cachePath);
|
|
118
|
+
} catch {}
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Clear all cached translations
|
|
122
|
+
*/
|
|
123
|
+
async clearAll() {
|
|
124
|
+
try {
|
|
125
|
+
const files = await fs_promises.readdir(this.config.cacheDir);
|
|
126
|
+
await Promise.all(files.filter((file) => file.endsWith(".json")).map((file) => fs_promises.unlink(path.join(this.config.cacheDir, file))));
|
|
127
|
+
} catch {}
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
//#endregion
|
|
132
|
+
exports.LocalTranslationCache = LocalTranslationCache;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { DEFAULT_TIMEOUTS, withTimeout } from "../utils/timeout.mjs";
|
|
2
|
+
import { dictionaryFrom } from "./api.mjs";
|
|
3
|
+
import * as fs$1 from "fs/promises";
|
|
4
|
+
import * as path$1 from "path";
|
|
5
|
+
|
|
6
|
+
//#region src/translators/local-cache.ts
|
|
7
|
+
/**
|
|
8
|
+
* Local disk-based translation cache implementation
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Local file system cache for translations
|
|
12
|
+
* Stores translations as JSON files in weglot/cache/
|
|
13
|
+
*/
|
|
14
|
+
var LocalTranslationCache = class {
|
|
15
|
+
config;
|
|
16
|
+
/** One chain per locale: read-modify-write must not interleave. */
|
|
17
|
+
writes = /* @__PURE__ */ new Map();
|
|
18
|
+
writeCount = 0;
|
|
19
|
+
constructor(config, logger) {
|
|
20
|
+
this.logger = logger;
|
|
21
|
+
this.config = config;
|
|
22
|
+
}
|
|
23
|
+
enqueue(locale, task) {
|
|
24
|
+
const next = (this.writes.get(locale) ?? Promise.resolve()).then(task, task);
|
|
25
|
+
this.writes.set(locale, next.catch(() => {}));
|
|
26
|
+
return next;
|
|
27
|
+
}
|
|
28
|
+
getCachePath(locale) {
|
|
29
|
+
return path$1.join(this.config.cacheDir, `${locale}.json`);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Read dictionary file from disk
|
|
33
|
+
* Times out after 10 seconds to prevent indefinite hangs
|
|
34
|
+
*/
|
|
35
|
+
async getDictionary(locale) {
|
|
36
|
+
try {
|
|
37
|
+
const cachePath = this.getCachePath(locale);
|
|
38
|
+
const content = await withTimeout(fs$1.readFile(cachePath, "utf-8"), DEFAULT_TIMEOUTS.FILE_IO, `Read cache for ${locale}`);
|
|
39
|
+
return JSON.parse(content);
|
|
40
|
+
} catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Write dictionary file to disk
|
|
46
|
+
* Times out after 10 seconds to prevent indefinite hangs
|
|
47
|
+
*/
|
|
48
|
+
async setDictionary(locale, dictionary) {
|
|
49
|
+
try {
|
|
50
|
+
const cachePath = this.getCachePath(locale);
|
|
51
|
+
const cacheDir = path$1.dirname(cachePath);
|
|
52
|
+
await withTimeout(fs$1.mkdir(cacheDir, { recursive: true }), DEFAULT_TIMEOUTS.FILE_IO, `Create cache directory for ${locale}`);
|
|
53
|
+
const tempPath = `${cachePath}.${process.pid}.${this.writeCount++}.tmp`;
|
|
54
|
+
try {
|
|
55
|
+
await withTimeout(fs$1.writeFile(tempPath, JSON.stringify(dictionary, null, 2), "utf-8"), DEFAULT_TIMEOUTS.FILE_IO, `Write cache for ${locale}`);
|
|
56
|
+
await fs$1.rename(tempPath, cachePath);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
await fs$1.unlink(tempPath).catch(() => {});
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
} catch (error) {
|
|
62
|
+
this.logger.error(`Failed to write cache for locale ${locale}:`, error);
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Get cached translations for a locale
|
|
68
|
+
*/
|
|
69
|
+
async get(locale, hashes) {
|
|
70
|
+
const dictionary = await this.getDictionary(locale);
|
|
71
|
+
if (!dictionary) return {};
|
|
72
|
+
if (hashes) return hashes.reduce((acc, hash) => ({
|
|
73
|
+
...acc,
|
|
74
|
+
[hash]: dictionary.entries[hash]
|
|
75
|
+
}), {});
|
|
76
|
+
return dictionary.entries || {};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Update cache with new translations (merge)
|
|
80
|
+
*/
|
|
81
|
+
async update(locale, translations) {
|
|
82
|
+
await this.enqueue(locale, async () => {
|
|
83
|
+
const existing = await this.get(locale);
|
|
84
|
+
await this.setDictionary(locale, dictionaryFrom(locale, {
|
|
85
|
+
...existing,
|
|
86
|
+
...translations
|
|
87
|
+
}));
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Replace entire cache for a locale
|
|
92
|
+
*/
|
|
93
|
+
async set(locale, translations) {
|
|
94
|
+
await this.enqueue(locale, () => this.setDictionary(locale, dictionaryFrom(locale, translations)));
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Check if cache exists for a locale
|
|
98
|
+
*/
|
|
99
|
+
async has(locale) {
|
|
100
|
+
try {
|
|
101
|
+
const cachePath = this.getCachePath(locale);
|
|
102
|
+
await fs$1.access(cachePath);
|
|
103
|
+
return true;
|
|
104
|
+
} catch {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Clear cache for a specific locale
|
|
110
|
+
*/
|
|
111
|
+
async clear(locale) {
|
|
112
|
+
try {
|
|
113
|
+
const cachePath = this.getCachePath(locale);
|
|
114
|
+
await fs$1.unlink(cachePath);
|
|
115
|
+
} catch {}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Clear all cached translations
|
|
119
|
+
*/
|
|
120
|
+
async clearAll() {
|
|
121
|
+
try {
|
|
122
|
+
const files = await fs$1.readdir(this.config.cacheDir);
|
|
123
|
+
await Promise.all(files.filter((file) => file.endsWith(".json")).map((file) => fs$1.unlink(path$1.join(this.config.cacheDir, file))));
|
|
124
|
+
} catch {}
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
//#endregion
|
|
129
|
+
export { LocalTranslationCache };
|
|
130
|
+
//# sourceMappingURL=local-cache.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"local-cache.mjs","names":["logger: Logger","path","fs"],"sources":["../../src/translators/local-cache.ts"],"sourcesContent":["/**\n * Local disk-based translation cache implementation\n */\n\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport type { LocalCacheConfig, TranslationCache } from \"./cache\";\nimport { dictionaryFrom, type DictionarySchema } from \"./api\";\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../utils/timeout\";\nimport type { Logger } from \"../utils/logger\";\nimport type { LocaleCode } from \"../locale\";\n\n/**\n * Local file system cache for translations\n * Stores translations as JSON files in weglot/cache/\n */\nexport class LocalTranslationCache implements TranslationCache {\n private config: LocalCacheConfig;\n /** One chain per locale: read-modify-write must not interleave. */\n private writes = new Map<LocaleCode, Promise<unknown>>();\n private writeCount = 0;\n\n constructor(\n config: LocalCacheConfig,\n private logger: Logger,\n ) {\n this.config = config;\n }\n\n private enqueue<T>(locale: LocaleCode, task: () => Promise<T>): Promise<T> {\n const previous = this.writes.get(locale) ?? Promise.resolve();\n const next = previous.then(task, task);\n this.writes.set(\n locale,\n next.catch(() => {}),\n );\n return next;\n }\n\n private getCachePath(locale: LocaleCode): string {\n return path.join(this.config.cacheDir, `${locale}.json`);\n }\n\n /**\n * Read dictionary file from disk\n * Times out after 10 seconds to prevent indefinite hangs\n */\n async getDictionary(locale: LocaleCode): Promise<DictionarySchema | null> {\n try {\n const cachePath = this.getCachePath(locale);\n const content = await withTimeout(\n fs.readFile(cachePath, \"utf-8\"),\n DEFAULT_TIMEOUTS.FILE_IO,\n `Read cache for ${locale}`,\n );\n return JSON.parse(content);\n } catch {\n return null;\n }\n }\n\n /**\n * Write dictionary file to disk\n * Times out after 10 seconds to prevent indefinite hangs\n */\n private async setDictionary(\n locale: LocaleCode,\n dictionary: DictionarySchema,\n ): Promise<void> {\n try {\n const cachePath = this.getCachePath(locale);\n const cacheDir = path.dirname(cachePath);\n\n // Ensure cache directory exists\n await withTimeout(\n fs.mkdir(cacheDir, { recursive: true }),\n DEFAULT_TIMEOUTS.FILE_IO,\n `Create cache directory for ${locale}`,\n );\n\n // Write through a temporary file: a rename is atomic, so a reader never\n // sees a partial dictionary and concurrent writers cannot interleave.\n const tempPath = `${cachePath}.${process.pid}.${this.writeCount++}.tmp`;\n try {\n await withTimeout(\n fs.writeFile(tempPath, JSON.stringify(dictionary, null, 2), \"utf-8\"),\n DEFAULT_TIMEOUTS.FILE_IO,\n `Write cache for ${locale}`,\n );\n await fs.rename(tempPath, cachePath);\n } catch (error) {\n await fs.unlink(tempPath).catch(() => {});\n throw error;\n }\n } catch (error) {\n this.logger.error(`Failed to write cache for locale ${locale}:`, error);\n throw error;\n }\n }\n\n /**\n * Get cached translations for a locale\n */\n async get(\n locale: LocaleCode,\n hashes?: string[],\n ): Promise<Record<string, string>> {\n const dictionary = await this.getDictionary(locale);\n if (!dictionary) {\n return {};\n }\n if (hashes) {\n return hashes.reduce(\n (acc, hash) => ({ ...acc, [hash]: dictionary.entries[hash] }),\n {},\n );\n }\n return dictionary.entries || {};\n }\n\n /**\n * Update cache with new translations (merge)\n */\n async update(\n locale: LocaleCode,\n translations: Record<string, string>,\n ): Promise<void> {\n await this.enqueue(locale, async () => {\n const existing = await this.get(locale);\n await this.setDictionary(\n locale,\n dictionaryFrom(locale, { ...existing, ...translations }),\n );\n });\n }\n\n /**\n * Replace entire cache for a locale\n */\n async set(\n locale: LocaleCode,\n translations: Record<string, string>,\n ): Promise<void> {\n await this.enqueue(locale, () =>\n this.setDictionary(locale, dictionaryFrom(locale, translations)),\n );\n }\n\n /**\n * Check if cache exists for a locale\n */\n async has(locale: LocaleCode): Promise<boolean> {\n try {\n const cachePath = this.getCachePath(locale);\n await fs.access(cachePath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Clear cache for a specific locale\n */\n async clear(locale: LocaleCode): Promise<void> {\n try {\n const cachePath = this.getCachePath(locale);\n await fs.unlink(cachePath);\n } catch {\n // Ignore errors if file doesn't exist\n }\n }\n\n /**\n * Clear all cached translations\n */\n async clearAll(): Promise<void> {\n try {\n const files = await fs.readdir(this.config.cacheDir);\n\n await Promise.all(\n files\n .filter((file) => file.endsWith(\".json\"))\n .map((file) => fs.unlink(path.join(this.config.cacheDir, file))),\n );\n } catch {\n // Ignore errors if directory doesn't exist\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,IA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V,MAAM,IACJ,QACA,QACiC;EACjC,MAAM,aAAa,MAAM,KAAK,cAAc,OAAO;AACnD,MAAI,CAAC,WACH,QAAO,EAAE;AAEX,MAAI,OACF,QAAO,OAAO,QACX,KAAK,UAAU;GAAE,GAAG;IAAM,OAAO,WAAW,QAAQ;GAAO,GAC5D,EAAE,CACH;AAEH,SAAO,WAAW,WAAW,EAAE;;;;;CAMjC,MAAM,OACJ,QACA,cACe;AACf,QAAM,KAAK,QAAQ,QAAQ,YAAY;GACrC,MAAM,WAAW,MAAM,KAAK,IAAI,OAAO;AACvC,SAAM,KAAK,cACT,QACA,eAAe,QAAQ;IAAE,GAAG;IAAU,GAAG;IAAc,CAAC,CACzD;IACD;;;;;CAMJ,MAAM,IACJ,QACA,cACe;AACf,QAAM,KAAK,QAAQ,cACjB,KAAK,cAAc,QAAQ,eAAe,QAAQ,aAAa,CAAC,CACjE;;;;;CAMH,MAAM,IAAI,QAAsC;AAC9C,MAAI;GACF,MAAM,YAAY,KAAK,aAAa,OAAO;AAC3C,SAAMA,KAAG,OAAO,UAAU;AAC1B,UAAO;UACD;AACN,UAAO;;;;;;CAOX,MAAM,MAAM,QAAmC;AAC7C,MAAI;GACF,MAAM,YAAY,KAAK,aAAa,OAAO;AAC3C,SAAMA,KAAG,OAAO,UAAU;UACpB;;;;;CAQV,MAAM,WAA0B;AAC9B,MAAI;GACF,MAAM,QAAQ,MAAMA,KAAG,QAAQ,KAAK,OAAO,SAAS;AAEpD,SAAM,QAAQ,IACZ,MACG,QAAQ,SAAS,KAAK,SAAS,QAAQ,CAAC,CACxC,KAAK,SAASA,KAAG,OAAOD,OAAK,KAAK,KAAK,OAAO,UAAU,KAAK,CAAC,CAAC,CACnE;UACK"}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
const require_api_client = require('./weglot/api-client.cjs');
|
|
2
|
+
const require_translator = require('./weglot/translator.cjs');
|
|
3
|
+
const require_cache_factory = require('./cache-factory.cjs');
|
|
4
|
+
|
|
5
|
+
//#region src/translators/translation-service.ts
|
|
6
|
+
var TranslationService = class {
|
|
7
|
+
translator;
|
|
8
|
+
cache;
|
|
9
|
+
constructor(config, logger) {
|
|
10
|
+
this.config = config;
|
|
11
|
+
this.logger = logger;
|
|
12
|
+
this.cache = require_cache_factory.createCache(config);
|
|
13
|
+
this.translator = new require_translator.WeglotTranslator({
|
|
14
|
+
apiKey: config.apiKey,
|
|
15
|
+
sourceLocale: config.sourceLocale,
|
|
16
|
+
apiLocales: config.apiLocales,
|
|
17
|
+
translationEngine: config.translationEngine,
|
|
18
|
+
apiBaseUrl: config.apiBaseUrl,
|
|
19
|
+
translationTimeoutMs: config.translationTimeout * 1e3
|
|
20
|
+
}, this.logger);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Translate entries to target locale
|
|
24
|
+
*
|
|
25
|
+
* @param locale Target locale (including source locale)
|
|
26
|
+
* @param metadata Metadata schema with all entries
|
|
27
|
+
* @param requestedHashes Optional: only translate specific hashes
|
|
28
|
+
* @returns Translation result with translations and errors
|
|
29
|
+
*/
|
|
30
|
+
async translate(locale, metadata, requestedHashes) {
|
|
31
|
+
const startTime = performance.now();
|
|
32
|
+
const workingHashes = requestedHashes || Object.keys(metadata);
|
|
33
|
+
this.logger.debug(`Translation requested for ${workingHashes.length} hashes in locale: ${locale}`);
|
|
34
|
+
const cachedTranslations = await this.cache.get(locale);
|
|
35
|
+
const uncachedHashes = workingHashes.filter((hash) => !cachedTranslations[hash]);
|
|
36
|
+
this.logger.debug(`${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`);
|
|
37
|
+
const cachedCount = workingHashes.length - uncachedHashes.length;
|
|
38
|
+
if (uncachedHashes.length === 0) return {
|
|
39
|
+
translations: this.pickTranslations(cachedTranslations, workingHashes),
|
|
40
|
+
errors: [],
|
|
41
|
+
stats: {
|
|
42
|
+
total: workingHashes.length,
|
|
43
|
+
cached: cachedCount,
|
|
44
|
+
translated: 0,
|
|
45
|
+
failed: 0
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
this.logger.debug(`Generating translations for ${uncachedHashes.length} uncached hashes in ${locale}...`);
|
|
49
|
+
const filteredMetadata = Object.fromEntries(uncachedHashes.map((hash) => [hash, metadata[hash]]).filter(([_, entry]) => entry !== void 0));
|
|
50
|
+
const entriesToTranslate = this.prepareEntries(filteredMetadata, uncachedHashes);
|
|
51
|
+
let newTranslations = {};
|
|
52
|
+
const errors = [];
|
|
53
|
+
if (locale === this.config.sourceLocale) {
|
|
54
|
+
this.logger.debug(`Source locale detected, returning sourceText for ${uncachedHashes.length} entries`);
|
|
55
|
+
for (const [hash, entry] of Object.entries(entriesToTranslate)) newTranslations[hash] = entry.text;
|
|
56
|
+
} else if (Object.keys(entriesToTranslate).length > 0) {
|
|
57
|
+
try {
|
|
58
|
+
this.logger.debug(`Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`);
|
|
59
|
+
newTranslations = { ...await this.translator.translate(locale, entriesToTranslate) };
|
|
60
|
+
} catch (error) {
|
|
61
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
62
|
+
const unsupportedLocale = error instanceof require_api_client.UnsupportedLanguagePairError;
|
|
63
|
+
if (unsupportedLocale) this.logger.warn(`Locale "${locale}" cannot be translated: ${errorMessage}`);
|
|
64
|
+
else this.logger.error(`Translation failed for locale "${locale}": ${errorMessage}`);
|
|
65
|
+
if (error instanceof Error && error.stack) this.logger.debug(`Stack trace: ${error.stack}`);
|
|
66
|
+
return {
|
|
67
|
+
unsupportedLocale,
|
|
68
|
+
translations: this.pickTranslations(cachedTranslations, workingHashes),
|
|
69
|
+
errors: [{
|
|
70
|
+
hash: "all",
|
|
71
|
+
sourceText: "all",
|
|
72
|
+
error: errorMessage
|
|
73
|
+
}],
|
|
74
|
+
stats: {
|
|
75
|
+
total: workingHashes.length,
|
|
76
|
+
cached: cachedCount,
|
|
77
|
+
translated: 0,
|
|
78
|
+
failed: uncachedHashes.length
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
for (const hash of uncachedHashes) if (!newTranslations[hash]) {
|
|
83
|
+
const entry = filteredMetadata[hash];
|
|
84
|
+
errors.push({
|
|
85
|
+
hash,
|
|
86
|
+
sourceText: entry?.sourceText || "",
|
|
87
|
+
error: "No translation returned yet; Weglot may still be generating it"
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (Object.keys(newTranslations).length > 0) try {
|
|
92
|
+
await this.cache.update(locale, newTranslations);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
this.logger.error(`Failed to update cache:`, error);
|
|
95
|
+
}
|
|
96
|
+
const allTranslations = {
|
|
97
|
+
...cachedTranslations,
|
|
98
|
+
...newTranslations
|
|
99
|
+
};
|
|
100
|
+
const result = this.pickTranslations(allTranslations, workingHashes);
|
|
101
|
+
const endTime = performance.now();
|
|
102
|
+
this.logger.debug(`Translation completed for ${locale}: ${Object.keys(newTranslations).length} new, ${cachedCount} cached, ${errors.length} errors in ${(endTime - startTime).toFixed(2)}ms`);
|
|
103
|
+
return {
|
|
104
|
+
translations: result,
|
|
105
|
+
errors,
|
|
106
|
+
stats: {
|
|
107
|
+
total: workingHashes.length,
|
|
108
|
+
cached: cachedCount,
|
|
109
|
+
translated: Object.keys(newTranslations).length,
|
|
110
|
+
failed: errors.length
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Prepare metadata entries for translation
|
|
116
|
+
*/
|
|
117
|
+
prepareEntries(metadata, hashes) {
|
|
118
|
+
const entries = {};
|
|
119
|
+
for (const hash of hashes) {
|
|
120
|
+
const entry = metadata[hash];
|
|
121
|
+
if (entry) entries[hash] = {
|
|
122
|
+
text: entry.sourceText,
|
|
123
|
+
context: entry.context || {}
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
return entries;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Pick only requested translations from the full set
|
|
130
|
+
*/
|
|
131
|
+
pickTranslations(allTranslations, requestedHashes) {
|
|
132
|
+
const result = {};
|
|
133
|
+
for (const hash of requestedHashes) if (allTranslations[hash]) result[hash] = allTranslations[hash];
|
|
134
|
+
return result;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
//#endregion
|
|
139
|
+
exports.TranslationService = TranslationService;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { UnsupportedLanguagePairError } from "./weglot/api-client.mjs";
|
|
2
|
+
import { WeglotTranslator } from "./weglot/translator.mjs";
|
|
3
|
+
import { createCache } from "./cache-factory.mjs";
|
|
4
|
+
|
|
5
|
+
//#region src/translators/translation-service.ts
|
|
6
|
+
var TranslationService = class {
|
|
7
|
+
translator;
|
|
8
|
+
cache;
|
|
9
|
+
constructor(config, logger) {
|
|
10
|
+
this.config = config;
|
|
11
|
+
this.logger = logger;
|
|
12
|
+
this.cache = createCache(config);
|
|
13
|
+
this.translator = new WeglotTranslator({
|
|
14
|
+
apiKey: config.apiKey,
|
|
15
|
+
sourceLocale: config.sourceLocale,
|
|
16
|
+
apiLocales: config.apiLocales,
|
|
17
|
+
translationEngine: config.translationEngine,
|
|
18
|
+
apiBaseUrl: config.apiBaseUrl,
|
|
19
|
+
translationTimeoutMs: config.translationTimeout * 1e3
|
|
20
|
+
}, this.logger);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Translate entries to target locale
|
|
24
|
+
*
|
|
25
|
+
* @param locale Target locale (including source locale)
|
|
26
|
+
* @param metadata Metadata schema with all entries
|
|
27
|
+
* @param requestedHashes Optional: only translate specific hashes
|
|
28
|
+
* @returns Translation result with translations and errors
|
|
29
|
+
*/
|
|
30
|
+
async translate(locale, metadata, requestedHashes) {
|
|
31
|
+
const startTime = performance.now();
|
|
32
|
+
const workingHashes = requestedHashes || Object.keys(metadata);
|
|
33
|
+
this.logger.debug(`Translation requested for ${workingHashes.length} hashes in locale: ${locale}`);
|
|
34
|
+
const cachedTranslations = await this.cache.get(locale);
|
|
35
|
+
const uncachedHashes = workingHashes.filter((hash) => !cachedTranslations[hash]);
|
|
36
|
+
this.logger.debug(`${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`);
|
|
37
|
+
const cachedCount = workingHashes.length - uncachedHashes.length;
|
|
38
|
+
if (uncachedHashes.length === 0) return {
|
|
39
|
+
translations: this.pickTranslations(cachedTranslations, workingHashes),
|
|
40
|
+
errors: [],
|
|
41
|
+
stats: {
|
|
42
|
+
total: workingHashes.length,
|
|
43
|
+
cached: cachedCount,
|
|
44
|
+
translated: 0,
|
|
45
|
+
failed: 0
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
this.logger.debug(`Generating translations for ${uncachedHashes.length} uncached hashes in ${locale}...`);
|
|
49
|
+
const filteredMetadata = Object.fromEntries(uncachedHashes.map((hash) => [hash, metadata[hash]]).filter(([_, entry]) => entry !== void 0));
|
|
50
|
+
const entriesToTranslate = this.prepareEntries(filteredMetadata, uncachedHashes);
|
|
51
|
+
let newTranslations = {};
|
|
52
|
+
const errors = [];
|
|
53
|
+
if (locale === this.config.sourceLocale) {
|
|
54
|
+
this.logger.debug(`Source locale detected, returning sourceText for ${uncachedHashes.length} entries`);
|
|
55
|
+
for (const [hash, entry] of Object.entries(entriesToTranslate)) newTranslations[hash] = entry.text;
|
|
56
|
+
} else if (Object.keys(entriesToTranslate).length > 0) {
|
|
57
|
+
try {
|
|
58
|
+
this.logger.debug(`Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`);
|
|
59
|
+
newTranslations = { ...await this.translator.translate(locale, entriesToTranslate) };
|
|
60
|
+
} catch (error) {
|
|
61
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
62
|
+
const unsupportedLocale = error instanceof UnsupportedLanguagePairError;
|
|
63
|
+
if (unsupportedLocale) this.logger.warn(`Locale "${locale}" cannot be translated: ${errorMessage}`);
|
|
64
|
+
else this.logger.error(`Translation failed for locale "${locale}": ${errorMessage}`);
|
|
65
|
+
if (error instanceof Error && error.stack) this.logger.debug(`Stack trace: ${error.stack}`);
|
|
66
|
+
return {
|
|
67
|
+
unsupportedLocale,
|
|
68
|
+
translations: this.pickTranslations(cachedTranslations, workingHashes),
|
|
69
|
+
errors: [{
|
|
70
|
+
hash: "all",
|
|
71
|
+
sourceText: "all",
|
|
72
|
+
error: errorMessage
|
|
73
|
+
}],
|
|
74
|
+
stats: {
|
|
75
|
+
total: workingHashes.length,
|
|
76
|
+
cached: cachedCount,
|
|
77
|
+
translated: 0,
|
|
78
|
+
failed: uncachedHashes.length
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
for (const hash of uncachedHashes) if (!newTranslations[hash]) {
|
|
83
|
+
const entry = filteredMetadata[hash];
|
|
84
|
+
errors.push({
|
|
85
|
+
hash,
|
|
86
|
+
sourceText: entry?.sourceText || "",
|
|
87
|
+
error: "No translation returned yet; Weglot may still be generating it"
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (Object.keys(newTranslations).length > 0) try {
|
|
92
|
+
await this.cache.update(locale, newTranslations);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
this.logger.error(`Failed to update cache:`, error);
|
|
95
|
+
}
|
|
96
|
+
const allTranslations = {
|
|
97
|
+
...cachedTranslations,
|
|
98
|
+
...newTranslations
|
|
99
|
+
};
|
|
100
|
+
const result = this.pickTranslations(allTranslations, workingHashes);
|
|
101
|
+
const endTime = performance.now();
|
|
102
|
+
this.logger.debug(`Translation completed for ${locale}: ${Object.keys(newTranslations).length} new, ${cachedCount} cached, ${errors.length} errors in ${(endTime - startTime).toFixed(2)}ms`);
|
|
103
|
+
return {
|
|
104
|
+
translations: result,
|
|
105
|
+
errors,
|
|
106
|
+
stats: {
|
|
107
|
+
total: workingHashes.length,
|
|
108
|
+
cached: cachedCount,
|
|
109
|
+
translated: Object.keys(newTranslations).length,
|
|
110
|
+
failed: errors.length
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Prepare metadata entries for translation
|
|
116
|
+
*/
|
|
117
|
+
prepareEntries(metadata, hashes) {
|
|
118
|
+
const entries = {};
|
|
119
|
+
for (const hash of hashes) {
|
|
120
|
+
const entry = metadata[hash];
|
|
121
|
+
if (entry) entries[hash] = {
|
|
122
|
+
text: entry.sourceText,
|
|
123
|
+
context: entry.context || {}
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
return entries;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Pick only requested translations from the full set
|
|
130
|
+
*/
|
|
131
|
+
pickTranslations(allTranslations, requestedHashes) {
|
|
132
|
+
const result = {};
|
|
133
|
+
for (const hash of requestedHashes) if (allTranslations[hash]) result[hash] = allTranslations[hash];
|
|
134
|
+
return result;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
//#endregion
|
|
139
|
+
export { TranslationService };
|
|
140
|
+
//# sourceMappingURL=translation-service.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"translation-service.mjs","names":["config: TranslationServiceConfig","logger: Logger","filteredMetadata: MetadataSchema","newTranslations: Record<string, string>","errors: TranslationError[]","entries: Record<string, TranslatableEntry>","result: Record<string, string>"],"sources":["../../src/translators/translation-service.ts"],"sourcesContent":["/**\n * TranslationService - Main orchestrator for translation workflow\n *\n * Responsibilities:\n * - Coordinates between metadata, cache, and translator\n * - Determines what needs translation\n * - Handles caching strategy\n * - Manages partial failures\n */\n\nimport type { TranslationCache } from \"./cache\";\nimport type { TranslatableEntry, Translator } from \"./api\";\nimport type { WeglotEnvironment, MetadataSchema } from \"../types\";\nimport type { Logger } from \"../utils/logger\";\nimport type { LocaleCode } from \"../locale\";\nimport { UnsupportedLanguagePairError, WeglotTranslator } from \"./weglot\";\nimport { type CacheConfig, createCache } from \"./cache-factory\";\n\nexport type TranslationServiceConfig = {\n /**\n * Weglot project API key\n */\n apiKey: string;\n\n /**\n * Source locale (e.g., \"en\")\n */\n sourceLocale: LocaleCode;\n\n /** Public locale to the language code the translate API expects. */\n apiLocales?: Record<string, LocaleCode>;\n\n /** From the project settings; the modern engine when absent. */\n translationEngine?: number;\n\n /** The project's regional API host, from the project settings. */\n apiBaseUrl?: string;\n\n /** Seconds to wait for translations Weglot is still generating. */\n translationTimeout: number;\n\n environment: WeglotEnvironment;\n} & CacheConfig;\n\nexport interface TranslationResult {\n /**\n * Successfully translated entries (hash -> translated text)\n */\n translations: Record<string, string>;\n\n errors: TranslationError[];\n\n /** The API refuses this target, so callers report it and move on. */\n unsupportedLocale?: boolean;\n\n stats: {\n total: number;\n cached: number;\n translated: number;\n failed: number;\n };\n}\n\nexport interface TranslationError {\n hash: string;\n sourceText: string;\n error: string;\n}\n\nexport class TranslationService {\n private translator: Translator<any>;\n private cache: TranslationCache;\n\n constructor(\n private config: TranslationServiceConfig,\n private logger: Logger,\n ) {\n this.cache = createCache(config);\n this.translator = new WeglotTranslator(\n {\n apiKey: config.apiKey,\n sourceLocale: config.sourceLocale,\n apiLocales: config.apiLocales,\n translationEngine: config.translationEngine,\n apiBaseUrl: config.apiBaseUrl,\n translationTimeoutMs: config.translationTimeout * 1000,\n },\n this.logger,\n );\n }\n\n /**\n * Translate entries to target locale\n *\n * @param locale Target locale (including source locale)\n * @param metadata Metadata schema with all entries\n * @param requestedHashes Optional: only translate specific hashes\n * @returns Translation result with translations and errors\n */\n async translate(\n locale: LocaleCode,\n metadata: MetadataSchema,\n requestedHashes?: string[],\n ): Promise<TranslationResult> {\n const startTime = performance.now();\n\n // Step 1: Determine which hashes we need to work with\n const workingHashes = requestedHashes || Object.keys(metadata);\n\n this.logger.debug(\n `Translation requested for ${workingHashes.length} hashes in locale: ${locale}`,\n );\n\n // Step 2: Check cache first (same for all locales, including source)\n const cachedTranslations = await this.cache.get(locale);\n\n // Step 3: Determine what needs translation\n const uncachedHashes = workingHashes.filter(\n (hash) => !cachedTranslations[hash],\n );\n this.logger.debug(\n `${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`,\n );\n\n const cachedCount = workingHashes.length - uncachedHashes.length;\n\n if (uncachedHashes.length === 0) {\n return {\n translations: this.pickTranslations(cachedTranslations, workingHashes),\n errors: [],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: 0,\n },\n };\n }\n\n this.logger.debug(\n `Generating translations for ${uncachedHashes.length} uncached hashes in ${locale}...`,\n );\n\n // Step 4: Filter metadata to only uncached entries\n const filteredMetadata: MetadataSchema = Object.fromEntries(\n uncachedHashes\n .map((hash) => [hash, metadata[hash]])\n .filter(([_, entry]) => entry !== undefined),\n );\n\n // Step 5: Prepare entries for translation\n const entriesToTranslate = this.prepareEntries(\n filteredMetadata,\n uncachedHashes,\n );\n\n // Step 6: Translate or return source text\n let newTranslations: Record<string, string> = {};\n const errors: TranslationError[] = [];\n\n if (locale === this.config.sourceLocale) {\n // For source locale, just return the sourceText\n this.logger.debug(\n `Source locale detected, returning sourceText for ${uncachedHashes.length} entries`,\n );\n for (const [hash, entry] of Object.entries(entriesToTranslate)) {\n newTranslations[hash] = entry.text;\n }\n } else if (Object.keys(entriesToTranslate).length > 0) {\n // For other locales, translate entries\n try {\n this.logger.debug(\n `Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`,\n );\n const translatedTexts = await this.translator.translate(\n locale,\n entriesToTranslate,\n );\n newTranslations = { ...translatedTexts };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n const unsupportedLocale = error instanceof UnsupportedLanguagePairError;\n if (unsupportedLocale) {\n this.logger.warn(\n `Locale \"${locale}\" cannot be translated: ${errorMessage}`,\n );\n } else {\n this.logger.error(\n `Translation failed for locale \"${locale}\": ${errorMessage}`,\n );\n }\n if (error instanceof Error && error.stack) {\n this.logger.debug(`Stack trace: ${error.stack}`);\n }\n\n return {\n unsupportedLocale,\n translations: this.pickTranslations(\n cachedTranslations,\n workingHashes,\n ),\n errors: [\n {\n hash: \"all\",\n sourceText: \"all\",\n error: errorMessage,\n },\n ],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: uncachedHashes.length,\n },\n };\n }\n\n // Check for partial failures (some hashes didn't get translated)\n for (const hash of uncachedHashes) {\n if (!newTranslations[hash]) {\n const entry = filteredMetadata[hash];\n errors.push({\n hash,\n sourceText: entry?.sourceText || \"\",\n error: \"No translation returned yet; Weglot may still be generating it\",\n });\n }\n }\n }\n\n // Step 7: Update cache with successful translations\n if (Object.keys(newTranslations).length > 0) {\n try {\n await this.cache.update(locale, newTranslations);\n } catch (error) {\n this.logger.error(`Failed to update cache:`, error);\n // Don't fail the request if cache update fails\n }\n }\n\n // Step 8: Merge and return\n const allTranslations = { ...cachedTranslations, ...newTranslations };\n const result = this.pickTranslations(allTranslations, workingHashes);\n\n const endTime = performance.now();\n this.logger.debug(\n `Translation completed for ${locale}: ${Object.keys(newTranslations).length} new, ${cachedCount} cached, ${errors.length} errors in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n return {\n translations: result,\n errors,\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: Object.keys(newTranslations).length,\n failed: errors.length,\n },\n };\n }\n\n /**\n * Prepare metadata entries for translation\n */\n private prepareEntries(\n metadata: MetadataSchema,\n hashes: string[],\n ): Record<string, TranslatableEntry> {\n const entries: Record<string, TranslatableEntry> = {};\n\n for (const hash of hashes) {\n const entry = metadata[hash];\n if (entry) {\n entries[hash] = {\n text: entry.sourceText,\n context: entry.context || {},\n };\n }\n }\n\n return entries;\n }\n\n /**\n * Pick only requested translations from the full set\n */\n // TODO (AleksandrSl 14/12/2025): SHould I use this in the build somehow?\n private pickTranslations(\n allTranslations: Record<string, string>,\n requestedHashes: string[],\n ): Record<string, string> {\n const result: Record<string, string> = {};\n\n for (const hash of requestedHashes) {\n if (allTranslations[hash]) {\n result[hash] = allT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