@weglot/translate-react 0.2.0 → 0.2.2

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.
Files changed (59) hide show
  1. package/README.md +78 -15
  2. package/build/metadata/manager.cjs +18 -5
  3. package/build/metadata/manager.mjs +17 -5
  4. package/build/metadata/manager.mjs.map +1 -1
  5. package/build/plugin/build-translator.cjs +2 -1
  6. package/build/plugin/build-translator.mjs +2 -1
  7. package/build/plugin/build-translator.mjs.map +1 -1
  8. package/build/plugin/next-compiler-loader.cjs +1 -4
  9. package/build/plugin/next-compiler-loader.mjs +2 -5
  10. package/build/plugin/next-compiler-loader.mjs.map +1 -1
  11. package/build/plugin/next-traces.cjs +38 -0
  12. package/build/plugin/next-traces.mjs +36 -0
  13. package/build/plugin/next-traces.mjs.map +1 -0
  14. package/build/plugin/next.cjs +30 -10
  15. package/build/plugin/next.d.cts.map +1 -1
  16. package/build/plugin/next.d.mts.map +1 -1
  17. package/build/plugin/next.mjs +28 -11
  18. package/build/plugin/next.mjs.map +1 -1
  19. package/build/plugin/transform/process-file.cjs +9 -0
  20. package/build/plugin/transform/process-file.mjs +9 -0
  21. package/build/plugin/transform/process-file.mjs.map +1 -1
  22. package/build/plugin/unplugin.cjs +3 -5
  23. package/build/plugin/unplugin.mjs +4 -6
  24. package/build/plugin/unplugin.mjs.map +1 -1
  25. package/build/react/server/ServerWeglotProvider.d.mts +2 -2
  26. package/build/react/shared/LocaleSwitcher.d.mts +2 -2
  27. package/build/react/shared/WeglotContext.cjs +18 -2
  28. package/build/react/shared/WeglotContext.d.cts +1 -0
  29. package/build/react/shared/WeglotContext.d.cts.map +1 -1
  30. package/build/react/shared/WeglotContext.d.mts +1 -0
  31. package/build/react/shared/WeglotContext.d.mts.map +1 -1
  32. package/build/react/shared/WeglotContext.mjs +18 -2
  33. package/build/react/shared/WeglotContext.mjs.map +1 -1
  34. package/build/react/shared/WeglotProvider.cjs +4 -0
  35. package/build/react/shared/WeglotProvider.d.cts.map +1 -1
  36. package/build/react/shared/WeglotProvider.d.mts +2 -2
  37. package/build/react/shared/WeglotProvider.d.mts.map +1 -1
  38. package/build/react/shared/WeglotProvider.mjs +4 -0
  39. package/build/react/shared/WeglotProvider.mjs.map +1 -1
  40. package/build/runtime/translate-dynamic.cjs +1 -1
  41. package/build/runtime/translate-dynamic.mjs +1 -1
  42. package/build/runtime/translate-dynamic.mjs.map +1 -1
  43. package/build/translators/translation-service.cjs +3 -2
  44. package/build/translators/translation-service.mjs +3 -2
  45. package/build/translators/translation-service.mjs.map +1 -1
  46. package/build/translators/weglot/api-client.cjs +62 -34
  47. package/build/translators/weglot/api-client.mjs +62 -34
  48. package/build/translators/weglot/api-client.mjs.map +1 -1
  49. package/build/translators/weglot/translator.cjs +19 -1
  50. package/build/translators/weglot/translator.mjs +19 -1
  51. package/build/translators/weglot/translator.mjs.map +1 -1
  52. package/build/types.d.cts +7 -1
  53. package/build/types.d.cts.map +1 -1
  54. package/build/types.d.mts +7 -1
  55. package/build/types.d.mts.map +1 -1
  56. package/build/utils/package-version.cjs +12 -0
  57. package/build/utils/package-version.mjs +12 -0
  58. package/build/utils/package-version.mjs.map +1 -0
  59. package/package.json +4 -2
@@ -14,6 +14,7 @@ const REQUEST_URL = "https://compiler.weglot.com/";
14
14
  const WORD_LABEL = "translate-react";
15
15
  const MAX_WORDS_PER_REQUEST = 100;
16
16
  const DEFAULT_POLL_INTERVAL_MS = 5e3;
17
+ const REFUSED_AFTER_MISSES = 2;
17
18
  /** The API validates the pair independently of the project's languages, so
18
19
  * `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */
19
20
  var UnsupportedLanguagePairError = class extends Error {
@@ -24,6 +25,9 @@ var UnsupportedLanguagePairError = class extends Error {
24
25
  this.name = "UnsupportedLanguagePairError";
25
26
  }
26
27
  };
