@weglot/translate-react 0.0.0-stage → 0.1.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 +190 -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 +207 -0
- package/build/plugin/build-translator.mjs +205 -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 +226 -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 +228 -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 +142 -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 +139 -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 +137 -0
- package/build/translators/translation-service.mjs +138 -0
- package/build/translators/translation-service.mjs.map +1 -0
- package/build/translators/weglot/api-client.cjs +79 -0
- package/build/translators/weglot/api-client.mjs +79 -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 +46 -0
- package/build/translators/weglot/engine.mjs +43 -0
- package/build/translators/weglot/engine.mjs.map +1 -0
- package/build/translators/weglot/translator.cjs +61 -0
- package/build/translators/weglot/translator.mjs +62 -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 +143 -0
- package/build/types.d.cts.map +1 -0
- package/build/types.d.mts +143 -0
- package/build/types.d.mts.map +1 -0
- package/build/utils/config-factory.cjs +86 -0
- package/build/utils/config-factory.mjs +83 -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 +56 -0
- package/build/virtual/code-generator.mjs +55 -0
- package/build/virtual/code-generator.mjs.map +1 -0
- package/build/virtual/config.cjs +16 -0
- package/build/virtual/config.d.cts +13 -0
- package/build/virtual/config.d.cts.map +1 -0
- package/build/virtual/config.d.mts +13 -0
- package/build/virtual/config.d.mts.map +1 -0
- package/build/virtual/config.mjs +12 -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,79 @@
|
|
|
1
|
+
import { DEFAULT_TIMEOUTS, withTimeout } from "../../utils/timeout.mjs";
|
|
2
|
+
import { WORD_TYPE } from "./definitions/definitions.generated.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/translators/weglot/api-client.ts
|
|
5
|
+
/**
|
|
6
|
+
* Thin HTTP client for the Weglot public API.
|
|
7
|
+
*
|
|
8
|
+
* - Translation: POST https://api.weglot.com/translate?api_key=<key>
|
|
9
|
+
* - Project settings: cdn.weglot.com/projects-settings/<id>.json for v1 keys,
|
|
10
|
+
* api.weglot.com/project-settings otherwise (weglot-js getCdnSettings.ts).
|
|
11
|
+
*
|
|
12
|
+
* Translations made through the API are recorded in the Weglot project and
|
|
13
|
+
* can be reviewed/edited in the Weglot dashboard.
|
|
14
|
+
*/
|
|
15
|
+
const TRANSLATE_URL = "https://api.weglot.com/translate";
|
|
16
|
+
const CDN_SETTINGS_URL = "https://cdn.weglot.com/projects-settings";
|
|
17
|
+
const API_SETTINGS_URL = "https://api.weglot.com/project-settings";
|
|
18
|
+
const V1_KEY_PREFIX = "wg_";
|
|
19
|
+
const WORD_TYPE_TEXT = WORD_TYPE.TEXT;
|
|
20
|
+
const REQUEST_URL = "https://compiler.weglot.com/";
|
|
21
|
+
function settingsUrlFor(apiKey) {
|
|
22
|
+
if (apiKey.startsWith(V1_KEY_PREFIX)) return `${CDN_SETTINGS_URL}/${apiKey.slice(3)}.json`;
|
|
23
|
+
return `${API_SETTINGS_URL}?api_key=${apiKey}`;
|
|
24
|
+
}
|
|
25
|
+
/** The API validates the pair independently of the project's languages, so
|
|
26
|
+
* `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */
|
|
27
|
+
var UnsupportedLanguagePairError = class extends Error {
|
|
28
|
+
constructor(from, to) {
|
|
29
|
+
super(`The Weglot API does not translate "${from}" to "${to}".`);
|
|
30
|
+
this.from = from;
|
|
31
|
+
this.to = to;
|
|
32
|
+
this.name = "UnsupportedLanguagePairError";
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
var WeglotApiClient = class {
|
|
36
|
+
constructor(apiKey) {
|
|
37
|
+
this.apiKey = apiKey;
|
|
38
|
+
}
|
|
39
|
+
async translate(params) {
|
|
40
|
+
const response = await fetch(`${TRANSLATE_URL}?api_key=${this.apiKey}`, {
|
|
41
|
+
method: "POST",
|
|
42
|
+
headers: { "Content-Type": "application/json" },
|
|
43
|
+
body: JSON.stringify({
|
|
44
|
+
l_from: params.from,
|
|
45
|
+
l_to: params.to,
|
|
46
|
+
request_url: REQUEST_URL,
|
|
47
|
+
words: params.words.map((w, index) => ({
|
|
48
|
+
t: params.types?.[index] ?? WORD_TYPE_TEXT,
|
|
49
|
+
w
|
|
50
|
+
}))
|
|
51
|
+
})
|
|
52
|
+
});
|
|
53
|
+
if (!response.ok) {
|
|
54
|
+
const body = await response.text().catch(() => "");
|
|
55
|
+
if (response.status === 400 && /not valid languages pair/i.test(body)) throw new UnsupportedLanguagePairError(params.from, params.to);
|
|
56
|
+
throw new Error(`Weglot translate API error (${response.status}): ${body || "no response body"}`);
|
|
57
|
+
}
|
|
58
|
+
const toWords = (await response.json()).to_words;
|
|
59
|
+
if (!Array.isArray(toWords) || toWords.length !== params.words.length) throw new Error(`Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : "none"})`);
|
|
60
|
+
return toWords;
|
|
61
|
+
}
|
|
62
|
+
async fetchSettings() {
|
|
63
|
+
const response = await withTimeout(fetch(settingsUrlFor(this.apiKey)), DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
|
|
64
|
+
if (!response.ok) throw new Error(`Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`);
|
|
65
|
+
const data = await response.json();
|
|
66
|
+
if (!data.language_from || !Array.isArray(data.languages)) throw new Error("Unexpected Weglot project settings format: missing language_from or languages.");
|
|
67
|
+
const languages = data.languages.filter((lang) => lang.enabled !== false);
|
|
68
|
+
return {
|
|
69
|
+
sourceLocale: data.language_from,
|
|
70
|
+
targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),
|
|
71
|
+
translationEngine: data.translation_engine,
|
|
72
|
+
apiLocales: Object.fromEntries(languages.map((lang) => [lang.custom_code || lang.language_to, lang.language_to]))
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
//#endregion
|
|
78
|
+
export { UnsupportedLanguagePairError, WeglotApiClient };
|
|
79
|
+
//# sourceMappingURL=api-client.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-client.mjs","names":["from: string","to: string","apiKey: string"],"sources":["../../../src/translators/weglot/api-client.ts"],"sourcesContent":["/**\n * Thin HTTP client for the Weglot public API.\n *\n * - Translation: POST https://api.weglot.com/translate?api_key=<key>\n * - Project settings: cdn.weglot.com/projects-settings/<id>.json for v1 keys,\n * api.weglot.com/project-settings otherwise (weglot-js getCdnSettings.ts).\n *\n * Translations made through the API are recorded in the Weglot project and\n * can be reviewed/edited in the Weglot dashboard.\n */\n\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport { WORD_TYPE } from \"./definitions/definitions.generated\";\n\nconst TRANSLATE_URL = \"https://api.weglot.com/translate\";\nconst CDN_SETTINGS_URL = \"https://cdn.weglot.com/projects-settings\";\nconst API_SETTINGS_URL = \"https://api.weglot.com/project-settings\";\n// v1 keys are the project id behind a \"wg_\" prefix; the CDN is keyed by the id.\nconst V1_KEY_PREFIX = \"wg_\";\n// Body text; other types identify attributes (VALUE, IMG_ALT) and would misfile it.\nconst WORD_TYPE_TEXT = WORD_TYPE.TEXT;\n// The API requires a request_url identifying the caller.\nconst REQUEST_URL = \"https://compiler.weglot.com/\";\n\nexport type WeglotProjectSettings = {\n sourceLocale: string;\n targetLocales: string[];\n /** Public locale to the code the translate API expects: `a0` is served as `br`,\n * and only `a0` is a valid pair. */\n apiLocales: Record<string, string>;\n /** Inline elements allowed in a segment; absent on older projects, then derived\n * from the key length. */\n translationEngine?: number;\n};\n\nexport function settingsUrlFor(apiKey: string): string {\n if (apiKey.startsWith(V1_KEY_PREFIX)) {\n return `${CDN_SETTINGS_URL}/${apiKey.slice(V1_KEY_PREFIX.length)}.json`;\n }\n return `${API_SETTINGS_URL}?api_key=${apiKey}`;\n}\n\n/** The API validates the pair independently of the project's languages, so\n * `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */\nexport class UnsupportedLanguagePairError extends Error {\n constructor(\n readonly from: string,\n readonly to: string,\n ) {\n super(`The Weglot API does not translate \"${from}\" to \"${to}\".`);\n this.name = \"UnsupportedLanguagePairError\";\n }\n}\n\nexport class WeglotApiClient {\n constructor(private readonly apiKey: string) {}\n\n async translate(params: {\n from: string;\n to: string;\n words: string[];\n /** Word type per word; body text when omitted. */\n types?: number[];\n }): Promise<string[]> {\n const response = await fetch(\n `${TRANSLATE_URL}?api_key=${this.apiKey}`,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n l_from: params.from,\n l_to: params.to,\n request_url: REQUEST_URL,\n words: params.words.map((w, index) => ({\n t: params.types?.[index] ?? WORD_TYPE_TEXT,\n w,\n })),\n }),\n },\n );\n\n if (!response.ok) {\n const body = await response.text().catch(() => \"\");\n if (response.status === 400 && /not valid languages pair/i.test(body)) {\n throw new UnsupportedLanguagePairError(params.from, params.to);\n }\n throw new Error(\n `Weglot translate API error (${response.status}): ${body || \"no response body\"}`,\n );\n }\n\n const data = (await response.json()) as { to_words?: string[] };\n const toWords = data.to_words;\n if (!Array.isArray(toWords) || toWords.length !== params.words.length) {\n throw new Error(\n `Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : \"none\"})`,\n );\n }\n return toWords;\n }\n\n async fetchSettings(): Promise<WeglotProjectSettings> {\n const response = await withTimeout(\n fetch(settingsUrlFor(this.apiKey)),\n DEFAULT_TIMEOUTS.AI_API,\n \"Weglot project settings fetch\",\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`,\n );\n }\n\n const data = (await response.json()) as {\n language_from?: string;\n languages?: {\n language_to: string;\n custom_code?: string | null;\n enabled?: boolean;\n }[];\n translation_engine?: number;\n };\n\n if (!data.language_from || !Array.isArray(data.languages)) {\n throw new Error(\n \"Unexpected Weglot project settings format: missing language_from or languages.\",\n );\n }\n\n // Disabled languages are not public, so they are not built.\n const languages = data.languages.filter((lang) => lang.enabled !== false);\n\n return {\n sourceLocale: data.language_from,\n targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),\n translationEngine: data.translation_engine,\n apiLocales: Object.fromEntries(\n languages.map((lang) => [\n lang.custom_code || lang.language_to,\n lang.language_to,\n ]),\n ),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAM,gBAAgB;AACtB,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AAEzB,MAAM,gBAAgB;AAEtB,MAAM,iBAAiB,UAAU;AAEjC,MAAM,cAAc;AAapB,SAAgB,eAAe,QAAwB;AACrD,KAAI,OAAO,WAAW,cAAc,CAClC,QAAO,GAAG,iBAAiB,GAAG,OAAO,MAAM,EAAqB,CAAC;AAEnE,QAAO,GAAG,iBAAiB,WAAW;;;;AAKxC,IAAa,+BAAb,cAAkD,MAAM;CACtD,YACE,AAASA,MACT,AAASC,IACT;AACA,QAAM,sCAAsC,KAAK,QAAQ,GAAG,IAAI;EAHvD;EACA;AAGT,OAAK,OAAO;;;AAIhB,IAAa,kBAAb,MAA6B;CAC3B,YAAY,AAAiBC,QAAgB;EAAhB;;CAE7B,MAAM,UAAU,QAMM;EACpB,MAAM,WAAW,MAAM,MACrB,GAAG,cAAc,WAAW,KAAK,UACjC;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAC/C,MAAM,KAAK,UAAU;IACnB,QAAQ,OAAO;IACf,MAAM,OAAO;IACb,aAAa;IACb,OAAO,OAAO,MAAM,KAAK,GAAG,WAAW;KACrC,GAAG,OAAO,QAAQ,UAAU;KAC5B;KACD,EAAE;IACJ,CAAC;GACH,CACF;AAED,MAAI,CAAC,SAAS,IAAI;GAChB,MAAM,OAAO,MAAM,SAAS,MAAM,CAAC,YAAY,GAAG;AAClD,OAAI,SAAS,WAAW,OAAO,4BAA4B,KAAK,KAAK,CACnE,OAAM,IAAI,6BAA6B,OAAO,MAAM,OAAO,GAAG;AAEhE,SAAM,IAAI,MACR,+BAA+B,SAAS,OAAO,KAAK,QAAQ,qBAC7D;;EAIH,MAAM,WADQ,MAAM,SAAS,MAAM,EACd;AACrB,MAAI,CAAC,MAAM,QAAQ,QAAQ,IAAI,QAAQ,WAAW,OAAO,MAAM,OAC7D,OAAM,IAAI,MACR,+DAA+D,OAAO,MAAM,OAAO,aAAa,MAAM,QAAQ,QAAQ,GAAG,QAAQ,SAAS,OAAO,GAClJ;AAEH,SAAO;;CAGT,MAAM,gBAAgD;EACpD,MAAM,WAAW,MAAM,YACrB,MAAM,eAAe,KAAK,OAAO,CAAC,EAClC,iBAAiB,QACjB,gCACD;AAED,MAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,4CAA4C,SAAS,OAAO,iDAC7D;EAGH,MAAM,OAAQ,MAAM,SAAS,MAAM;AAUnC,MAAI,CAAC,KAAK,iBAAiB,CAAC,MAAM,QAAQ,KAAK,UAAU,CACvD,OAAM,IAAI,MACR,iFACD;EAIH,MAAM,YAAY,KAAK,UAAU,QAAQ,SAAS,KAAK,YAAY,MAAM;AAEzE,SAAO;GACL,cAAc,KAAK;GACnB,eAAe,UAAU,KAAK,SAAS,KAAK,eAAe,KAAK,YAAY;GAC5E,mBAAmB,KAAK;GACxB,YAAY,OAAO,YACjB,UAAU,KAAK,SAAS,CACtB,KAAK,eAAe,KAAK,aACzB,KAAK,YACN,CAAC,CACH;GACF"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/translators/weglot/definitions/definitions.generated.ts
|
|
3
|
+
/** Inline elements merged into the surrounding segment, by engine version. */
|
|
4
|
+
const MERGE_NODES = {
|
|
5
|
+
"v1": [],
|
|
6
|
+
"v2": [
|
|
7
|
+
"ABBR",
|
|
8
|
+
"ACRONYM",
|
|
9
|
+
"B",
|
|
10
|
+
"BDO",
|
|
11
|
+
"BIG",
|
|
12
|
+
"CITE",
|
|
13
|
+
"EM",
|
|
14
|
+
"I",
|
|
15
|
+
"KBD",
|
|
16
|
+
"Q",
|
|
17
|
+
"SMALL",
|
|
18
|
+
"STRONG",
|
|
19
|
+
"SUB",
|
|
20
|
+
"SUP",
|
|
21
|
+
"U"
|
|
22
|
+
],
|
|
23
|
+
"v3": [
|
|
24
|
+
"A",
|
|
25
|
+
"BDI",
|
|
26
|
+
"BR",
|
|
27
|
+
"WBR",
|
|
28
|
+
"DEL",
|
|
29
|
+
"DFN",
|
|
30
|
+
"INS",
|
|
31
|
+
"S",
|
|
32
|
+
"SPAN",
|
|
33
|
+
"MARK"
|
|
34
|
+
]
|
|
35
|
+
};
|
|
36
|
+
/** Weglot word types: what a translatable string is attached to. */
|
|
37
|
+
const WORD_TYPE = {
|
|
38
|
+
"OTHER": 0,
|
|
39
|
+
"TEXT": 1,
|
|
40
|
+
"VALUE": 2,
|
|
41
|
+
"PLACEHOLDER": 3,
|
|
42
|
+
"META_CONTENT": 4,
|
|
43
|
+
"IFRAME_SRC": 5,
|
|
44
|
+
"IMG_SRC": 6,
|
|
45
|
+
"IMG_ALT": 7,
|
|
46
|
+
"PDF_HREF": 8,
|
|
47
|
+
"PAGE_TITLE": 9,
|
|
48
|
+
"EXTERNAL_LINK": 10
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
//#endregion
|
|
52
|
+
exports.MERGE_NODES = MERGE_NODES;
|
|
53
|
+
exports.WORD_TYPE = WORD_TYPE;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
//#region src/translators/weglot/definitions/definitions.generated.ts
|
|
2
|
+
/** Inline elements merged into the surrounding segment, by engine version. */
|
|
3
|
+
const MERGE_NODES = {
|
|
4
|
+
"v1": [],
|
|
5
|
+
"v2": [
|
|
6
|
+
"ABBR",
|
|
7
|
+
"ACRONYM",
|
|
8
|
+
"B",
|
|
9
|
+
"BDO",
|
|
10
|
+
"BIG",
|
|
11
|
+
"CITE",
|
|
12
|
+
"EM",
|
|
13
|
+
"I",
|
|
14
|
+
"KBD",
|
|
15
|
+
"Q",
|
|
16
|
+
"SMALL",
|
|
17
|
+
"STRONG",
|
|
18
|
+
"SUB",
|
|
19
|
+
"SUP",
|
|
20
|
+
"U"
|
|
21
|
+
],
|
|
22
|
+
"v3": [
|
|
23
|
+
"A",
|
|
24
|
+
"BDI",
|
|
25
|
+
"BR",
|
|
26
|
+
"WBR",
|
|
27
|
+
"DEL",
|
|
28
|
+
"DFN",
|
|
29
|
+
"INS",
|
|
30
|
+
"S",
|
|
31
|
+
"SPAN",
|
|
32
|
+
"MARK"
|
|
33
|
+
]
|
|
34
|
+
};
|
|
35
|
+
/** Weglot word types: what a translatable string is attached to. */
|
|
36
|
+
const WORD_TYPE = {
|
|
37
|
+
"OTHER": 0,
|
|
38
|
+
"TEXT": 1,
|
|
39
|
+
"VALUE": 2,
|
|
40
|
+
"PLACEHOLDER": 3,
|
|
41
|
+
"META_CONTENT": 4,
|
|
42
|
+
"IFRAME_SRC": 5,
|
|
43
|
+
"IMG_SRC": 6,
|
|
44
|
+
"IMG_ALT": 7,
|
|
45
|
+
"PDF_HREF": 8,
|
|
46
|
+
"PAGE_TITLE": 9,
|
|
47
|
+
"EXTERNAL_LINK": 10
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
//#endregion
|
|
51
|
+
export { MERGE_NODES, WORD_TYPE };
|
|
52
|
+
//# sourceMappingURL=definitions.generated.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"definitions.generated.mjs","names":["MERGE_NODES: Readonly<Record<string, readonly string[]>>","WORD_TYPE: Readonly<Record<string, number>>"],"sources":["../../../../src/translators/weglot/definitions/definitions.generated.ts"],"sourcesContent":["// Generated by scripts/sync-definitions.ts from weglot/weglot-translation-definitions@79f2a72.\n// Do not edit: run `pnpm sync-definitions` instead.\n\n/** Inline elements merged into the surrounding segment, by engine version. */\nexport const MERGE_NODES: Readonly<Record<string, readonly string[]>> = {\n \"v1\": [],\n \"v2\": [\"ABBR\",\"ACRONYM\",\"B\",\"BDO\",\"BIG\",\"CITE\",\"EM\",\"I\",\"KBD\",\"Q\",\"SMALL\",\"STRONG\",\"SUB\",\"SUP\",\"U\"],\n \"v3\": [\"A\",\"BDI\",\"BR\",\"WBR\",\"DEL\",\"DFN\",\"INS\",\"S\",\"SPAN\",\"MARK\"],\n};\n\n/** Weglot word types: what a translatable string is attached to. */\nexport const WORD_TYPE: Readonly<Record<string, number>> = {\n \"OTHER\": 0,\n \"TEXT\": 1,\n \"VALUE\": 2,\n \"PLACEHOLDER\": 3,\n \"META_CONTENT\": 4,\n \"IFRAME_SRC\": 5,\n \"IMG_SRC\": 6,\n \"IMG_ALT\": 7,\n \"PDF_HREF\": 8,\n \"PAGE_TITLE\": 9,\n \"EXTERNAL_LINK\": 10,\n};\n"],"mappings":";;AAIA,MAAaA,cAA2D;CACtE,MAAM,EAAE;CACR,MAAM;EAAC;EAAO;EAAU;EAAI;EAAM;EAAM;EAAO;EAAK;EAAI;EAAM;EAAI;EAAQ;EAAS;EAAM;EAAM;EAAI;CACnG,MAAM;EAAC;EAAI;EAAM;EAAK;EAAM;EAAM;EAAM;EAAM;EAAI;EAAO;EAAO;CACjE;;AAGD,MAAaC,YAA8C;CACzD,SAAS;CACT,QAAQ;CACR,SAAS;CACT,eAAe;CACf,gBAAgB;CAChB,cAAc;CACd,WAAW;CACX,WAAW;CACX,YAAY;CACZ,cAAc;CACd,iBAAiB;CAClB"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
const require_definitions_generated = require('./definitions/definitions.generated.cjs');
|
|
2
|
+
|
|
3
|
+
//#region src/translators/weglot/engine.ts
|
|
4
|
+
/**
|
|
5
|
+
* The engine version and the inline tags it merges: sending a tag it does not
|
|
6
|
+
* merge gets the segment back untranslated, so the set follows the project.
|
|
7
|
+
*/
|
|
8
|
+
/** Keys shorter than this are v1 projects, as connect-edge and weglot-js also detect. */
|
|
9
|
+
const V1_KEY_LENGTH = 36;
|
|
10
|
+
/** connect-edge's default for a modern key. weglot-js still defaults to 2. */
|
|
11
|
+
const DEFAULT_MODERN_ENGINE = 3;
|
|
12
|
+
const LEGACY_ENGINE = 1;
|
|
13
|
+
/** Fallback tag for a placeholder or unknown element; the name is only a hint,
|
|
14
|
+
* so the first permitted one wins. */
|
|
15
|
+
const FALLBACK_TAG_PREFERENCE = [
|
|
16
|
+
"span",
|
|
17
|
+
"bdi",
|
|
18
|
+
"u",
|
|
19
|
+
"b"
|
|
20
|
+
];
|
|
21
|
+
function resolveTranslationEngine(apiKey, fromSettings) {
|
|
22
|
+
if (typeof fromSettings === "number" && Number.isFinite(fromSettings) && fromSettings > 0) return fromSettings;
|
|
23
|
+
return apiKey.length < V1_KEY_LENGTH ? LEGACY_ENGINE : DEFAULT_MODERN_ENGINE;
|
|
24
|
+
}
|
|
25
|
+
function mergeableTagsFor(engine) {
|
|
26
|
+
const tags = [];
|
|
27
|
+
if (engine >= 2) tags.push(...require_definitions_generated.MERGE_NODES.v2);
|
|
28
|
+
if (engine > 2) tags.push(...require_definitions_generated.MERGE_NODES.v3);
|
|
29
|
+
return new Set(tags.map((tag) => tag.toLowerCase()));
|
|
30
|
+
}
|
|
31
|
+
/** Undefined on engine 1, which merges nothing and so permits no tag at all. */
|
|
32
|
+
function fallbackWireTagFor(tags) {
|
|
33
|
+
return FALLBACK_TAG_PREFERENCE.find((tag) => tags.has(tag));
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Every inline tag any engine merges. Fixed rather than per-project: the hash
|
|
37
|
+
* follows the stored text, so a remote setting would re-hash on every change.
|
|
38
|
+
*/
|
|
39
|
+
const INLINE_TAGS = new Set(Object.values(require_definitions_generated.MERGE_NODES).flat().map((tag) => tag.toLowerCase()));
|
|
40
|
+
|
|
41
|
+
//#endregion
|
|
42
|
+
exports.DEFAULT_MODERN_ENGINE = DEFAULT_MODERN_ENGINE;
|
|
43
|
+
exports.INLINE_TAGS = INLINE_TAGS;
|
|
44
|
+
exports.fallbackWireTagFor = fallbackWireTagFor;
|
|
45
|
+
exports.mergeableTagsFor = mergeableTagsFor;
|
|
46
|
+
exports.resolveTranslationEngine = resolveTranslationEngine;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { MERGE_NODES } from "./definitions/definitions.generated.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/translators/weglot/engine.ts
|
|
4
|
+
/**
|
|
5
|
+
* The engine version and the inline tags it merges: sending a tag it does not
|
|
6
|
+
* merge gets the segment back untranslated, so the set follows the project.
|
|
7
|
+
*/
|
|
8
|
+
/** Keys shorter than this are v1 projects, as connect-edge and weglot-js also detect. */
|
|
9
|
+
const V1_KEY_LENGTH = 36;
|
|
10
|
+
/** connect-edge's default for a modern key. weglot-js still defaults to 2. */
|
|
11
|
+
const DEFAULT_MODERN_ENGINE = 3;
|
|
12
|
+
const LEGACY_ENGINE = 1;
|
|
13
|
+
/** Fallback tag for a placeholder or unknown element; the name is only a hint,
|
|
14
|
+
* so the first permitted one wins. */
|
|
15
|
+
const FALLBACK_TAG_PREFERENCE = [
|
|
16
|
+
"span",
|
|
17
|
+
"bdi",
|
|
18
|
+
"u",
|
|
19
|
+
"b"
|
|
20
|
+
];
|
|
21
|
+
function resolveTranslationEngine(apiKey, fromSettings) {
|
|
22
|
+
if (typeof fromSettings === "number" && Number.isFinite(fromSettings) && fromSettings > 0) return fromSettings;
|
|
23
|
+
return apiKey.length < V1_KEY_LENGTH ? LEGACY_ENGINE : DEFAULT_MODERN_ENGINE;
|
|
24
|
+
}
|
|
25
|
+
function mergeableTagsFor(engine) {
|
|
26
|
+
const tags = [];
|
|
27
|
+
if (engine >= 2) tags.push(...MERGE_NODES.v2);
|
|
28
|
+
if (engine > 2) tags.push(...MERGE_NODES.v3);
|
|
29
|
+
return new Set(tags.map((tag) => tag.toLowerCase()));
|
|
30
|
+
}
|
|
31
|
+
/** Undefined on engine 1, which merges nothing and so permits no tag at all. */
|
|
32
|
+
function fallbackWireTagFor(tags) {
|
|
33
|
+
return FALLBACK_TAG_PREFERENCE.find((tag) => tags.has(tag));
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Every inline tag any engine merges. Fixed rather than per-project: the hash
|
|
37
|
+
* follows the stored text, so a remote setting would re-hash on every change.
|
|
38
|
+
*/
|
|
39
|
+
const INLINE_TAGS = new Set(Object.values(MERGE_NODES).flat().map((tag) => tag.toLowerCase()));
|
|
40
|
+
|
|
41
|
+
//#endregion
|
|
42
|
+
export { DEFAULT_MODERN_ENGINE, INLINE_TAGS, fallbackWireTagFor, mergeableTagsFor, resolveTranslationEngine };
|
|
43
|
+
//# sourceMappingURL=engine.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"engine.mjs","names":["tags: string[]","INLINE_TAGS: ReadonlySet<string>"],"sources":["../../../src/translators/weglot/engine.ts"],"sourcesContent":["/**\n * The engine version and the inline tags it merges: sending a tag it does not\n * merge gets the segment back untranslated, so the set follows the project.\n */\n\nimport { MERGE_NODES } from \"./definitions/definitions.generated\";\n\n/** Keys shorter than this are v1 projects, as connect-edge and weglot-js also detect. */\nexport const V1_KEY_LENGTH = 36;\n\n/** connect-edge's default for a modern key. weglot-js still defaults to 2. */\nexport const DEFAULT_MODERN_ENGINE = 3;\n\nexport const LEGACY_ENGINE = 1;\n\n/** Fallback tag for a placeholder or unknown element; the name is only a hint,\n * so the first permitted one wins. */\nconst FALLBACK_TAG_PREFERENCE = [\"span\", \"bdi\", \"u\", \"b\"];\n\nexport function resolveTranslationEngine(\n apiKey: string,\n fromSettings?: number | null,\n): number {\n if (typeof fromSettings === \"number\" && Number.isFinite(fromSettings) && fromSettings > 0) {\n return fromSettings;\n }\n return apiKey.length < V1_KEY_LENGTH ? LEGACY_ENGINE : DEFAULT_MODERN_ENGINE;\n}\n\nexport function mergeableTagsFor(engine: number): ReadonlySet<string> {\n const tags: string[] = [];\n if (engine >= 2) tags.push(...MERGE_NODES.v2);\n if (engine > 2) tags.push(...MERGE_NODES.v3);\n return new Set(tags.map((tag) => tag.toLowerCase()));\n}\n\n/** Undefined on engine 1, which merges nothing and so permits no tag at all. */\nexport function fallbackWireTagFor(\n tags: ReadonlySet<string>,\n): string | undefined {\n return FALLBACK_TAG_PREFERENCE.find((tag) => tags.has(tag));\n}\n\n/**\n * Every inline tag any engine merges. Fixed rather than per-project: the hash\n * follows the stored text, so a remote setting would re-hash on every change.\n */\nexport const INLINE_TAGS: ReadonlySet<string> = new Set(\n Object.values(MERGE_NODES)\n .flat()\n .map((tag) => tag.toLowerCase()),\n);\n"],"mappings":";;;;;;;;AAQA,MAAa,gBAAgB;;AAG7B,MAAa,wBAAwB;AAErC,MAAa,gBAAgB;;;AAI7B,MAAM,0BAA0B;CAAC;CAAQ;CAAO;CAAK;CAAI;AAEzD,SAAgB,yBACd,QACA,cACQ;AACR,KAAI,OAAO,iBAAiB,YAAY,OAAO,SAAS,aAAa,IAAI,eAAe,EACtF,QAAO;AAET,QAAO,OAAO,SAAS,gBAAgB,gBAAgB;;AAGzD,SAAgB,iBAAiB,QAAqC;CACpE,MAAMA,OAAiB,EAAE;AACzB,KAAI,UAAU,EAAG,MAAK,KAAK,GAAG,YAAY,GAAG;AAC7C,KAAI,SAAS,EAAG,MAAK,KAAK,GAAG,YAAY,GAAG;AAC5C,QAAO,IAAI,IAAI,KAAK,KAAK,QAAQ,IAAI,aAAa,CAAC,CAAC;;;AAItD,SAAgB,mBACd,MACoB;AACpB,QAAO,wBAAwB,MAAM,QAAQ,KAAK,IAAI,IAAI,CAAC;;;;;;AAO7D,MAAaC,cAAmC,IAAI,IAClD,OAAO,OAAO,YAAY,CACvB,MAAM,CACN,KAAK,QAAQ,IAAI,aAAa,CAAC,CACnC"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
const require_timeout = require('../../utils/timeout.cjs');
|
|
2
|
+
const require_api_client = require('./api-client.cjs');
|
|
3
|
+
const require_engine = require('./engine.cjs');
|
|
4
|
+
const require_wire_format = require('./wire-format.cjs');
|
|
5
|
+
|
|
6
|
+
//#region src/translators/weglot/translator.ts
|
|
7
|
+
const MAX_WORDS_PER_REQUEST = 100;
|
|
8
|
+
var WeglotTranslator = class {
|
|
9
|
+
client;
|
|
10
|
+
engine;
|
|
11
|
+
constructor(config, logger, client) {
|
|
12
|
+
this.config = config;
|
|
13
|
+
this.logger = logger;
|
|
14
|
+
this.client = client ?? new require_api_client.WeglotApiClient(config.apiKey);
|
|
15
|
+
this.engine = require_engine.resolveTranslationEngine(config.apiKey, config.translationEngine);
|
|
16
|
+
}
|
|
17
|
+
async translate(locale, entriesMap) {
|
|
18
|
+
const hashes = Object.keys(entriesMap);
|
|
19
|
+
this.logger.debug(`Weglot translate() called for ${locale} with ${hashes.length} entries`);
|
|
20
|
+
const translations = {};
|
|
21
|
+
const protectedEntries = [];
|
|
22
|
+
for (const hash of hashes) {
|
|
23
|
+
const sourceText = entriesMap[hash].text;
|
|
24
|
+
const { wire, restore, encodable } = require_wire_format.encodeForApi(sourceText, this.engine);
|
|
25
|
+
if (!encodable) {
|
|
26
|
+
this.logger.warn(`Weglot translation engine ${this.engine} cannot carry the markup in hash "${hash}"; falling back to source text.`);
|
|
27
|
+
translations[hash] = sourceText;
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
protectedEntries.push({
|
|
31
|
+
hash,
|
|
32
|
+
text: wire,
|
|
33
|
+
restore
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
for (let i = 0; i < protectedEntries.length; i += MAX_WORDS_PER_REQUEST) {
|
|
37
|
+
const chunk = protectedEntries.slice(i, i + MAX_WORDS_PER_REQUEST);
|
|
38
|
+
this.logger.debug(`Translating chunk ${i / MAX_WORDS_PER_REQUEST + 1} (${chunk.length} words) to ${locale}`);
|
|
39
|
+
const translated = await require_timeout.withTimeout(this.client.translate({
|
|
40
|
+
from: this.config.sourceLocale,
|
|
41
|
+
to: this.config.apiLocales?.[locale] ?? locale,
|
|
42
|
+
words: chunk.map((entry) => entry.text)
|
|
43
|
+
}), require_timeout.DEFAULT_TIMEOUTS.AI_API, `Weglot API translation to ${locale}`);
|
|
44
|
+
chunk.forEach((entry, index) => {
|
|
45
|
+
const sourceText = entriesMap[entry.hash].text;
|
|
46
|
+
const { text: restored, damaged } = entry.restore(translated[index]);
|
|
47
|
+
if (damaged) {
|
|
48
|
+
this.logger.warn(`Weglot translation for hash "${entry.hash}" (locale "${locale}") lost an interpolation or element during restore; falling back to source text.`);
|
|
49
|
+
translations[entry.hash] = sourceText;
|
|
50
|
+
} else if (translated[index] === entry.text && entry.text !== sourceText) {
|
|
51
|
+
this.logger.warn(`Weglot API returned hash "${entry.hash}" (locale "${locale}") untranslated; falling back to source text.`);
|
|
52
|
+
translations[entry.hash] = sourceText;
|
|
53
|
+
} else translations[entry.hash] = restored;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
return translations;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
//#endregion
|
|
61
|
+
exports.WeglotTranslator = WeglotTranslator;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { DEFAULT_TIMEOUTS, withTimeout } from "../../utils/timeout.mjs";
|
|
2
|
+
import { WeglotApiClient } from "./api-client.mjs";
|
|
3
|
+
import { resolveTranslationEngine } from "./engine.mjs";
|
|
4
|
+
import { encodeForApi } from "./wire-format.mjs";
|
|
5
|
+
|
|
6
|
+
//#region src/translators/weglot/translator.ts
|
|
7
|
+
const MAX_WORDS_PER_REQUEST = 100;
|
|
8
|
+
var WeglotTranslator = class {
|
|
9
|
+
client;
|
|
10
|
+
engine;
|
|
11
|
+
constructor(config, logger, client) {
|
|
12
|
+
this.config = config;
|
|
13
|
+
this.logger = logger;
|
|
14
|
+
this.client = client ?? new WeglotApiClient(config.apiKey);
|
|
15
|
+
this.engine = resolveTranslationEngine(config.apiKey, config.translationEngine);
|
|
16
|
+
}
|
|
17
|
+
async translate(locale, entriesMap) {
|
|
18
|
+
const hashes = Object.keys(entriesMap);
|
|
19
|
+
this.logger.debug(`Weglot translate() called for ${locale} with ${hashes.length} entries`);
|
|
20
|
+
const translations = {};
|
|
21
|
+
const protectedEntries = [];
|
|
22
|
+
for (const hash of hashes) {
|
|
23
|
+
const sourceText = entriesMap[hash].text;
|
|
24
|
+
const { wire, restore, encodable } = encodeForApi(sourceText, this.engine);
|
|
25
|
+
if (!encodable) {
|
|
26
|
+
this.logger.warn(`Weglot translation engine ${this.engine} cannot carry the markup in hash "${hash}"; falling back to source text.`);
|
|
27
|
+
translations[hash] = sourceText;
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
protectedEntries.push({
|
|
31
|
+
hash,
|
|
32
|
+
text: wire,
|
|
33
|
+
restore
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
for (let i = 0; i < protectedEntries.length; i += MAX_WORDS_PER_REQUEST) {
|
|
37
|
+
const chunk = protectedEntries.slice(i, i + MAX_WORDS_PER_REQUEST);
|
|
38
|
+
this.logger.debug(`Translating chunk ${i / MAX_WORDS_PER_REQUEST + 1} (${chunk.length} words) to ${locale}`);
|
|
39
|
+
const translated = await withTimeout(this.client.translate({
|
|
40
|
+
from: this.config.sourceLocale,
|
|
41
|
+
to: this.config.apiLocales?.[locale] ?? locale,
|
|
42
|
+
words: chunk.map((entry) => entry.text)
|
|
43
|
+
}), DEFAULT_TIMEOUTS.AI_API, `Weglot API translation to ${locale}`);
|
|
44
|
+
chunk.forEach((entry, index) => {
|
|
45
|
+
const sourceText = entriesMap[entry.hash].text;
|
|
46
|
+
const { text: restored, damaged } = entry.restore(translated[index]);
|
|
47
|
+
if (damaged) {
|
|
48
|
+
this.logger.warn(`Weglot translation for hash "${entry.hash}" (locale "${locale}") lost an interpolation or element during restore; falling back to source text.`);
|
|
49
|
+
translations[entry.hash] = sourceText;
|
|
50
|
+
} else if (translated[index] === entry.text && entry.text !== sourceText) {
|
|
51
|
+
this.logger.warn(`Weglot API returned hash "${entry.hash}" (locale "${locale}") untranslated; falling back to source text.`);
|
|
52
|
+
translations[entry.hash] = sourceText;
|
|
53
|
+
} else translations[entry.hash] = restored;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
return translations;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
//#endregion
|
|
61
|
+
export { WeglotTranslator };
|
|
62
|
+
//# sourceMappingURL=translator.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"translator.mjs","names":["config: WeglotTranslatorConfig","logger: Logger","translations: Record<string, string>","protectedEntries: {\n hash: string;\n text: string;\n restore: (translated: string) => RestoredTranslation;\n }[]"],"sources":["../../../src/translators/weglot/translator.ts"],"sourcesContent":["import type { LocaleCode } from \"../../locale\";\nimport type { TranslatableEntry, Translator } from \"../api\";\nimport type { Logger } from \"../../utils/logger\";\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport { WeglotApiClient } from \"./api-client\";\nimport { encodeForApi, type RestoredTranslation } from \"./wire-format\";\nimport { resolveTranslationEngine } from \"./engine\";\n\nconst MAX_WORDS_PER_REQUEST = 100;\n\nexport interface WeglotTranslatorConfig {\n apiKey: string;\n sourceLocale: LocaleCode;\n /** Public locale to the language code the translate API expects. */\n apiLocales?: Record<string, LocaleCode>;\n /** From the project settings; derived from the key length when absent. */\n translationEngine?: number;\n}\n\nexport class WeglotTranslator implements Translator<WeglotTranslatorConfig> {\n private readonly client: WeglotApiClient;\n private readonly engine: number;\n\n constructor(\n readonly config: WeglotTranslatorConfig,\n private readonly logger: Logger,\n client?: WeglotApiClient,\n ) {\n this.client = client ?? new WeglotApiClient(config.apiKey);\n this.engine = resolveTranslationEngine(\n config.apiKey,\n config.translationEngine,\n );\n }\n\n async translate(\n locale: LocaleCode,\n entriesMap: Record<string, TranslatableEntry>,\n ): Promise<Record<string, string>> {\n const hashes = Object.keys(entriesMap);\n this.logger.debug(\n `Weglot translate() called for ${locale} with ${hashes.length} entries`,\n );\n\n const translations: Record<string, string> = {};\n const protectedEntries: {\n hash: string;\n text: string;\n restore: (translated: string) => RestoredTranslation;\n }[] = [];\n\n for (const hash of hashes) {\n const sourceText = entriesMap[hash].text;\n const { wire, restore, encodable } = encodeForApi(sourceText, this.engine);\n if (!encodable) {\n // Engine 1 merges nothing, so markup cannot survive the wire form.\n this.logger.warn(\n `Weglot translation engine ${this.engine} cannot carry the markup in hash \"${hash}\"; falling back to source text.`,\n );\n translations[hash] = sourceText;\n continue;\n }\n protectedEntries.push({ hash, text: wire, restore });\n }\n\n for (let i = 0; i < protectedEntries.length; i += MAX_WORDS_PER_REQUEST) {\n const chunk = protectedEntries.slice(i, i + MAX_WORDS_PER_REQUEST);\n this.logger.debug(\n `Translating chunk ${i / MAX_WORDS_PER_REQUEST + 1} (${chunk.length} words) to ${locale}`,\n );\n\n const translated = await withTimeout(\n this.client.translate({\n from: this.config.sourceLocale,\n to: this.config.apiLocales?.[locale] ?? locale,\n words: chunk.map((entry) => entry.text),\n }),\n DEFAULT_TIMEOUTS.AI_API,\n `Weglot API translation to ${locale}`,\n );\n\n chunk.forEach((entry, index) => {\n const sourceText = entriesMap[entry.hash].text;\n const { text: restored, damaged } = entry.restore(translated[index]);\n\n if (damaged) {\n this.logger.warn(\n `Weglot translation for hash \"${entry.hash}\" (locale \"${locale}\") lost an interpolation or element during restore; falling back to source text.`,\n );\n translations[entry.hash] = sourceText;\n } else if (translated[index] === entry.text && entry.text !== sourceText) {\n // The API echoes a segment back verbatim when it rejects its markup.\n this.logger.warn(\n `Weglot API returned hash \"${entry.hash}\" (locale \"${locale}\") untranslated; falling back to source text.`,\n );\n translations[entry.hash] = sourceText;\n } else {\n translations[entry.hash] = restored;\n }\n });\n }\n\n return translations;\n }\n}\n"],"mappings":";;;;;;AAQA,MAAM,wBAAwB;AAW9B,IAAa,mBAAb,MAA4E;CAC1E,AAAiB;CACjB,AAAiB;CAEjB,YACE,AAASA,QACT,AAAiBC,QACjB,QACA;EAHS;EACQ;AAGjB,OAAK,SAAS,UAAU,IAAI,gBAAgB,OAAO,OAAO;AAC1D,OAAK,SAAS,yBACZ,OAAO,QACP,OAAO,kBACR;;CAGH,MAAM,UACJ,QACA,YACiC;EACjC,MAAM,SAAS,OAAO,KAAK,WAAW;AACtC,OAAK,OAAO,MACV,iCAAiC,OAAO,QAAQ,OAAO,OAAO,UAC/D;EAED,MAAMC,eAAuC,EAAE;EAC/C,MAAMC,mBAIA,EAAE;AAER,OAAK,MAAM,QAAQ,QAAQ;GACzB,MAAM,aAAa,WAAW,MAAM;GACpC,MAAM,EAAE,MAAM,SAAS,cAAc,aAAa,YAAY,KAAK,OAAO;AAC1E,OAAI,CAAC,WAAW;AAEd,SAAK,OAAO,KACV,6BAA6B,KAAK,OAAO,oCAAoC,KAAK,iCACnF;AACD,iBAAa,QAAQ;AACrB;;AAEF,oBAAiB,KAAK;IAAE;IAAM,MAAM;IAAM;IAAS,CAAC;;AAGtD,OAAK,IAAI,IAAI,GAAG,IAAI,iBAAiB,QAAQ,KAAK,uBAAuB;GACvE,MAAM,QAAQ,iBAAiB,MAAM,GAAG,IAAI,sBAAsB;AAClE,QAAK,OAAO,MACV,qBAAqB,IAAI,wBAAwB,EAAE,IAAI,MAAM,OAAO,aAAa,SAClF;GAED,MAAM,aAAa,MAAM,YACvB,KAAK,OAAO,UAAU;IACpB,MAAM,KAAK,OAAO;IAClB,IAAI,KAAK,OAAO,aAAa,WAAW;IACxC,OAAO,MAAM,KAAK,UAAU,MAAM,KAAK;IACxC,CAAC,EACF,iBAAiB,QACjB,6BAA6B,SAC9B;AAED,SAAM,SAAS,OAAO,UAAU;IAC9B,MAAM,aAAa,WAAW,MAAM,MAAM;IAC1C,MAAM,EAAE,MAAM,UAAU,YAAY,MAAM,QAAQ,WAAW,OAAO;AAEpE,QAAI,SAAS;AACX,UAAK,OAAO,KACV,gCAAgC,MAAM,KAAK,aAAa,OAAO,kFAChE;AACD,kBAAa,MAAM,QAAQ;eAClB,WAAW,WAAW,MAAM,QAAQ,MAAM,SAAS,YAAY;AAExE,UAAK,OAAO,KACV,6BAA6B,MAAM,KAAK,aAAa,OAAO,+CAC7D;AACD,kBAAa,MAAM,QAAQ;UAE3B,cAAa,MAAM,QAAQ;KAE7B;;AAGJ,SAAO"}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
const require_engine = require('./engine.cjs');
|
|
2
|
+
|
|
3
|
+
//#region src/translators/weglot/wire-format.ts
|
|
4
|
+
/**
|
|
5
|
+
* Converts the stored ICU form to the wire form the API accepts and back:
|
|
6
|
+
* `Read <strong0>this</strong0>` ↔ `Read <strong wg-1="">this</strong>`.
|
|
7
|
+
*/
|
|
8
|
+
const STORED_TOKEN = /\{[^{}]+\}|<([A-Za-z][A-Za-z0-9]*)\s*>|<\/([A-Za-z][A-Za-z0-9]*)\s*>/g;
|
|
9
|
+
const WIRE_TOKEN = /<([A-Za-z][A-Za-z0-9]*)\s+wg-(\d+)(?:="")?\s*>|<\/([A-Za-z][A-Za-z0-9]*)\s*>/g;
|
|
10
|
+
const TAG_SHAPED = /<\/?([A-Za-z][A-Za-z0-9]*)(\s[^<>]*?)?\s*\/?>/g;
|
|
11
|
+
const ICU_QUOTE_BEFORE_SYNTAX = /(?<!')'(?=[{}<])/g;
|
|
12
|
+
const VOID_TAGS = new Set([
|
|
13
|
+
"area",
|
|
14
|
+
"base",
|
|
15
|
+
"br",
|
|
16
|
+
"col",
|
|
17
|
+
"embed",
|
|
18
|
+
"hr",
|
|
19
|
+
"img",
|
|
20
|
+
"input",
|
|
21
|
+
"link",
|
|
22
|
+
"meta",
|
|
23
|
+
"source",
|
|
24
|
+
"track",
|
|
25
|
+
"wbr"
|
|
26
|
+
]);
|
|
27
|
+
function wireTagFor(icuName, tags, fallbackTag) {
|
|
28
|
+
const base = icuName.replace(/\d+$/, "");
|
|
29
|
+
if (VOID_TAGS.has(base)) return fallbackTag;
|
|
30
|
+
return tags.has(base) ? base : fallbackTag;
|
|
31
|
+
}
|
|
32
|
+
function encodeForApi(text, engine = require_engine.DEFAULT_MODERN_ENGINE) {
|
|
33
|
+
const tags = require_engine.mergeableTagsFor(engine);
|
|
34
|
+
const fallbackTag = require_engine.fallbackWireTagFor(tags);
|
|
35
|
+
const slots = [];
|
|
36
|
+
const openSlots = [];
|
|
37
|
+
let wire = "";
|
|
38
|
+
let cursor = 0;
|
|
39
|
+
if (fallbackTag === void 0) {
|
|
40
|
+
const carriesMarkup = STORED_TOKEN.test(text);
|
|
41
|
+
STORED_TOKEN.lastIndex = 0;
|
|
42
|
+
return {
|
|
43
|
+
wire: text,
|
|
44
|
+
restore: (translated) => ({
|
|
45
|
+
text: translated,
|
|
46
|
+
damaged: false
|
|
47
|
+
}),
|
|
48
|
+
encodable: !carriesMarkup
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
for (const match of text.matchAll(STORED_TOKEN)) {
|
|
52
|
+
wire += text.slice(cursor, match.index);
|
|
53
|
+
cursor = match.index + match[0].length;
|
|
54
|
+
const [token, openName, closeName] = match;
|
|
55
|
+
if (openName !== void 0) {
|
|
56
|
+
const slot = {
|
|
57
|
+
kind: "tag",
|
|
58
|
+
icuName: openName,
|
|
59
|
+
wireName: wireTagFor(openName, tags, fallbackTag)
|
|
60
|
+
};
|
|
61
|
+
openSlots.push(slots.push(slot) - 1);
|
|
62
|
+
wire += `<${slot.wireName} wg-${slots.length}="">`;
|
|
63
|
+
} else if (closeName !== void 0) {
|
|
64
|
+
const index = openSlots.pop();
|
|
65
|
+
const slot = index === void 0 ? void 0 : slots[index];
|
|
66
|
+
if (slot?.kind === "tag") wire += `</${slot.wireName}>`;
|
|
67
|
+
} else {
|
|
68
|
+
slots.push({
|
|
69
|
+
kind: "placeholder",
|
|
70
|
+
value: token
|
|
71
|
+
});
|
|
72
|
+
wire += `<${fallbackTag} wg-${slots.length}=""></${fallbackTag}>`;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
wire += text.slice(cursor);
|
|
76
|
+
return {
|
|
77
|
+
wire,
|
|
78
|
+
restore: (translated) => restore(translated, slots),
|
|
79
|
+
encodable: true
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function restore(translated, slots) {
|
|
83
|
+
const stack = [];
|
|
84
|
+
const seen = /* @__PURE__ */ new Set();
|
|
85
|
+
let text = "";
|
|
86
|
+
let cursor = 0;
|
|
87
|
+
let suppressed = 0;
|
|
88
|
+
for (const match of translated.matchAll(WIRE_TOKEN)) {
|
|
89
|
+
if (!suppressed) text += translated.slice(cursor, match.index);
|
|
90
|
+
cursor = match.index + match[0].length;
|
|
91
|
+
const [, , markerIndex, closeName] = match;
|
|
92
|
+
if (markerIndex !== void 0) {
|
|
93
|
+
const index = Number(markerIndex) - 1;
|
|
94
|
+
const slot = slots[index];
|
|
95
|
+
if (!slot) {
|
|
96
|
+
stack.push(void 0);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
seen.add(index);
|
|
100
|
+
stack.push(slot);
|
|
101
|
+
if (slot.kind === "placeholder") {
|
|
102
|
+
if (!suppressed) text += slot.value;
|
|
103
|
+
suppressed++;
|
|
104
|
+
} else if (!suppressed) text += `<${slot.icuName}>`;
|
|
105
|
+
} else if (closeName !== void 0) {
|
|
106
|
+
const slot = stack.pop();
|
|
107
|
+
if (!slot) continue;
|
|
108
|
+
if (slot.kind === "placeholder") suppressed--;
|
|
109
|
+
else if (!suppressed) text += `</${slot.icuName}>`;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (!suppressed) text += translated.slice(cursor);
|
|
113
|
+
text = text.replace(ICU_QUOTE_BEFORE_SYNTAX, "''");
|
|
114
|
+
const lostSlot = slots.some((_, index) => !seen.has(index));
|
|
115
|
+
return {
|
|
116
|
+
text,
|
|
117
|
+
damaged: lostSlot || hasStrayMarkup(text, slots)
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** Invented markup or a leftover marker would reach intl-messageformat as an
|
|
121
|
+
* unknown tag and throw at render time. */
|
|
122
|
+
function hasStrayMarkup(text, slots) {
|
|
123
|
+
const known = new Set(slots.flatMap((slot) => slot.kind === "tag" ? [slot.icuName] : []));
|
|
124
|
+
return [...text.matchAll(TAG_SHAPED)].some(([, name, attributes]) => !known.has(name) || attributes !== void 0);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
//#endregion
|
|
128
|
+
exports.encodeForApi = encodeForApi;
|