@weglot/translate-react 0.2.2 → 0.3.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/README.md +96 -9
- package/build/plugin/next.cjs +13 -2
- package/build/plugin/next.d.cts.map +1 -1
- package/build/plugin/next.d.mts.map +1 -1
- package/build/plugin/next.mjs +13 -2
- package/build/plugin/next.mjs.map +1 -1
- package/build/plugin/transform/index.cjs +17 -3
- package/build/plugin/transform/index.mjs +17 -3
- package/build/plugin/transform/index.mjs.map +1 -1
- package/build/plugin/transform/msg.cjs +66 -0
- package/build/plugin/transform/msg.mjs +64 -0
- package/build/plugin/transform/msg.mjs.map +1 -0
- package/build/plugin/transform/process-file.cjs +9 -7
- package/build/plugin/transform/process-file.mjs +9 -7
- package/build/plugin/transform/process-file.mjs.map +1 -1
- package/build/plugin/transform/utils.cjs +1 -0
- package/build/plugin/transform/utils.mjs +1 -1
- package/build/plugin/transform/utils.mjs.map +1 -1
- package/build/plugin/unplugin.cjs +3 -2
- package/build/plugin/unplugin.d.cts.map +1 -1
- package/build/plugin/unplugin.d.mts.map +1 -1
- package/build/plugin/unplugin.mjs +3 -2
- package/build/plugin/unplugin.mjs.map +1 -1
- package/build/react/client/index.cjs +2 -0
- package/build/react/client/index.d.cts +2 -1
- package/build/react/client/index.d.mts +2 -1
- package/build/react/client/index.mjs +2 -1
- package/build/react/client/useTranslation.cjs +14 -2
- package/build/react/client/useTranslation.d.cts +0 -35
- package/build/react/client/useTranslation.d.cts.map +1 -1
- package/build/react/client/useTranslation.d.mts +0 -35
- package/build/react/client/useTranslation.d.mts.map +1 -1
- package/build/react/client/useTranslation.mjs +15 -3
- package/build/react/client/useTranslation.mjs.map +1 -1
- package/build/react/server/ServerWeglotProvider.d.mts +2 -2
- package/build/react/server/index.cjs +2 -0
- package/build/react/server/index.d.cts +2 -1
- package/build/react/server/index.d.mts +2 -1
- package/build/react/server/index.mjs +2 -1
- package/build/react/server/useTranslation.cjs +6 -4
- package/build/react/server/useTranslation.d.cts.map +1 -1
- package/build/react/server/useTranslation.d.mts.map +1 -1
- package/build/react/server/useTranslation.mjs +6 -4
- package/build/react/server/useTranslation.mjs.map +1 -1
- package/build/react/server-only/index.cjs +5 -3
- package/build/react/server-only/index.d.cts +2 -3
- package/build/react/server-only/index.d.cts.map +1 -1
- package/build/react/server-only/index.d.mts +2 -3
- package/build/react/server-only/index.d.mts.map +1 -1
- package/build/react/server-only/index.mjs +5 -3
- package/build/react/server-only/index.mjs.map +1 -1
- package/build/react/server-only/translations.cjs +21 -1
- package/build/react/server-only/translations.mjs +22 -2
- package/build/react/server-only/translations.mjs.map +1 -1
- package/build/react/shared/LocaleSwitcher.d.mts +2 -2
- package/build/react/shared/WeglotContext.d.mts +1 -0
- package/build/react/shared/WeglotContext.d.mts.map +1 -1
- package/build/react/shared/WeglotProvider.d.mts +2 -2
- package/build/react/shared/msg.cjs +50 -0
- package/build/react/shared/msg.d.cts +26 -0
- package/build/react/shared/msg.d.cts.map +1 -0
- package/build/react/shared/msg.d.mts +26 -0
- package/build/react/shared/msg.d.mts.map +1 -0
- package/build/react/shared/msg.mjs +47 -0
- package/build/react/shared/msg.mjs.map +1 -0
- package/build/react/types.d.cts +7 -3
- package/build/react/types.d.cts.map +1 -1
- package/build/react/types.d.mts +7 -3
- package/build/react/types.d.mts.map +1 -1
- package/build/runtime/lru-cache.cjs +38 -0
- package/build/runtime/lru-cache.mjs +38 -0
- package/build/runtime/lru-cache.mjs.map +1 -0
- package/build/runtime/translate-dynamic.cjs +71 -17
- package/build/runtime/translate-dynamic.d.cts +2 -0
- package/build/runtime/translate-dynamic.d.cts.map +1 -1
- package/build/runtime/translate-dynamic.d.mts +2 -0
- package/build/runtime/translate-dynamic.d.mts.map +1 -1
- package/build/runtime/translate-dynamic.mjs +71 -17
- package/build/runtime/translate-dynamic.mjs.map +1 -1
- package/build/translators/weglot/api-client.cjs +4 -1
- package/build/translators/weglot/api-client.mjs +4 -1
- package/build/translators/weglot/api-client.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -3,6 +3,7 @@ import { withTimeout } from "../utils/timeout.mjs";
|
|
|
3
3
|
import { WORD_TYPE } from "../translators/weglot/definitions/definitions.generated.mjs";
|
|
4
4
|
import { WeglotApiClient } from "../translators/weglot/api-client.mjs";
|
|
5
5
|
import { HtmlSegmenter } from "./html/segmenter.mjs";
|
|
6
|
+
import { LruCache } from "./lru-cache.mjs";
|
|
6
7
|
import { cache } from "react";
|
|
7
8
|
import { apiBaseUrl, apiLocales, sourceLocale, translationEngine } from "@weglot/translate-react/virtual/config";
|
|
8
9
|
import { getServerLocale } from "@weglot/translate-react/virtual/locale/server";
|
|
@@ -10,23 +11,37 @@ import { getServerLocale } from "@weglot/translate-react/virtual/locale/server";
|
|
|
10
11
|
//#region src/runtime/translate-dynamic.ts
|
|
11
12
|
/**
|
|
12
13
|
* Runtime translation for content the compiler cannot see — a CMS title, an API
|
|
13
|
-
* record.
|
|
14
|
+
* record. Translations are kept in memory across requests, so content is only
|
|
15
|
+
* slow on its first view.
|
|
14
16
|
*/
|
|
15
17
|
/** Matches the translate API's own limit, as in the build-time translator. */
|
|
16
18
|
const MAX_WORDS_PER_REQUEST = 100;
|
|
17
19
|
/** Batches are shared across concurrent renders, so a busy server queues many pages. */
|
|
18
20
|
const MAX_CONCURRENT_REQUESTS = 4;
|
|
21
|
+
/** Collection window: server components render concurrently, so this gathers a
|
|
22
|
+
* whole page into one call. */
|
|
23
|
+
const DEFAULT_BATCH_WINDOW_MS = 5;
|
|
24
|
+
/** Measured round trips are ~150ms warm and ~750ms cold: this clears a warm
|
|
25
|
+
* call and cuts off a cold one. */
|
|
26
|
+
const DEFAULT_TIMEOUT_MS = 500;
|
|
27
|
+
const DEFAULT_CACHE_SIZE = 1e4;
|
|
28
|
+
/** Seconds a render that served source text stays cached before Next renders it again. */
|
|
29
|
+
const FALLBACK_REVALIDATE_SECONDS = 1;
|
|
19
30
|
let config = {
|
|
20
31
|
apiKey: void 0,
|
|
21
|
-
timeoutMs:
|
|
22
|
-
batchWindowMs:
|
|
32
|
+
timeoutMs: DEFAULT_TIMEOUT_MS,
|
|
33
|
+
batchWindowMs: DEFAULT_BATCH_WINDOW_MS,
|
|
34
|
+
cacheSize: DEFAULT_CACHE_SIZE
|
|
23
35
|
};
|
|
36
|
+
const translations = new LruCache(DEFAULT_CACHE_SIZE);
|
|
37
|
+
const cacheKey = (locale, text, type) => `${locale}\u0000${type}\u0000${text}`;
|
|
24
38
|
/** Optional: the key otherwise comes from WEGLOT_API_KEY. */
|
|
25
39
|
function configureDynamicTranslation(next) {
|
|
26
40
|
config = {
|
|
27
41
|
...config,
|
|
28
42
|
...next
|
|
29
43
|
};
|
|
44
|
+
translations.resize(config.cacheSize);
|
|
30
45
|
}
|
|
31
46
|
function resolveApiKey() {
|
|
32
47
|
return config.apiKey ?? process.env.WEGLOT_API_KEY;
|
|
@@ -44,6 +59,23 @@ function memoFor() {
|
|
|
44
59
|
return null;
|
|
45
60
|
}
|
|
46
61
|
}
|
|
62
|
+
/** Cuts the page's revalidation so Next does not keep serving the source text. */
|
|
63
|
+
async function shortenRevalidation() {
|
|
64
|
+
try {
|
|
65
|
+
const { unstable_cache } = await import("next/cache");
|
|
66
|
+
await unstable_cache(async () => null, ["weglot-dynamic-fallback"], { revalidate: FALLBACK_REVALIDATE_SECONDS })();
|
|
67
|
+
} catch (error) {
|
|
68
|
+
logger.debug(`Could not shorten the revalidation of a page with untranslated dynamic content: ${error instanceof Error ? error.message : String(error)}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function translateWord(locale, text, timeoutMs, type = WORD_TYPE.TEXT) {
|
|
72
|
+
const cached = translations.get(cacheKey(locale, text, type));
|
|
73
|
+
if (cached !== void 0) return Promise.resolve({
|
|
74
|
+
text: cached,
|
|
75
|
+
fallback: false
|
|
76
|
+
});
|
|
77
|
+
return enqueue(locale, text, timeoutMs, type);
|
|
78
|
+
}
|
|
47
79
|
function enqueue(locale, text, timeoutMs, type) {
|
|
48
80
|
const key = batchKey(locale, timeoutMs);
|
|
49
81
|
return new Promise((resolve) => {
|
|
@@ -65,7 +97,10 @@ async function flush(key, locale, timeoutMs) {
|
|
|
65
97
|
const apiKey = resolveApiKey();
|
|
66
98
|
if (!apiKey) {
|
|
67
99
|
logger.warn("Weglot project key is missing, so dynamic content is served untranslated. Set WEGLOT_API_KEY or call configureDynamicTranslation({ apiKey }).");
|
|
68
|
-
queue.forEach((word) => word.resolve(
|
|
100
|
+
queue.forEach((word) => word.resolve({
|
|
101
|
+
text: word.text,
|
|
102
|
+
fallback: false
|
|
103
|
+
}));
|
|
69
104
|
return;
|
|
70
105
|
}
|
|
71
106
|
const client = new WeglotApiClient(apiKey, apiBaseUrl);
|
|
@@ -73,30 +108,45 @@ async function flush(key, locale, timeoutMs) {
|
|
|
73
108
|
for (let i = 0; i < queue.length; i += MAX_WORDS_PER_REQUEST) chunks.push(queue.slice(i, i + MAX_WORDS_PER_REQUEST));
|
|
74
109
|
const deadline = Date.now() + timeoutMs;
|
|
75
110
|
let next = 0;
|
|
111
|
+
const fallBack = (chunk) => chunk.forEach((word) => word.resolve({
|
|
112
|
+
text: word.text,
|
|
113
|
+
fallback: true
|
|
114
|
+
}));
|
|
76
115
|
const worker = async () => {
|
|
77
116
|
while (next < chunks.length) {
|
|
78
117
|
const chunk = chunks[next++];
|
|
79
118
|
if (Date.now() >= deadline) {
|
|
80
|
-
chunk
|
|
119
|
+
fallBack(chunk);
|
|
81
120
|
continue;
|
|
82
121
|
}
|
|
122
|
+
const request = client.translate({
|
|
123
|
+
from: sourceLocale,
|
|
124
|
+
to: apiLocales[locale] ?? locale,
|
|
125
|
+
words: chunk.map((word) => word.text),
|
|
126
|
+
types: chunk.map((word) => word.type),
|
|
127
|
+
live: true
|
|
128
|
+
});
|
|
129
|
+
request.then(({ words }) => chunk.forEach((word, index) => {
|
|
130
|
+
const result = words[index];
|
|
131
|
+
if (result != null) translations.set(cacheKey(locale, word.text, word.type), result);
|
|
132
|
+
})).catch(() => {});
|
|
83
133
|
try {
|
|
84
|
-
const { words: translated } = await withTimeout(
|
|
85
|
-
from: sourceLocale,
|
|
86
|
-
to: apiLocales[locale] ?? locale,
|
|
87
|
-
words: chunk.map((word) => word.text),
|
|
88
|
-
types: chunk.map((word) => word.type ?? WORD_TYPE.TEXT),
|
|
89
|
-
live: true
|
|
90
|
-
}), deadline - Date.now(), `Weglot dynamic translation to ${locale}`);
|
|
134
|
+
const { words: translated } = await withTimeout(request, deadline - Date.now(), `Weglot dynamic translation to ${locale}`);
|
|
91
135
|
chunk.forEach((word, index) => {
|
|
92
136
|
const result = translated[index];
|
|
93
137
|
if (result === null) logger.debug(`Weglot is still translating dynamic content for locale "${locale}".`);
|
|
94
138
|
else if (result === word.text) logger.debug(`Weglot returned dynamic content unchanged for locale "${locale}".`);
|
|
95
|
-
word.resolve(result
|
|
139
|
+
word.resolve(result === null ? {
|
|
140
|
+
text: word.text,
|
|
141
|
+
fallback: true
|
|
142
|
+
} : {
|
|
143
|
+
text: result,
|
|
144
|
+
fallback: false
|
|
145
|
+
});
|
|
96
146
|
});
|
|
97
147
|
} catch (error) {
|
|
98
148
|
logger.warn(`Dynamic translation to "${locale}" failed, serving source text: ${error instanceof Error ? error.message : String(error)}`);
|
|
99
|
-
chunk
|
|
149
|
+
fallBack(chunk);
|
|
100
150
|
}
|
|
101
151
|
}
|
|
102
152
|
};
|
|
@@ -112,7 +162,10 @@ async function tDynamic(text, options = {}) {
|
|
|
112
162
|
const key = `${batchKey(locale, timeoutMs)}\u0000${text}`;
|
|
113
163
|
const existing = memo?.get(key);
|
|
114
164
|
if (existing) return existing;
|
|
115
|
-
const pending =
|
|
165
|
+
const pending = translateWord(locale, text, timeoutMs).then(async (result) => {
|
|
166
|
+
if (result.fallback) await shortenRevalidation();
|
|
167
|
+
return result.text;
|
|
168
|
+
});
|
|
116
169
|
memo?.set(key, pending);
|
|
117
170
|
return pending;
|
|
118
171
|
}
|
|
@@ -128,8 +181,9 @@ async function tDynamicHtml(html, options = {}) {
|
|
|
128
181
|
const segmenter = new HtmlSegmenter(html, translationEngine);
|
|
129
182
|
const segments = segmenter.extract();
|
|
130
183
|
if (segments.length === 0) return html;
|
|
131
|
-
const translated = await Promise.all(segments.map((segment) =>
|
|
132
|
-
|
|
184
|
+
const translated = await Promise.all(segments.map((segment) => translateWord(locale, segment.w, timeoutMs, segment.t)));
|
|
185
|
+
if (translated.some((result) => result.fallback)) await shortenRevalidation();
|
|
186
|
+
return segmenter.apply(translated.map((result) => result.text));
|
|
133
187
|
}
|
|
134
188
|
/** Translates several strings in one pass, sharing a single request. */
|
|
135
189
|
async function tDynamicAll(texts, options = {}) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translate-dynamic.mjs","names":["config: Required<\n Pick<DynamicTranslationConfig, \"timeoutMs\" | \"batchWindowMs\">\n> &\n Pick<DynamicTranslationConfig, \"apiKey\">","chunks: PendingWord[][]"],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":["/**\n * Runtime translation for content the compiler cannot see — a CMS title, an API\n * record. No cache: the API already stores repeated segments.\n */\n\nimport { cache } from \"react\";\nimport { WeglotApiClient } from \"../translators/weglot/api-client\";\nimport { WORD_TYPE } from \"../translators/weglot/definitions/definitions.generated\";\nimport { HtmlSegmenter } from \"./html/segmenter\";\nimport { translationEngine } from \"@weglot/translate-react/virtual/config\";\nimport { logger } from \"../utils/logger\";\nimport { withTimeout } from \"../utils/timeout\";\nimport type { LocaleCode } from \"../locale\";\n// Keep these imports full for replacement during build.\nimport {\n apiBaseUrl,\n apiLocales,\n sourceLocale,\n} from \"@weglot/translate-react/virtual/config\";\nimport { getServerLocale } from \"@weglot/translate-react/virtual/locale/server\";\n\n/** Matches the translate API's own limit, as in the build-time translator. */\nconst MAX_WORDS_PER_REQUEST = 100;\n\n/** Batches are shared across concurrent renders, so a busy server queues many pages. */\nconst MAX_CONCURRENT_REQUESTS = 4;\n\n/** Collection window: server components render concurrently, so this gathers a\n * whole page into one call. */\nconst DEFAULT_BATCH_WINDOW_MS = 5;\n\n/** Measured round trips are ~150ms warm and ~750ms cold: this clears a warm\n * call and cuts off a cold one. */\nconst DEFAULT_TIMEOUT_MS = 500;\n\nexport interface DynamicTranslationOptions {\n /** Overrides the locale resolved from the request. */\n locale?: LocaleCode;\n /** Overrides the per-call ceiling before the source text is served. */\n timeoutMs?: number;\n}\n\nexport interface DynamicTranslationConfig {\n apiKey?: string;\n timeoutMs?: number;\n batchWindowMs?: number;\n}\n\nlet config: Required<\n Pick<DynamicTranslationConfig, \"timeoutMs\" | \"batchWindowMs\">\n> &\n Pick<DynamicTranslationConfig, \"apiKey\"> = {\n apiKey: undefined,\n timeoutMs: DEFAULT_TIMEOUT_MS,\n batchWindowMs: DEFAULT_BATCH_WINDOW_MS,\n};\n\n/** Optional: the key otherwise comes from WEGLOT_API_KEY. */\nexport function configureDynamicTranslation(\n next: DynamicTranslationConfig,\n): void {\n config = { ...config, ...next };\n}\n\nfunction resolveApiKey(): string | undefined {\n return config.apiKey ?? process.env.WEGLOT_API_KEY;\n}\n\ninterface PendingWord {\n text: string;\n type?: number;\n resolve: (translated: string) => void;\n}\n\n/** Keyed by ceiling too, or the stricter call would inherit the looser one's wait. */\ntype BatchKey = string;\n\nconst queues = new Map<BatchKey, PendingWord[]>();\nconst timers = new Map<BatchKey, ReturnType<typeof setTimeout>>();\n\nconst batchKey = (locale: LocaleCode, timeoutMs: number): BatchKey =>\n `${locale}\\u0000${timeoutMs}`;\n\n/** One map per request, so a title rendered twice is translated once. Outside a\n * render, `cache` has nothing to key on and calls stand alone. */\nconst requestMemo = cache(() => new Map<string, Promise<string>>());\n\nfunction memoFor(): Map<string, Promise<string>> | null {\n try {\n return requestMemo();\n } catch {\n return null;\n }\n}\n\nfunction enqueue(\n locale: LocaleCode,\n text: string,\n timeoutMs: number,\n type?: number,\n): Promise<string> {\n const key = batchKey(locale, timeoutMs);\n return new Promise<string>((resolve) => {\n const queue = queues.get(key) ?? [];\n queue.push({ text, type, resolve });\n queues.set(key, queue);\n\n if (!timers.has(key)) {\n timers.set(\n key,\n setTimeout(\n () => void flush(key, locale, timeoutMs),\n config.batchWindowMs,\n ),\n );\n }\n });\n}\n\nasync function flush(\n key: BatchKey,\n locale: LocaleCode,\n timeoutMs: number,\n): Promise<void> {\n timers.delete(key);\n const queue = queues.get(key) ?? [];\n queues.delete(key);\n if (queue.length === 0) return;\n\n const apiKey = resolveApiKey();\n if (!apiKey) {\n logger.warn(\n \"Weglot project key is missing, so dynamic content is served untranslated. Set WEGLOT_API_KEY or call configureDynamicTranslation({ apiKey }).\",\n );\n queue.forEach((word) => word.resolve(word.text));\n return;\n }\n\n const client = new WeglotApiClient(apiKey, apiBaseUrl);\n\n const chunks: PendingWord[][] = [];\n for (let i = 0; i < queue.length; i += MAX_WORDS_PER_REQUEST) {\n chunks.push(queue.slice(i, i + MAX_WORDS_PER_REQUEST));\n }\n\n // One deadline for the batch: chunks sent in turn would multiply the ceiling.\n // The pool bounds the burst, since the ceiling cannot recall a sent request.\n const deadline = Date.now() + timeoutMs;\n let next = 0;\n\n const worker = async (): Promise<void> => {\n while (next < chunks.length) {\n const chunk = chunks[next++];\n if (Date.now() >= deadline) {\n chunk.forEach((word) => word.resolve(word.text));\n continue;\n }\n\n try {\n const { words: translated } = await withTimeout(\n client.translate({\n from: sourceLocale,\n to: apiLocales[locale] ?? locale,\n words: chunk.map((word) => word.text),\n types: chunk.map((word) => word.type ?? WORD_TYPE.TEXT),\n live: true,\n }),\n deadline - Date.now(),\n `Weglot dynamic translation to ${locale}`,\n );\n\n chunk.forEach((word, index) => {\n const result = translated[index];\n if (result === null) {\n // Not translated yet at Weglot; a later request gets the translation.\n logger.debug(\n `Weglot is still translating dynamic content for locale \"${locale}\".`,\n );\n } else if (result === word.text) {\n // The API echoes a segment back when it rejects it.\n logger.debug(\n `Weglot returned dynamic content unchanged for locale \"${locale}\".`,\n );\n }\n word.resolve(result ?? word.text);\n });\n } catch (error) {\n // A slow or failing API must degrade to source text, never break a page.\n logger.warn(\n `Dynamic translation to \"${locale}\" failed, serving source text: ${error instanceof Error ? error.message : String(error)}`,\n );\n chunk.forEach((word) => word.resolve(word.text));\n }\n }\n };\n\n await Promise.all(\n Array.from(\n { length: Math.min(MAX_CONCURRENT_REQUESTS, chunks.length) },\n worker,\n ),\n );\n}\n\n/** Translate a string that only exists at runtime: `await tDynamic(post.title)`. */\nexport async function tDynamic(\n text: string,\n options: DynamicTranslationOptions = {},\n): Promise<string> {\n if (!text.trim()) return text;\n\n const locale = options.locale ?? (await getServerLocale());\n if (!locale || locale === sourceLocale) return text;\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs;\n const memo = memoFor();\n const key = `${batchKey(locale, timeoutMs)}\\u0000${text}`;\n const existing = memo?.get(key);\n if (existing) return existing;\n\n const pending = enqueue(locale, text, timeoutMs);\n memo?.set(key, pending);\n return pending;\n}\n\n/**\n * Translate an HTML fragment, split into segments the way the proxy splits a\n * page, so a sentence wrapped in `<strong>` travels whole.\n */\nexport async function tDynamicHtml(\n html: string,\n options: DynamicTranslationOptions = {},\n): Promise<string> {\n if (!html.trim()) return html;\n\n const locale = options.locale ?? (await getServerLocale());\n if (!locale || locale === sourceLocale) return html;\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs;\n const segmenter = new HtmlSegmenter(html, translationEngine);\n const segments = segmenter.extract();\n if (segments.length === 0) return html;\n\n const translated = await Promise.all(\n segments.map((segment) => enqueue(locale, segment.w, timeoutMs, segment.t)),\n );\n return segmenter.apply(translated);\n}\n\n/** Translates several strings in one pass, sharing a single request. */\nexport async function tDynamicAll(\n texts: string[],\n options: DynamicTranslationOptions = {},\n): Promise<string[]> {\n return Promise.all(texts.map((text) => tDynamic(text, options)));\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsBA,MAAM,wBAAwB;;AAG9B,MAAM,0BAA0B;AAuBhC,IAAIA,SAGyC;CAC3C,QAAQ;CACR,WApByB;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AG,SAAS,QAAQ,UAAU,CAAC,QAAQ;CACnD,MAAM,WAAW,MAAM,IAAI,IAAI;AAC/B,KAAI,SAAU,QAAO;CAErB,MAAM,UAAU,QAAQ,QAAQ,MAAM,UAAU;AAChD,OAAM,IAAI,KAAK,QAAQ;AACvB,QAAO;;;;;;AAOT,eAAsB,aACpB,MACA,UAAqC,EAAE,EACtB;AACjB,KAAI,CAAC,KAAK,MAAM,CAAE,QAAO;CAEzB,MAAM,SAAS,QAAQ,UAAW,MAAM,iBAAiB;AACzD,KAAI,CAAC,UAAU,WAAW,aAAc,QAAO;CAE/C,MAAM,YAAY,QAAQ,aAAa,OAAO;CAC9C,MAAM,YAAY,IAAI,cAAc,MAAM,kBAAkB;CAC5D,MAAM,WAAW,UAAU,SAAS;AACpC,KAAI,SAAS,WAAW,EAAG,QAAO;CAElC,MAAM,aAAa,MAAM,QAAQ,IAC/B,SAAS,KAAK,YAAY,QAAQ,QAAQ,QAAQ,GAAG,WAAW,QAAQ,EAAE,CAAC,CAC5E;AACD,QAAO,UAAU,MAAM,WAAW;;;AAIpC,eAAsB,YACpB,OACA,UAAqC,EAAE,EACpB;AACnB,QAAO,QAAQ,IAAI,MAAM,KAAK,SAAS,SAAS,MAAM,QAAQ,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"translate-dynamic.mjs","names":["config: Required<\n Pick<DynamicTranslationConfig, \"timeoutMs\" | \"batchWindowMs\" | \"cacheSize\">\n> &\n Pick<DynamicTranslationConfig, \"apiKey\">","chunks: PendingWord[][]"],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":["/**\n * Runtime translation for content the compiler cannot see — a CMS title, an API\n * record. Translations are kept in memory across requests, so content is only\n * slow on its first view.\n */\n\nimport { cache } from \"react\";\nimport { WeglotApiClient } from \"../translators/weglot/api-client\";\nimport { WORD_TYPE } from \"../translators/weglot/definitions/definitions.generated\";\nimport { HtmlSegmenter } from \"./html/segmenter\";\nimport { translationEngine } from \"@weglot/translate-react/virtual/config\";\nimport { logger } from \"../utils/logger\";\nimport { withTimeout } from \"../utils/timeout\";\nimport { LruCache } from \"./lru-cache\";\nimport type { LocaleCode } from \"../locale\";\n// Keep these imports full for replacement during build.\nimport {\n apiBaseUrl,\n apiLocales,\n sourceLocale,\n} from \"@weglot/translate-react/virtual/config\";\nimport { getServerLocale } from \"@weglot/translate-react/virtual/locale/server\";\n\n/** Matches the translate API's own limit, as in the build-time translator. */\nconst MAX_WORDS_PER_REQUEST = 100;\n\n/** Batches are shared across concurrent renders, so a busy server queues many pages. */\nconst MAX_CONCURRENT_REQUESTS = 4;\n\n/** Collection window: server components render concurrently, so this gathers a\n * whole page into one call. */\nconst DEFAULT_BATCH_WINDOW_MS = 5;\n\n/** Measured round trips are ~150ms warm and ~750ms cold: this clears a warm\n * call and cuts off a cold one. */\nconst DEFAULT_TIMEOUT_MS = 500;\n\nconst DEFAULT_CACHE_SIZE = 10_000;\n\n/** Seconds a render that served source text stays cached before Next renders it again. */\nconst FALLBACK_REVALIDATE_SECONDS = 1;\n\nexport interface DynamicTranslationOptions {\n /** Overrides the locale resolved from the request. */\n locale?: LocaleCode;\n /** Overrides the per-call ceiling before the source text is served. */\n timeoutMs?: number;\n}\n\nexport interface DynamicTranslationConfig {\n apiKey?: string;\n timeoutMs?: number;\n batchWindowMs?: number;\n /** Translations kept in memory across requests. 0 disables the cache. */\n cacheSize?: number;\n}\n\nlet config: Required<\n Pick<DynamicTranslationConfig, \"timeoutMs\" | \"batchWindowMs\" | \"cacheSize\">\n> &\n Pick<DynamicTranslationConfig, \"apiKey\"> = {\n apiKey: undefined,\n timeoutMs: DEFAULT_TIMEOUT_MS,\n batchWindowMs: DEFAULT_BATCH_WINDOW_MS,\n cacheSize: DEFAULT_CACHE_SIZE,\n};\n\nconst translations = new LruCache<string>(DEFAULT_CACHE_SIZE);\n\nconst cacheKey = (locale: LocaleCode, text: string, type: number): string =>\n `${locale}\\u0000${type}\\u0000${text}`;\n\n/** Optional: the key otherwise comes from WEGLOT_API_KEY. */\nexport function configureDynamicTranslation(\n next: DynamicTranslationConfig,\n): void {\n config = { ...config, ...next };\n translations.resize(config.cacheSize);\n}\n\nfunction resolveApiKey(): string | undefined {\n return config.apiKey ?? process.env.WEGLOT_API_KEY;\n}\n\ninterface Translated {\n text: string;\n /** The source text was served because the translation was not available in time. */\n fallback: boolean;\n}\n\ninterface PendingWord {\n text: string;\n type: number;\n resolve: (result: Translated) => void;\n}\n\n/** Keyed by ceiling too, or the stricter call would inherit the looser one's wait. */\ntype BatchKey = string;\n\nconst queues = new Map<BatchKey, PendingWord[]>();\nconst timers = new Map<BatchKey, ReturnType<typeof setTimeout>>();\n\nconst batchKey = (locale: LocaleCode, timeoutMs: number): BatchKey =>\n `${locale}\\u0000${timeoutMs}`;\n\n/** One map per request, so a title rendered twice is translated once. Outside a\n * render, `cache` has nothing to key on and calls stand alone. */\nconst requestMemo = cache(() => new Map<string, Promise<string>>());\n\nfunction memoFor(): Map<string, Promise<string>> | null {\n try {\n return requestMemo();\n } catch {\n return null;\n }\n}\n\n/** Cuts the page's revalidation so Next does not keep serving the source text. */\nasync function shortenRevalidation(): Promise<void> {\n try {\n const { unstable_cache } = await import(\"next/cache\");\n await unstable_cache(async () => null, [\"weglot-dynamic-fallback\"], {\n revalidate: FALLBACK_REVALIDATE_SECONDS,\n })();\n } catch (error) {\n logger.debug(\n `Could not shorten the revalidation of a page with untranslated dynamic content: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nfunction translateWord(\n locale: LocaleCode,\n text: string,\n timeoutMs: number,\n type: number = WORD_TYPE.TEXT,\n): Promise<Translated> {\n const cached = translations.get(cacheKey(locale, text, type));\n if (cached !== undefined) {\n return Promise.resolve({ text: cached, fallback: false });\n }\n return enqueue(locale, text, timeoutMs, type);\n}\n\nfunction enqueue(\n locale: LocaleCode,\n text: string,\n timeoutMs: number,\n type: number,\n): Promise<Translated> {\n const key = batchKey(locale, timeoutMs);\n return new Promise<Translated>((resolve) => {\n const queue = queues.get(key) ?? [];\n queue.push({ text, type, resolve });\n queues.set(key, queue);\n\n if (!timers.has(key)) {\n timers.set(\n key,\n setTimeout(\n () => void flush(key, locale, timeoutMs),\n config.batchWindowMs,\n ),\n );\n }\n });\n}\n\nasync function flush(\n key: BatchKey,\n locale: LocaleCode,\n timeoutMs: number,\n): Promise<void> {\n timers.delete(key);\n const queue = queues.get(key) ?? [];\n queues.delete(key);\n if (queue.length === 0) return;\n\n const apiKey = resolveApiKey();\n if (!apiKey) {\n logger.warn(\n \"Weglot project key is missing, so dynamic content is served untranslated. Set WEGLOT_API_KEY or call configureDynamicTranslation({ apiKey }).\",\n );\n queue.forEach((word) => word.resolve({ text: word.text, fallback: false }));\n return;\n }\n\n const client = new WeglotApiClient(apiKey, apiBaseUrl);\n\n const chunks: PendingWord[][] = [];\n for (let i = 0; i < queue.length; i += MAX_WORDS_PER_REQUEST) {\n chunks.push(queue.slice(i, i + MAX_WORDS_PER_REQUEST));\n }\n\n // One deadline for the batch: chunks sent in turn would multiply the ceiling.\n // The pool bounds the burst, since the ceiling cannot recall a sent request.\n const deadline = Date.now() + timeoutMs;\n let next = 0;\n const fallBack = (chunk: PendingWord[]) =>\n chunk.forEach((word) => word.resolve({ text: word.text, fallback: true }));\n\n const worker = async (): Promise<void> => {\n while (next < chunks.length) {\n const chunk = chunks[next++];\n if (Date.now() >= deadline) {\n fallBack(chunk);\n continue;\n }\n\n const request = client.translate({\n from: sourceLocale,\n to: apiLocales[locale] ?? locale,\n words: chunk.map((word) => word.text),\n types: chunk.map((word) => word.type),\n live: true,\n });\n // An answer arriving after the deadline still serves the next request.\n request\n .then(({ words }) =>\n chunk.forEach((word, index) => {\n const result = words[index];\n if (result != null) {\n translations.set(cacheKey(locale, word.text, word.type), result);\n }\n }),\n )\n .catch(() => {});\n\n try {\n const { words: translated } = await withTimeout(\n request,\n deadline - Date.now(),\n `Weglot dynamic translation to ${locale}`,\n );\n\n chunk.forEach((word, index) => {\n const result = translated[index];\n if (result === null) {\n // Not translated yet at Weglot; a later request gets the translation.\n logger.debug(\n `Weglot is still translating dynamic content for locale \"${locale}\".`,\n );\n } else if (result === word.text) {\n // The API echoes a segment back when it rejects it.\n logger.debug(\n `Weglot returned dynamic content unchanged for locale \"${locale}\".`,\n );\n }\n word.resolve(\n result === null\n ? { text: word.text, fallback: true }\n : { text: result, fallback: false },\n );\n });\n } catch (error) {\n // A slow or failing API must degrade to source text, never break a page.\n logger.warn(\n `Dynamic translation to \"${locale}\" failed, serving source text: ${error instanceof Error ? error.message : String(error)}`,\n );\n fallBack(chunk);\n }\n }\n };\n\n await Promise.all(\n Array.from(\n { length: Math.min(MAX_CONCURRENT_REQUESTS, chunks.length) },\n worker,\n ),\n );\n}\n\n/** Translate a string that only exists at runtime: `await tDynamic(post.title)`. */\nexport async function tDynamic(\n text: string,\n options: DynamicTranslationOptions = {},\n): Promise<string> {\n if (!text.trim()) return text;\n\n const locale = options.locale ?? (await getServerLocale());\n if (!locale || locale === sourceLocale) return text;\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs;\n const memo = memoFor();\n const key = `${batchKey(locale, timeoutMs)}\\u0000${text}`;\n const existing = memo?.get(key);\n if (existing) return existing;\n\n const pending = translateWord(locale, text, timeoutMs).then(\n async (result) => {\n if (result.fallback) await shortenRevalidation();\n return result.text;\n },\n );\n memo?.set(key, pending);\n return pending;\n}\n\n/**\n * Translate an HTML fragment, split into segments the way the proxy splits a\n * page, so a sentence wrapped in `<strong>` travels whole.\n */\nexport async function tDynamicHtml(\n html: string,\n options: DynamicTranslationOptions = {},\n): Promise<string> {\n if (!html.trim()) return html;\n\n const locale = options.locale ?? (await getServerLocale());\n if (!locale || locale === sourceLocale) return html;\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs;\n const segmenter = new HtmlSegmenter(html, translationEngine);\n const segments = segmenter.extract();\n if (segments.length === 0) return html;\n\n const translated = await Promise.all(\n segments.map((segment) =>\n translateWord(locale, segment.w, timeoutMs, segment.t),\n ),\n );\n if (translated.some((result) => result.fallback)) {\n await shortenRevalidation();\n }\n return segmenter.apply(translated.map((result) => result.text));\n}\n\n/** Translates several strings in one pass, sharing a single request. */\nexport async function tDynamicAll(\n texts: string[],\n options: DynamicTranslationOptions = {},\n): Promise<string[]> {\n return Promise.all(texts.map((text) => tDynamic(text, options)));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,MAAM,wBAAwB;;AAG9B,MAAM,0BAA0B;;;AAIhC,MAAM,0BAA0B;;;AAIhC,MAAM,qBAAqB;AAE3B,MAAM,qBAAqB;;AAG3B,MAAM,8BAA8B;AAiBpC,IAAIA,SAGyC;CAC3C,QAAQ;CACR,WAAW;CACX,eAAe;CACf,WAAW;CACZ;AAED,MAAM,eAAe,IAAI,SAAiB,mBAAmB;AAE7D,MAAM,YAAY,QAAoB,MAAc,SAClD,GAAG,OAAO,QAAQ,KAAK,QAAQ;;AAGjC,SAAgB,4BACd,MACM;AACN,UAAS;EAAE,GAAG;EAAQ,GAAG;EAAM;AAC/B,cAAa,OAAO,OAAO,UAAU;;AAGvC,SAAS,gBAAoC;AAC3C,QAAO,OAAO,UAAU,QAAQ,IAAI;;AAkBtC,MAAM,yBAAS,IAAI,KAA8B;AACjD,MAAM,yBAAS,IAAI,KAA8C;AAEjE,MAAM,YAAY,QAAoB,cACpC,GAAG,OAAO,QAAQ;;;AAIpB,MAAM,cAAc,4BAAY,IAAI,KAA8B,CAAC;AAEnE,SAAS,UAA+C;AACtD,KAAI;AACF,SAAO,aAAa;SACd;AACN,SAAO;;;;AAKX,eAAe,sBAAqC;AAClD,KAAI;EACF,MAAM,EAAE,mBAAmB,MAAM,OAAO;AACxC,QAAM,eAAe,YAAY,MAAM,CAAC,0BAA0B,EAAE,EAClE,YAAY,6BACb,CAAC,EAAE;UACG,OAAO;AACd,SAAO,MACL,mFAAmF,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,GAC1I;;;AAIL,SAAS,cACP,QACA,MACA,WACA,OAAe,UAA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`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, { headers: {
|
|
140
|
+
const response = await require_timeout.withTimeout(fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, { headers: {
|
|
141
|
+
Accept: "application/json",
|
|
142
|
+
Authorization: `Key ${this.apiKey}`
|
|
143
|
+
} }), require_timeout.DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
|
|
141
144
|
if (!response.ok) throw new Error(`Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`);
|
|
142
145
|
const data = await response.json();
|
|
143
146
|
if (data.product !== SUPPORTED_PRODUCT) throw new Error("@weglot/translate-react does not support the Weglot project this key belongs to. Check that you are using the right project key.");
|
|
@@ -137,7 +137,10 @@ var WeglotApiClient = class {
|
|
|
137
137
|
}
|
|
138
138
|
}
|
|
139
139
|
async fetchSettings() {
|
|
140
|
-
const response = await withTimeout(fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, { headers: {
|
|
140
|
+
const response = await withTimeout(fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, { headers: {
|
|
141
|
+
Accept: "application/json",
|
|
142
|
+
Authorization: `Key ${this.apiKey}`
|
|
143
|
+
} }), DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
|
|
141
144
|
if (!response.ok) throw new Error(`Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`);
|
|
142
145
|
const data = await response.json();
|
|
143
146
|
if (data.product !== SUPPORTED_PRODUCT) throw new Error("@weglot/translate-react does not support the Weglot project this key belongs to. Check that you are using the right project key.");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-client.mjs","names":["from: string","to: string","apiKey: string","words: (string | null)[]","everAccepted: boolean[]","misses: number[]","lastError: unknown"],"sources":["../../../src/translators/weglot/api-client.ts"],"sourcesContent":["/**\n * Weglot API client. Weglot translates with an LLM: a word not translated yet\n * comes back null and is queued, so callers poll until it is ready.\n */\n\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport { WORD_TYPE } from \"./definitions/definitions.generated\";\n\nconst DEFAULT_SETTINGS_URL = \"https://api.weglot.com/project-settings\";\nexport const DEFAULT_API_BASE_URL = \"https://api.weglot.com\";\nconst SUPPORTED_PRODUCT = \"2.0\";\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// Tags the words in the dashboard with where they came from.\nconst WORD_LABEL = \"translate-react\";\nexport const MAX_WORDS_PER_REQUEST = 100;\nexport const DEFAULT_POLL_INTERVAL_MS = 5_000;\n// The API sometimes takes new words only on a second request; one still without an id after this many is refused.\nconst REFUSED_AFTER_MISSES = 2;\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 /** The project's regional API host, e.g. https://eu.api.weglot.com. */\n apiBaseUrl: string;\n /** Inline elements allowed in a segment; absent on older projects. */\n translationEngine?: number;\n};\n\nexport type TranslateParams = {\n from: string;\n to: string;\n words: string[];\n /** Word type per word; body text when omitted. */\n types?: number[];\n /** Marks a request made while a page renders, as opposed to a build. */\n live?: boolean;\n};\n\nexport type TranslateResponse = {\n /** Null while not translated yet. */\n words: (string | null)[];\n /** Whether the API took each word in: it was translated or given an id. */\n accepted: boolean[];\n};\n\nexport type PolledTranslation = {\n /** Null for words still queued at the deadline or refused. */\n words: (string | null)[];\n /** Indexes of the words the API will not translate. */\n refused: number[];\n};\n\nexport type PollOptions = {\n /** Epoch ms after which words still queued are given up on. */\n deadline: number;\n pollIntervalMs?: number;\n sleep?: (ms: number) => Promise<void>;\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\n/** A 400 the API gives a whole request when one of its words is unreadable. */\nclass RefusedRequestError extends Error {}\n\nconst wellFormed = (text: string) =>\n text.replace(/[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/g, \"\\uFFFD\");\n\nconst defaultSleep = (ms: number) =>\n new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nexport class WeglotApiClient {\n private readonly apiBaseUrl: string;\n\n constructor(\n private readonly apiKey: string,\n apiBaseUrl?: string,\n ) {\n this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;\n }\n\n /** One request. A word not translated yet comes back null, with an id once the API has queued it. */\n async translate(params: TranslateParams): Promise<TranslateResponse> {\n const query = params.live ? \"?live=1\" : \"\";\n const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n Authorization: `Key ${this.apiKey}`,\n },\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 // A lone surrogate makes the API refuse the whole request.\n w: wellFormed(w),\n l: [WORD_LABEL],\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 if (response.status === 400) {\n throw new RefusedRequestError(\n `Weglot translate API refused the request (400): ${body || \"no response body\"}`,\n );\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 {\n to_words?: (string | null)[];\n ids?: (string | null)[];\n };\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 const ids = Array.isArray(data.ids) ? data.ids : null;\n\n return {\n words: toWords,\n accepted: toWords.map(\n (value, index) => value !== null || ids === null || (ids[index] ?? null) !== null,\n ),\n };\n }\n\n /** Re-polls words until translated or the deadline. A failed request leaves\n * its words pending, so one error never discards what was already received. */\n async translateUntilReady(\n params: TranslateParams,\n { deadline, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, sleep = defaultSleep }: PollOptions,\n ): Promise<PolledTranslation> {\n const words: (string | null)[] = new Array(params.words.length).fill(null);\n const everAccepted: boolean[] = new Array(params.words.length).fill(false);\n const misses: number[] = new Array(params.words.length).fill(0);\n const refused = new Set<number>();\n let pending = params.words.map((_, index) => index);\n let received = false;\n let anyAccepted = false;\n let lastError: unknown;\n\n while (true) {\n for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) {\n try {\n const answers = await this.sendIsolatingRefused(\n params,\n pending.slice(i, i + MAX_WORDS_PER_REQUEST),\n refused,\n );\n received = true;\n for (const { index, word, accepted } of answers) {\n words[index] = word;\n if (accepted) {\n everAccepted[index] = true;\n anyAccepted = true;\n } else {\n misses[index]++;\n }\n }\n } catch (error) {\n if (error instanceof UnsupportedLanguagePairError) throw error;\n lastError = error;\n }\n }\n\n // Only while the API takes other words in: otherwise it is not ready, and the words stay pending.\n if (anyAccepted) {\n for (const index of pending) {\n if (!everAccepted[index] && misses[index] >= REFUSED_AFTER_MISSES) refused.add(index);\n }\n }\n pending = pending.filter((index) => words[index] === null && !refused.has(index));\n\n const remaining = deadline - Date.now();\n if (pending.length === 0 || remaining <= 0) {\n // Nothing ever got through: a key or quota problem, not a slow queue.\n if (!received && lastError !== undefined) throw lastError;\n return { words, refused: [...refused].sort((a, b) => a - b) };\n }\n await sleep(Math.min(pollIntervalMs, remaining));\n }\n }\n\n /** Splits a request the API refuses until the unreadable word is alone, then marks it refused. */\n private async sendIsolatingRefused(\n params: TranslateParams,\n indexes: number[],\n refused: Set<number>,\n ): Promise<{ index: number; word: string | null; accepted: boolean }[]> {\n try {\n const { words, accepted } = await withTimeout(\n this.translate({\n from: params.from,\n to: params.to,\n words: indexes.map((index) => params.words[index]),\n types: params.types && indexes.map((index) => params.types![index]),\n }),\n DEFAULT_TIMEOUTS.AI_API,\n `Weglot API translation to ${params.to}`,\n );\n return indexes.map((index, k) => ({ index, word: words[k], accepted: accepted[k] }));\n } catch (error) {\n if (!(error instanceof RefusedRequestError)) throw error;\n if (indexes.length === 1) {\n refused.add(indexes[0]);\n return [];\n }\n const middle = Math.ceil(indexes.length / 2);\n return [\n ...(await this.sendIsolatingRefused(params, indexes.slice(0, middle), refused)),\n ...(await this.sendIsolatingRefused(params, indexes.slice(middle), refused)),\n ];\n }\n }\n\n async fetchSettings(): Promise<WeglotProjectSettings> {\n const response = await withTimeout(\n // Overridable to point at another settings endpoint.\n fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, {\n headers: { Accept: \"application/json\" },\n }),\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 product?: string;\n api_base_url?: string;\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.product !== SUPPORTED_PRODUCT) {\n throw new Error(\n \"@weglot/translate-react does not support the Weglot project this key belongs to. Check that you are using the right project key.\",\n );\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 apiBaseUrl: (data.api_base_url || DEFAULT_API_BASE_URL).replace(/\\/+$/, \"\"),\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":";;;;;;;;AAQA,MAAM,uBAAuB;AAC7B,MAAa,uBAAuB;AACpC,MAAM,oBAAoB;AAE1B,MAAM,iBAAiB,UAAU;AAEjC,MAAM,cAAc;AAEpB,MAAM,aAAa;AACnB,MAAa,wBAAwB;AACrC,MAAa,2BAA2B;AAExC,MAAM,uBAAuB;;;AA+C7B,IAAa,+BAAb,cAAkD,MAAM;CACtD,YACE,AAASA,MACT,AAASC,IACT;AACA,QAAM,sCAAsC,KAAK,QAAQ,GAAG,IAAI;EAHvD;EACA;AAGT,OAAK,OAAO;;;;AAKhB,IAAM,sBAAN,cAAkC,MAAM;AAExC,MAAM,cAAc,SAClB,KAAK,QAAQ,2EAA2E,IAAS;AAEnG,MAAM,gBAAgB,OACpB,IAAI,SAAe,YAAY,WAAW,SAAS,GAAG,CAAC;AAEzD,IAAa,kBAAb,MAA6B;CAC3B,AAAiB;CAEjB,YACE,AAAiBC,QACjB,YACA;EAFiB;AAGjB,OAAK,aAAa,cAAc;;;CAIlC,MAAM,UAAU,QAAqD;EACnE,MAAM,QAAQ,OAAO,OAAO,YAAY;EACxC,MAAM,WAAW,MAAM,MAAM,GAAG,KAAK,WAAW,YAAY,SAAS;GACnE,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,QAAQ;IACR,eAAe,OAAO,KAAK;IAC5B;GACD,MAAM,KAA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AK,aACzB,KAAK,YACN,CAAC,CACH;GACF"}
|
|
1
|
+
{"version":3,"file":"api-client.mjs","names":["from: string","to: string","apiKey: string","words: (string | null)[]","everAccepted: boolean[]","misses: number[]","lastError: unknown"],"sources":["../../../src/translators/weglot/api-client.ts"],"sourcesContent":["/**\n * Weglot API client. Weglot translates with an LLM: a word not translated yet\n * comes back null and is queued, so callers poll until it is ready.\n */\n\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport { WORD_TYPE } from \"./definitions/definitions.generated\";\n\nconst DEFAULT_SETTINGS_URL = \"https://api.weglot.com/project-settings\";\nexport const DEFAULT_API_BASE_URL = \"https://api.weglot.com\";\nconst SUPPORTED_PRODUCT = \"2.0\";\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// Tags the words in the dashboard with where they came from.\nconst WORD_LABEL = \"translate-react\";\nexport const MAX_WORDS_PER_REQUEST = 100;\nexport const DEFAULT_POLL_INTERVAL_MS = 5_000;\n// The API sometimes takes new words only on a second request; one still without an id after this many is refused.\nconst REFUSED_AFTER_MISSES = 2;\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 /** The project's regional API host, e.g. https://eu.api.weglot.com. */\n apiBaseUrl: string;\n /** Inline elements allowed in a segment; absent on older projects. */\n translationEngine?: number;\n};\n\nexport type TranslateParams = {\n from: string;\n to: string;\n words: string[];\n /** Word type per word; body text when omitted. */\n types?: number[];\n /** Marks a request made while a page renders, as opposed to a build. */\n live?: boolean;\n};\n\nexport type TranslateResponse = {\n /** Null while not translated yet. */\n words: (string | null)[];\n /** Whether the API took each word in: it was translated or given an id. */\n accepted: boolean[];\n};\n\nexport type PolledTranslation = {\n /** Null for words still queued at the deadline or refused. */\n words: (string | null)[];\n /** Indexes of the words the API will not translate. */\n refused: number[];\n};\n\nexport type PollOptions = {\n /** Epoch ms after which words still queued are given up on. */\n deadline: number;\n pollIntervalMs?: number;\n sleep?: (ms: number) => Promise<void>;\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\n/** A 400 the API gives a whole request when one of its words is unreadable. */\nclass RefusedRequestError extends Error {}\n\nconst wellFormed = (text: string) =>\n text.replace(/[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/g, \"\\uFFFD\");\n\nconst defaultSleep = (ms: number) =>\n new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nexport class WeglotApiClient {\n private readonly apiBaseUrl: string;\n\n constructor(\n private readonly apiKey: string,\n apiBaseUrl?: string,\n ) {\n this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;\n }\n\n /** One request. A word not translated yet comes back null, with an id once the API has queued it. */\n async translate(params: TranslateParams): Promise<TranslateResponse> {\n const query = params.live ? \"?live=1\" : \"\";\n const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n Authorization: `Key ${this.apiKey}`,\n },\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 // A lone surrogate makes the API refuse the whole request.\n w: wellFormed(w),\n l: [WORD_LABEL],\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 if (response.status === 400) {\n throw new RefusedRequestError(\n `Weglot translate API refused the request (400): ${body || \"no response body\"}`,\n );\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 {\n to_words?: (string | null)[];\n ids?: (string | null)[];\n };\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 const ids = Array.isArray(data.ids) ? data.ids : null;\n\n return {\n words: toWords,\n accepted: toWords.map(\n (value, index) => value !== null || ids === null || (ids[index] ?? null) !== null,\n ),\n };\n }\n\n /** Re-polls words until translated or the deadline. A failed request leaves\n * its words pending, so one error never discards what was already received. */\n async translateUntilReady(\n params: TranslateParams,\n { deadline, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, sleep = defaultSleep }: PollOptions,\n ): Promise<PolledTranslation> {\n const words: (string | null)[] = new Array(params.words.length).fill(null);\n const everAccepted: boolean[] = new Array(params.words.length).fill(false);\n const misses: number[] = new Array(params.words.length).fill(0);\n const refused = new Set<number>();\n let pending = params.words.map((_, index) => index);\n let received = false;\n let anyAccepted = false;\n let lastError: unknown;\n\n while (true) {\n for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) {\n try {\n const answers = await this.sendIsolatingRefused(\n params,\n pending.slice(i, i + MAX_WORDS_PER_REQUEST),\n refused,\n );\n received = true;\n for (const { index, word, accepted } of answers) {\n words[index] = word;\n if (accepted) {\n everAccepted[index] = true;\n anyAccepted = true;\n } else {\n misses[index]++;\n }\n }\n } catch (error) {\n if (error instanceof UnsupportedLanguagePairError) throw error;\n lastError = error;\n }\n }\n\n // Only while the API takes other words in: otherwise it is not ready, and the words stay pending.\n if (anyAccepted) {\n for (const index of pending) {\n if (!everAccepted[index] && misses[index] >= REFUSED_AFTER_MISSES) refused.add(index);\n }\n }\n pending = pending.filter((index) => words[index] === null && !refused.has(index));\n\n const remaining = deadline - Date.now();\n if (pending.length === 0 || remaining <= 0) {\n // Nothing ever got through: a key or quota problem, not a slow queue.\n if (!received && lastError !== undefined) throw lastError;\n return { words, refused: [...refused].sort((a, b) => a - b) };\n }\n await sleep(Math.min(pollIntervalMs, remaining));\n }\n }\n\n /** Splits a request the API refuses until the unreadable word is alone, then marks it refused. */\n private async sendIsolatingRefused(\n params: TranslateParams,\n indexes: number[],\n refused: Set<number>,\n ): Promise<{ index: number; word: string | null; accepted: boolean }[]> {\n try {\n const { words, accepted } = await withTimeout(\n this.translate({\n from: params.from,\n to: params.to,\n words: indexes.map((index) => params.words[index]),\n types: params.types && indexes.map((index) => params.types![index]),\n }),\n DEFAULT_TIMEOUTS.AI_API,\n `Weglot API translation to ${params.to}`,\n );\n return indexes.map((index, k) => ({ index, word: words[k], accepted: accepted[k] }));\n } catch (error) {\n if (!(error instanceof RefusedRequestError)) throw error;\n if (indexes.length === 1) {\n refused.add(indexes[0]);\n return [];\n }\n const middle = Math.ceil(indexes.length / 2);\n return [\n ...(await this.sendIsolatingRefused(params, indexes.slice(0, middle), refused)),\n ...(await this.sendIsolatingRefused(params, indexes.slice(middle), refused)),\n ];\n }\n }\n\n async fetchSettings(): Promise<WeglotProjectSettings> {\n const response = await withTimeout(\n // Overridable to point at another settings endpoint, such as a Weglot API that reads the key only from the header.\n fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, {\n headers: { Accept: \"application/json\", Authorization: `Key ${this.apiKey}` },\n }),\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 product?: string;\n api_base_url?: string;\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.product !== SUPPORTED_PRODUCT) {\n throw new Error(\n \"@weglot/translate-react does not support the Weglot project this key belongs to. Check that you are using the right project key.\",\n );\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 apiBaseUrl: (data.api_base_url || DEFAULT_API_BASE_URL).replace(/\\/+$/, \"\"),\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":";;;;;;;;AAQA,MAAM,uBAAuB;AAC7B,MAAa,uBAAuB;AACpC,MAAM,oBAAoB;AAE1B,MAAM,iBAAiB,UAAU;AAEjC,MAAM,cAAc;AAEpB,MAAM,aAAa;AACnB,MAAa,wBAAwB;AACrC,MAAa,2BAA2B;AAExC,MAAM,uBAAuB;;;AA+C7B,IAAa,+BAAb,cAAkD,MAAM;CACtD,YACE,AAASA,MACT,AAASC,IACT;AACA,QAAM,sCAAsC,KAAK,QAAQ,GAAG,IAAI;EAHvD;EACA;AAGT,OAAK,OAAO;;;;AAKhB,IAAM,sBAAN,cAAkC,MAAM;AAExC,MAAM,cAAc,SAClB,KAAK,QAAQ,2EAA2E,IAAS;AAEnG,MAAM,gBAAgB,OACpB,IAAI,SAAe,YAAY,WAAW,SAAS,GAAG,CAAC;AAEzD,IAAa,kBAAb,MAA6B;CAC3B,AAAiB;CAEjB,YACE,AAAiBC,QACjB,YACA;EAFiB;AAGjB,OAAK,aAAa,cAAc;;;CAIlC,MAAM,UAAU,QAAqD;EACnE,MAAM,QAAQ,OAAO,OAAO,YAAY;EACxC,MAAM,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