28
+ /** A 400 the API gives a whole request when one of its words is unreadable. */
29
+ var RefusedRequestError = class extends Error {};
30
+ const wellFormed = (text) => text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
27
31
  const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
28
32
  var WeglotApiClient = class {
29
33
  apiBaseUrl;
@@ -31,10 +35,7 @@ var WeglotApiClient = class {
31
35
  this.apiKey = apiKey;
32
36
  this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;
33
37
  }
34
- /**
35
- * One request. A word the API has queued comes back null; a word it will
36
- * never translate comes back as its source text.
37
- */
38
+ /** One request. A word not translated yet comes back null, with an id once the API has queued it. */
38
39
  async translate(params) {
39
40
  const query = params.live ? "?live=1" : "";
40
41
  const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {
@@ -50,7 +51,7 @@ var WeglotApiClient = class {
50
51
  request_url: REQUEST_URL,
51
52
  words: params.words.map((w, index) => ({
52
53
  t: params.types?.[index] ?? WORD_TYPE_TEXT,
53
- w,
54
+ w: wellFormed(w),
54
55
  l: [WORD_LABEL]
55
56
  }))
56
57
  })
@@ -58,56 +59,83 @@ var WeglotApiClient = class {
58
59
  if (!response.ok) {
59
60
  const body = await response.text().catch(() => "");
60
61
  if (response.status === 400 && /not valid languages pair/i.test(body)) throw new UnsupportedLanguagePairError(params.from, params.to);
62
+ if (response.status === 400) throw new RefusedRequestError(`Weglot translate API refused the request (400): ${body || "no response body"}`);
61
63
  throw new Error(`Weglot translate API error (${response.status}): ${body || "no response body"}`);
62
64
  }
63
65
  const data = await response.json();
64
66
  const toWords = data.to_words;
65
67
  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"})`);
66
68
  const ids = Array.isArray(data.ids) ? data.ids : null;
67
- return toWords.map((value, index) => {
68
- if (value !== null) return value;
69
- return ids === null || (ids[index] ?? null) !== null ? null : params.words[index];
70
- });
69
+ return {
70
+ words: toWords,
71
+ accepted: toWords.map((value, index) => value !== null || ids === null || (ids[index] ?? null) !== null)
72
+ };
71
73
  }
72
- /** Re-polls queued words until ready or the deadline, then returns null for
73
- * the rest. A failed request leaves its words queued for the next round, so
74
- * one error never discards what was already received. */
74
+ /** Re-polls words until translated or the deadline. A failed request leaves
75
+ * its words pending, so one error never discards what was already received. */
75
76
  async translateUntilReady(params, { deadline, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, sleep = defaultSleep }) {
76
- const results = new Array(params.words.length).fill(null);
77
+ const words = new Array(params.words.length).fill(null);
78
+ const everAccepted = new Array(params.words.length).fill(false);
79
+ const misses = new Array(params.words.length).fill(0);
80
+ const refused = /* @__PURE__ */ new Set();
77
81
  let pending = params.words.map((_, index) => index);
78
82
  let received = false;
83
+ let anyAccepted = false;
79
84
  let lastError;
80
85
  while (true) {
81
- const stillPending = [];
82
- for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) {
83
- const chunk = pending.slice(i, i + MAX_WORDS_PER_REQUEST);
84
- try {
85
- const translated = await withTimeout(this.translate({
86
- from: params.from,
87
- to: params.to,
88
- words: chunk.map((index) => params.words[index]),
89
- types: params.types && chunk.map((index) => params.types[index])
90
- }), DEFAULT_TIMEOUTS.AI_API, `Weglot API translation to ${params.to}`);
91
- received = true;
92
- chunk.forEach((index, k) => {
93
- if (translated[k] === null) stillPending.push(index);
94
- else results[index] = translated[k];
95
- });
96
- } catch (error) {
97
- if (error instanceof UnsupportedLanguagePairError) throw error;
98
- lastError = error;
99
- stillPending.push(...chunk);
86
+ for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) try {
87
+ const answers = await this.sendIsolatingRefused(params, pending.slice(i, i + MAX_WORDS_PER_REQUEST), refused);
88
+ received = true;
89
+ for (const { index, word, accepted } of answers) {
90
+ words[index] = word;
91
+ if (accepted) {
92
+ everAccepted[index] = true;
93
+ anyAccepted = true;
94
+ } else misses[index]++;
100
95
  }
96
+ } catch (error) {
97
+ if (error instanceof UnsupportedLanguagePairError) throw error;
98
+ lastError = error;
99
+ }
100
+ if (anyAccepted) {
101
+ for (const index of pending) if (!everAccepted[index] && misses[index] >= REFUSED_AFTER_MISSES) refused.add(index);
101
102
  }
102
- pending = stillPending;
103
+ pending = pending.filter((index) => words[index] === null && !refused.has(index));
103
104
  const remaining = deadline - Date.now();
104
105
  if (pending.length === 0 || remaining <= 0) {
105
106
  if (!received && lastError !== void 0) throw lastError;
106
- return results;
107
+ return {
108
+ words,
109
+ refused: [...refused].sort((a, b) => a - b)
110
+ };
107
111
  }
108
112
  await sleep(Math.min(pollIntervalMs, remaining));
109
113
  }
110
114
  }
115
+ /** Splits a request the API refuses until the unreadable word is alone, then marks it refused. */
116
+ async sendIsolatingRefused(params, indexes, refused) {
117
+ try {
118
+ const { words, accepted } = await withTimeout(this.translate({
119
+ from: params.from,
120
+ to: params.to,
121
+ words: indexes.map((index) => params.words[index]),
122
+ types: params.types && indexes.map((index) => params.types[index])
123
+ }), DEFAULT_TIMEOUTS.AI_API, `Weglot API translation to ${params.to}`);
124
+ return indexes.map((index, k) => ({
125
+ index,
126
+ word: words[k],
127
+ accepted: accepted[k]
128
+ }));
129
+ } catch (error) {
130
+ if (!(error instanceof RefusedRequestError)) throw error;
131
+ if (indexes.length === 1) {
132
+ refused.add(indexes[0]);
133
+ return [];
134
+ }
135
+ const middle = Math.ceil(indexes.length / 2);
136
+ return [...await this.sendIsolatingRefused(params, indexes.slice(0, middle), refused), ...await this.sendIsolatingRefused(params, indexes.slice(middle), refused)];
137
+ }
138
+ }
111
139
  async fetchSettings() {
112
140
  const response = await withTimeout(fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, { headers: { Accept: "application/json" } }), DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
113
141
  if (!response.ok) throw new Error(`Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`);
@@ -1 +1 @@
1
- {"version":3,"file":"api-client.mjs","names":["from: string","to: string","apiKey: string","results: (string | null)[]","lastError: unknown","stillPending: number[]"],"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\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 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\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 /**\n * One request. A word the API has queued comes back null; a word it will\n * never translate comes back as its source text.\n */\n async translate(params: TranslateParams): Promise<(string | null)[]> {\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 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 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 toWords.map((value, index) => {\n if (value !== null) return value;\n // Null without an id was not queued: it will never be translated.\n const queued = ids === null || (ids[index] ?? null) !== null;\n return queued ? null : params.words[index];\n });\n }\n\n /** Re-polls queued words until ready or the deadline, then returns null for\n * the rest. A failed request leaves its words queued for the next round, so\n * 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<(string | null)[]> {\n const results: (string | null)[] = new Array(params.words.length).fill(null);\n let pending = params.words.map((_, index) => index);\n let received = false;\n let lastError: unknown;\n\n while (true) {\n const stillPending: number[] = [];\n for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) {\n const chunk = pending.slice(i, i + MAX_WORDS_PER_REQUEST);\n try {\n const translated = await withTimeout(\n this.translate({\n from: params.from,\n to: params.to,\n words: chunk.map((index) => params.words[index]),\n types: params.types && chunk.map((index) => params.types![index]),\n }),\n DEFAULT_TIMEOUTS.AI_API,\n `Weglot API translation to ${params.to}`,\n );\n received = true;\n chunk.forEach((index, k) => {\n if (translated[k] === null) stillPending.push(index);\n else results[index] = translated[k];\n });\n } catch (error) {\n if (error instanceof UnsupportedLanguagePairError) throw error;\n lastError = error;\n stillPending.push(...chunk);\n }\n }\n pending = stillPending;\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 results;\n }\n await sleep(Math.min(pollIntervalMs, remaining));\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;;;AAiCxC,IAAa,+BAAb,cAAkD,MAAM;CACtD,YACE,AAASA,MACT,AAASC,IACT;AACA,QAAM,sCAAsC,KAAK,QAAQ,GAAG,IAAI;EAHvD;EACA;AAGT,OAAK,OAAO;;;AAIhB,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;;;;;;CAOlC,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,KAAK,UAAU;IACnB,QAAQ,OAAO;IACf,MAAM,OAAO;IACb,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K,SAAS,KAAK,eAAe,KAAK,YAAY;GAC5E,aAAa,KAAK,gBAAgB,sBAAsB,QAAQ,QAAQ,GAAG;GAC3E,mBAAmB,KAAK;GACxB,YAAY,OAAO,YACjB,UAAU,KAAK,SAAS,CACtB,KAAK,eAAe,KAAK,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.\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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AK,UAAU,QAAQ,SAAS,KAAK,YAAY,MAAM;AAEzE,SAAO;GACL,cAAc,KAAK;GACnB,eAAe,UAAU,KAAK,SAAS,KAAK,eAAe,KAAK,YAAY;GAC5E,aAAa,KAAK,gBAAgB,sBAAsB,QAAQ,QAAQ,GAAG;GAC3E,mBAAmB,KAAK;GACxB,YAAY,OAAO,YACjB,UAAU,KAAK,SAAS,CACtB,KAAK,eAAe,KAAK,aACzB,KAAK,YACN,CAAC,CACH;GACF"}
@@ -6,6 +6,8 @@ const require_wire_format = require('./wire-format.cjs');
6
6
  var WeglotTranslator = class {
7
7
  client;
8
8
  engine;
9
+ /** Texts settled as their source this process, per locale, so they are not polled again. */
10
+ settledAsSource = /* @__PURE__ */ new Map();
9
11
  constructor(config, logger, client, pollOptions = {}) {
10
12
  this.config = config;
11
13
  this.logger = logger;
@@ -18,8 +20,14 @@ var WeglotTranslator = class {
18
20
  this.logger.debug(`Weglot translate() called for ${locale} with ${hashes.length} entries`);
19
21
  const translations = {};
20
22
  const protectedEntries = [];
23
+ const settled = this.settledAsSource.get(locale) ?? /* @__PURE__ */ new Set();
24
+ this.settledAsSource.set(locale, settled);
21
25
  for (const hash of hashes) {
22
26
  const sourceText = entriesMap[hash].text;
27
+ if (settled.has(sourceText)) {
28
+ translations[hash] = sourceText;
29
+ continue;
30
+ }
23
31
  const { wire, restore, encodable } = require_wire_format.encodeForApi(sourceText, this.engine);
24
32
  if (!encodable) {
25
33
  this.logger.warn(`Weglot translation engine ${this.engine} cannot carry the markup in hash "${hash}"; falling back to source text.`);
@@ -33,7 +41,7 @@ var WeglotTranslator = class {
33
41
  });
34
42
  }
35
43
  if (protectedEntries.length === 0) return translations;
36
- const translated = await this.client.translateUntilReady({
44
+ const { words: translated, refused } = await this.client.translateUntilReady({
37
45
  from: this.config.sourceLocale,
38
46
  to: this.config.apiLocales?.[locale] ?? locale,
39
47
  words: protectedEntries.map((entry) => entry.text)
@@ -41,10 +49,15 @@ var WeglotTranslator = class {
41
49
  ...this.pollOptions,
42
50
  deadline: Date.now() + this.config.translationTimeoutMs
43
51
  });
52
+ const refusedIndexes = new Set(refused);
44
53
  let queued = 0;
45
54
  protectedEntries.forEach((entry, index) => {
46
55
  const result = translated[index];
47
56
  const sourceText = entriesMap[entry.hash].text;
57
+ if (refusedIndexes.has(index)) {
58
+ translations[entry.hash] = sourceText;
59
+ return;
60
+ }
48
61
  if (result === null) {
49
62
  queued++;
50
63
  return;
@@ -58,6 +71,11 @@ var WeglotTranslator = class {
58
71
  translations[entry.hash] = sourceText;
59
72
  } else translations[entry.hash] = restored;
60
73
  });
74
+ for (const [hash, text] of Object.entries(translations)) if (text === entriesMap[hash].text) settled.add(text);
75
+ if (refused.length > 0) {
76
+ const examples = refused.slice(0, 5).map((index) => `"${entriesMap[protectedEntries[index].hash].text.slice(0, 80)}"`).join(", ");
77
+ this.logger.warn(`Weglot will not translate ${refused.length} ${locale} string(s), served untranslated: ${examples}${refused.length > 5 ? ", ..." : ""}`);
78
+ }
61
79
  if (queued > 0) this.logger.warn(`${queued} ${locale} translation(s) are still being generated by Weglot after ${Math.round(this.config.translationTimeoutMs / 1e3)}s. Translations already received are cached, so running again picks up the rest.`);
62
80
  return translations;
63
81
  }
@@ -6,6 +6,8 @@ import { encodeForApi } from "./wire-format.mjs";
6
6
  var WeglotTranslator = class {
7
7
  client;
8
8
  engine;
9
+ /** Texts settled as their source this process, per locale, so they are not polled again. */
10
+ settledAsSource = /* @__PURE__ */ new Map();
9
11
  constructor(config, logger, client, pollOptions = {}) {
10
12
  this.config = config;
11
13
  this.logger = logger;
@@ -18,8 +20,14 @@ var WeglotTranslator = class {
18
20
  this.logger.debug(`Weglot translate() called for ${locale} with ${hashes.length} entries`);
19
21
  const translations = {};
20
22
  const protectedEntries = [];
23
+ const settled = this.settledAsSource.get(locale) ?? /* @__PURE__ */ new Set();
24
+ this.settledAsSource.set(locale, settled);
21
25
  for (const hash of hashes) {
22
26
  const sourceText = entriesMap[hash].text;
27
+ if (settled.has(sourceText)) {
28
+ translations[hash] = sourceText;
29
+ continue;
30
+ }
23
31
  const { wire, restore, encodable } = encodeForApi(sourceText, this.engine);
24
32
  if (!encodable) {
25
33
  this.logger.warn(`Weglot translation engine ${this.engine} cannot carry the markup in hash "${hash}"; falling back to source text.`);
@@ -33,7 +41,7 @@ var WeglotTranslator = class {
33
41
  });
34
42
  }
35
43
  if (protectedEntries.length === 0) return translations;
36
- const translated = await this.client.translateUntilReady({
44
+ const { words: translated, refused } = await this.client.translateUntilReady({
37
45
  from: this.config.sourceLocale,
38
46
  to: this.config.apiLocales?.[locale] ?? locale,
39
47
  words: protectedEntries.map((entry) => entry.text)
@@ -41,10 +49,15 @@ var WeglotTranslator = class {
41
49
  ...this.pollOptions,
42
50
  deadline: Date.now() + this.config.translationTimeoutMs
43
51
  });
52
+ const refusedIndexes = new Set(refused);
44
53
  let queued = 0;
45
54
  protectedEntries.forEach((entry, index) => {
46
55
  const result = translated[index];
47
56
  const sourceText = entriesMap[entry.hash].text;
57
+ if (refusedIndexes.has(index)) {
58
+ translations[entry.hash] = sourceText;
59
+ return;
60
+ }
48
61
  if (result === null) {
49
62
  queued++;
50
63
  return;
@@ -58,6 +71,11 @@ var WeglotTranslator = class {
58
71
  translations[entry.hash] = sourceText;
59
72
  } else translations[entry.hash] = restored;
60
73
  });
74
+ for (const [hash, text] of Object.entries(translations)) if (text === entriesMap[hash].text) settled.add(text);
75
+ if (refused.length > 0) {
76
+ const examples = refused.slice(0, 5).map((index) => `"${entriesMap[protectedEntries[index].hash].text.slice(0, 80)}"`).join(", ");
77
+ this.logger.warn(`Weglot will not translate ${refused.length} ${locale} string(s), served untranslated: ${examples}${refused.length > 5 ? ", ..." : ""}`);
78
+ }
61
79
  if (queued > 0) this.logger.warn(`${queued} ${locale} translation(s) are still being generated by Weglot after ${Math.round(this.config.translationTimeoutMs / 1e3)}s. Translations already received are cached, so running again picks up the rest.`);
62
80
  return translations;
63
81
  }
@@ -1 +1 @@
1
- {"version":3,"file":"translator.mjs","names":["config: WeglotTranslatorConfig","logger: Logger","pollOptions: Omit<PollOptions, \"deadline\">","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 { type PollOptions, WeglotApiClient } from \"./api-client\";\nimport { encodeForApi, type RestoredTranslation } from \"./wire-format\";\nimport { resolveTranslationEngine } from \"./engine\";\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; the modern engine when absent. */\n translationEngine?: number;\n /** The project's regional API host, from the project settings. */\n apiBaseUrl?: string;\n /** How long to wait for queued translations before leaving them out. */\n translationTimeoutMs: 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 private readonly pollOptions: Omit<PollOptions, \"deadline\"> = {},\n ) {\n this.client = client ?? new WeglotApiClient(config.apiKey, config.apiBaseUrl);\n this.engine = resolveTranslationEngine(config.translationEngine);\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 if (protectedEntries.length === 0) return translations;\n\n const translated = await this.client.translateUntilReady(\n {\n from: this.config.sourceLocale,\n to: this.config.apiLocales?.[locale] ?? locale,\n words: protectedEntries.map((entry) => entry.text),\n },\n {\n ...this.pollOptions,\n deadline: Date.now() + this.config.translationTimeoutMs,\n },\n );\n\n let queued = 0;\n protectedEntries.forEach((entry, index) => {\n const result = translated[index];\n const sourceText = entriesMap[entry.hash].text;\n\n if (result === null) {\n // Left out rather than filled with source, which would be cached.\n queued++;\n return;\n }\n\n const { text: restored, damaged } = entry.restore(result);\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 (result === 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 if (queued > 0) {\n this.logger.warn(\n `${queued} ${locale} translation(s) are still being generated by Weglot after ${Math.round(this.config.translationTimeoutMs / 1000)}s. Translations already received are cached, so running again picks up the rest.`,\n );\n }\n\n return translations;\n }\n}\n"],"mappings":";;;;;AAoBA,IAAa,mBAAb,MAA4E;CAC1E,AAAiB;CACjB,AAAiB;CAEjB,YACE,AAASA,QACT,AAAiBC,QACjB,QACA,AAAiBC,cAA6C,EAAE,EAChE;EAJS;EACQ;EAEA;AAEjB,OAAK,SAAS,UAAU,IAAI,gBAAgB,OAAO,QAAQ,OAAO,WAAW;AAC7E,OAAK,SAAS,yBAAyB,OAAO,kBAAkB;;CAGlE,MAAM,UACJ,QACA,YACiC;EACjC,MAAM,SAAS,OA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O,4DAA4D,KAAK,MAAM,KAAK,OAAO,uBAAuB,IAAK,CAAC,kFACrI;AAGH,SAAO"}
1
+ {"version":3,"file":"translator.mjs","names":["config: WeglotTranslatorConfig","logger: Logger","pollOptions: Omit<PollOptions, \"deadline\">","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 { type PollOptions, WeglotApiClient } from \"./api-client\";\nimport { encodeForApi, type RestoredTranslation } from \"./wire-format\";\nimport { resolveTranslationEngine } from \"./engine\";\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; the modern engine when absent. */\n translationEngine?: number;\n /** The project's regional API host, from the project settings. */\n apiBaseUrl?: string;\n /** How long to wait for queued translations before leaving them out. */\n translationTimeoutMs: number;\n}\n\nexport class WeglotTranslator implements Translator<WeglotTranslatorConfig> {\n private readonly client: WeglotApiClient;\n private readonly engine: number;\n /** Texts settled as their source this process, per locale, so they are not polled again. */\n private readonly settledAsSource = new Map<LocaleCode, Set<string>>();\n\n constructor(\n readonly config: WeglotTranslatorConfig,\n private readonly logger: Logger,\n client?: WeglotApiClient,\n private readonly pollOptions: Omit<PollOptions, \"deadline\"> = {},\n ) {\n this.client = client ?? new WeglotApiClient(config.apiKey, config.apiBaseUrl);\n this.engine = resolveTranslationEngine(config.translationEngine);\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 const settled = this.settledAsSource.get(locale) ?? new Set<string>();\n this.settledAsSource.set(locale, settled);\n\n for (const hash of hashes) {\n const sourceText = entriesMap[hash].text;\n if (settled.has(sourceText)) {\n translations[hash] = sourceText;\n continue;\n }\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 if (protectedEntries.length === 0) return translations;\n\n const { words: translated, refused } = await this.client.translateUntilReady(\n {\n from: this.config.sourceLocale,\n to: this.config.apiLocales?.[locale] ?? locale,\n words: protectedEntries.map((entry) => entry.text),\n },\n {\n ...this.pollOptions,\n deadline: Date.now() + this.config.translationTimeoutMs,\n },\n );\n\n const refusedIndexes = new Set(refused);\n let queued = 0;\n protectedEntries.forEach((entry, index) => {\n const result = translated[index];\n const sourceText = entriesMap[entry.hash].text;\n\n if (refusedIndexes.has(index)) {\n translations[entry.hash] = sourceText;\n return;\n }\n if (result === null) {\n // Left out rather than filled with source, which would be cached.\n queued++;\n return;\n }\n\n const { text: restored, damaged } = entry.restore(result);\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 (result === 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 for (const [hash, text] of Object.entries(translations)) {\n if (text === entriesMap[hash].text) settled.add(text);\n }\n\n if (refused.length > 0) {\n const examples = refused\n .slice(0, 5)\n .map((index) => `\"${entriesMap[protectedEntries[index].hash].text.slice(0, 80)}\"`)\n .join(\", \");\n this.logger.warn(\n `Weglot will not translate ${refused.length} ${locale} string(s), served untranslated: ${examples}${refused.length > 5 ? \", ...\" : \"\"}`,\n );\n }\n\n if (queued > 0) {\n this.logger.warn(\n `${queued} ${locale} translation(s) are still being generated by Weglot after ${Math.round(this.config.translationTimeoutMs / 1000)}s. Translations already received are cached, so running again picks up the rest.`,\n );\n }\n\n return translations;\n }\n}\n"],"mappings":";;;;;AAoBA,IAAa,mBAAb,MAA4E;CAC1E,AAAiB;CACjB,AAAiB;;CAEjB,AAAiB,kCAAkB,IAAI,KAA8B;CAErE,YACE,AAASA,QACT,AAAiBC,QACjB,QACA,AAAiBC,cAA6C,EAAE,EAChE;EAJS;EACQ;EAEA;AAEjB,OAAK,SAAS,UAAU,IAAI,gBAAgB,OAAO,QAAQ,OAAO,WAAW;AAC7E,OAAK,SAAS,yBAAyB,OAAO,kBAAkB;;CAGlE,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;EAER,MAAM,UAAU,KAAK,gBAAgB,IAAI,OAAO,oBAAI,IAAI,KAAa;AACrE,OAAK,gBAAgB,IAAI,QAAQ,QAAQ;AAEzC,OAAK,MAAM,QAAQ,QAAQ;GACzB,MAAM,aAAa,WAAW,MAAM;AACpC,OAAI,QAAQ,IAAI,WAAW,EAAE;AAC3B,iBAAa,QAAQ;AACrB;;GAEF,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;IAA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CAAmC,WAAW,QAAQ,SAAS,IAAI,UAAU,KACpI;;AAGH,MAAI,SAAS,EACX,MAAK,OAAO,KACV,GAAG,OAAO,GAAG,OAAO,4DAA4D,KAAK,MAAM,KAAK,OAAO,uBAAuB,IAAK,CAAC,kFACrI;AAGH,SAAO"}
package/build/types.d.cts CHANGED
@@ -29,7 +29,7 @@ type LocalePersistenceConfig = {
29
29
  * Fields that are resolved internally (from the Weglot project settings or the
30
30
  * environment) rather than provided by users.
31
31
  */
32
- type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "apiBaseUrl" | "weglotDir";
32
+ type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "apiBaseUrl" | "weglotDir" | "metadataDir";
33
33
  /**
34
34
  * Configuration for @weglot/translate-react
35
35
  */
@@ -56,6 +56,12 @@ type WeglotConfig = {
56
56
  * @internal
57
57
  */
58
58
  weglotDir: string;
59
+ /**
60
+ * Overrides where the metadata database lives.
61
+ *
62
+ * @internal
63
+ */
64
+ metadataDir?: string;
59
65
  /**
60
66
  * Environment mode
61
67
  * Determines metadata file naming and translator behavior
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;AA2BA;AAMA;AAaA;AACO,UAtCU,YAAA,CAsCV;EAAc;;;;EADa,IAAA,EAAA,MAAA;EAAO;AAMzC;AAKA;;EA6CgB,MAAA,EAAA,MAAA;;;;;;AAkE4B,KA7IhC,uBAAA,GA6IgC;;UA7IoB;;;;;;KAMpD,oBAAA;;;;KAaA,mBAAA,GAAsB,QAChC,KAAK,cAAc;OACZ,QAAQ;;KAIL,iBAAA;;;;KAKA,YAAA;;;;;;;;;;;;;;;;;;;;;;;eA0BG;;;;;;;;;;;;;;;;;gBAmBC;;;;;;;;iBASC;;;cAIH,eAAe;;;;;;;;;;;;;;;;;;;;;;0BA2BH;;;;;;;;;;;;;;;;;;;;;;;qBA0BL"}
1
+ {"version":3,"file":"types.d.cts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;AA2BA;AAMA;AAcA;AACO,UAvCU,YAAA,CAuCV;EAAc;;;;EADa,IAAA,EAAA,MAAA;EAAO;AAMzC;AAKA;;EAoDgB,MAAA,EAAA,MAAA;;;;;;AAkE4B,KArJhC,uBAAA,GAqJgC;;UArJoB;;;;;;KAMpD,oBAAA;;;;KAcA,mBAAA,GAAsB,QAChC,KAAK,cAAc;OACZ,QAAQ;;KAIL,iBAAA;;;;KAKA,YAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eAiCG;;;;;;;;;;;;;;;;;gBAmBC;;;;;;;;iBASC;;;cAIH,eAAe;;;;;;;;;;;;;;;;;;;;;;0BA2BH;;;;;;;;;;;;;;;;;;;;;;;qBA0BL"}
package/build/types.d.mts CHANGED
@@ -29,7 +29,7 @@ type LocalePersistenceConfig = {
29
29
  * Fields that are resolved internally (from the Weglot project settings or the
30
30
  * environment) rather than provided by users.
31
31
  */
32
- type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "apiBaseUrl" | "weglotDir";
32
+ type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "apiBaseUrl" | "weglotDir" | "metadataDir";
33
33
  /**
34
34
  * Configuration for @weglot/translate-react
35
35
  */
@@ -56,6 +56,12 @@ type WeglotConfig = {
56
56
  * @internal
57
57
  */
58
58
  weglotDir: string;
59
+ /**
60
+ * Overrides where the metadata database lives.
61
+ *
62
+ * @internal
63
+ */
64
+ metadataDir?: string;
59
65
  /**
60
66
  * Environment mode
61
67
  * Determines metadata file naming and translator behavior
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;AA2BA;AAMA;AAaA;AACO,UAtCU,YAAA,CAsCV;EAAc;;;;EADa,IAAA,EAAA,MAAA;EAAO;AAMzC;AAKA;;EA6CgB,MAAA,EAAA,MAAA;;;;;;AAkE4B,KA7IhC,uBAAA,GA6IgC;;UA7IoB;;;;;;KAMpD,oBAAA;;;;KAaA,mBAAA,GAAsB,QAChC,KAAK,cAAc;OACZ,QAAQ;;KAIL,iBAAA;;;;KAKA,YAAA;;;;;;;;;;;;;;;;;;;;;;;eA0BG;;;;;;;;;;;;;;;;;gBAmBC;;;;;;;;iBASC;;;cAIH,eAAe;;;;;;;;;;;;;;;;;;;;;;0BA2BH;;;;;;;;;;;;;;;;;;;;;;;qBA0BL"}
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;AA2BA;AAMA;AAcA;AACO,UAvCU,YAAA,CAuCV;EAAc;;;;EADa,IAAA,EAAA,MAAA;EAAO;AAMzC;AAKA;;EAoDgB,MAAA,EAAA,MAAA;;;;;;AAkE4B,KArJhC,uBAAA,GAqJgC;;UArJoB;;;;;;KAMpD,oBAAA;;;;KAcA,mBAAA,GAAsB,QAChC,KAAK,cAAc;OACZ,QAAQ;;KAIL,iBAAA;;;;KAKA,YAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eAiCG;;;;;;;;;;;;;;;;;gBAmBC;;;;;;;;iBASC;;;cAIH,eAAe;;;;;;;;;;;;;;;;;;;;;;0BA2BH;;;;;;;;;;;;;;;;;;;;;;;qBA0BL"}
@@ -0,0 +1,12 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ let node_fs = require("node:fs");
3
+
4
+ //#region src/utils/package-version.ts
5
+ let version;
6
+ function packageVersion() {
7
+ version ??= JSON.parse((0, node_fs.readFileSync)(new URL("../../package.json", require("url").pathToFileURL(__filename).href), "utf8")).version;
8
+ return version;
9
+ }
10
+
11
+ //#endregion
12
+ exports.packageVersion = packageVersion;
@@ -0,0 +1,12 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ //#region src/utils/package-version.ts
4
+ let version;
5
+ function packageVersion() {
6
+ version ??= JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
7
+ return version;
8
+ }
9
+
10
+ //#endregion
11
+ export { packageVersion };
12
+ //# sourceMappingURL=package-version.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package-version.mjs","names":["version: string | undefined"],"sources":["../../src/utils/package-version.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\n\nlet version: string | undefined;\n\nexport function packageVersion(): string {\n version ??= JSON.parse(\n readFileSync(new URL(\"../../package.json\", import.meta.url), \"utf8\"),\n ).version as string;\n return version;\n}\n"],"mappings":";;;AAEA,IAAIA;AAEJ,SAAgB,iBAAyB;AACvC,aAAY,KAAK,MACf,aAAa,IAAI,IAAI,sBAAsB,OAAO,KAAK,IAAI,EAAE,OAAO,CACrE,CAAC;AACF,QAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weglot/translate-react",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Automatic Weglot translation for React and Next.js apps, detected from your JSX at build time",
5
5
  "sideEffects": false,
6
6
  "type": "module",
@@ -190,9 +190,10 @@
190
190
  "scripts": {
191
191
  "dev": "tsdown --watch",
192
192
  "build": "pnpm typecheck && tsdown",
193
- "typecheck": "tsc --noEmit",
193
+ "typecheck": "tsc --noEmit && tsc -p e2e/tsconfig.json",
194
194
  "clean": "rm -rf build",
195
195
  "test": "vitest --run",
196
+ "test:e2e": "vitest --run --config vitest.e2e.config.ts",
196
197
  "sync-definitions": "node scripts/sync-definitions.ts",
197
198
  "check-definitions": "node scripts/sync-definitions.ts --check",
198
199
  "test:watch": "vitest -w",
@@ -232,6 +233,7 @@
232
233
  "@types/react-dom": "19.2.3",
233
234
  "jsdom": "30.0.1",
234
235
  "next": "16.2.9",
236
+ "playwright": "1.64.1",
235
237
  "tsdown": "0.18.2",
236
238
  "typescript": "5.9.3",
237
239
  "vitest": "4.1.0"