@weglot/translate-react 0.2.1 → 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.
Files changed (111) hide show
  1. package/README.md +118 -12
  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/next-compiler-loader.cjs +1 -4
  6. package/build/plugin/next-compiler-loader.mjs +2 -5
  7. package/build/plugin/next-compiler-loader.mjs.map +1 -1
  8. package/build/plugin/next-traces.cjs +38 -0
  9. package/build/plugin/next-traces.mjs +36 -0
  10. package/build/plugin/next-traces.mjs.map +1 -0
  11. package/build/plugin/next.cjs +43 -12
  12. package/build/plugin/next.d.cts.map +1 -1
  13. package/build/plugin/next.d.mts.map +1 -1
  14. package/build/plugin/next.mjs +41 -13
  15. package/build/plugin/next.mjs.map +1 -1
  16. package/build/plugin/transform/index.cjs +17 -3
  17. package/build/plugin/transform/index.mjs +17 -3
  18. package/build/plugin/transform/index.mjs.map +1 -1
  19. package/build/plugin/transform/msg.cjs +66 -0
  20. package/build/plugin/transform/msg.mjs +64 -0
  21. package/build/plugin/transform/msg.mjs.map +1 -0
  22. package/build/plugin/transform/process-file.cjs +18 -7
  23. package/build/plugin/transform/process-file.mjs +18 -7
  24. package/build/plugin/transform/process-file.mjs.map +1 -1
  25. package/build/plugin/transform/utils.cjs +1 -0
  26. package/build/plugin/transform/utils.mjs +1 -1
  27. package/build/plugin/transform/utils.mjs.map +1 -1
  28. package/build/plugin/unplugin.cjs +6 -7
  29. package/build/plugin/unplugin.d.cts.map +1 -1
  30. package/build/plugin/unplugin.d.mts.map +1 -1
  31. package/build/plugin/unplugin.mjs +7 -8
  32. package/build/plugin/unplugin.mjs.map +1 -1
  33. package/build/react/client/index.cjs +2 -0
  34. package/build/react/client/index.d.cts +2 -1
  35. package/build/react/client/index.d.mts +2 -1
  36. package/build/react/client/index.mjs +2 -1
  37. package/build/react/client/useTranslation.cjs +14 -2
  38. package/build/react/client/useTranslation.d.cts +0 -35
  39. package/build/react/client/useTranslation.d.cts.map +1 -1
  40. package/build/react/client/useTranslation.d.mts +0 -35
  41. package/build/react/client/useTranslation.d.mts.map +1 -1
  42. package/build/react/client/useTranslation.mjs +15 -3
  43. package/build/react/client/useTranslation.mjs.map +1 -1
  44. package/build/react/server/ServerWeglotProvider.d.cts +2 -2
  45. package/build/react/server/ServerWeglotProvider.d.mts +2 -2
  46. package/build/react/server/index.cjs +2 -0
  47. package/build/react/server/index.d.cts +2 -1
  48. package/build/react/server/index.d.mts +2 -1
  49. package/build/react/server/index.mjs +2 -1
  50. package/build/react/server/useTranslation.cjs +6 -4
  51. package/build/react/server/useTranslation.d.cts.map +1 -1
  52. package/build/react/server/useTranslation.d.mts.map +1 -1
  53. package/build/react/server/useTranslation.mjs +6 -4
  54. package/build/react/server/useTranslation.mjs.map +1 -1
  55. package/build/react/server-only/index.cjs +5 -3
  56. package/build/react/server-only/index.d.cts +2 -3
  57. package/build/react/server-only/index.d.cts.map +1 -1
  58. package/build/react/server-only/index.d.mts +2 -3
  59. package/build/react/server-only/index.d.mts.map +1 -1
  60. package/build/react/server-only/index.mjs +5 -3
  61. package/build/react/server-only/index.mjs.map +1 -1
  62. package/build/react/server-only/translations.cjs +21 -1
  63. package/build/react/server-only/translations.mjs +22 -2
  64. package/build/react/server-only/translations.mjs.map +1 -1
  65. package/build/react/shared/LocaleSwitcher.d.mts +2 -2
  66. package/build/react/shared/WeglotContext.cjs +18 -2
  67. package/build/react/shared/WeglotContext.d.cts +1 -0
  68. package/build/react/shared/WeglotContext.d.cts.map +1 -1
  69. package/build/react/shared/WeglotContext.d.mts +2 -0
  70. package/build/react/shared/WeglotContext.d.mts.map +1 -1
  71. package/build/react/shared/WeglotContext.mjs +18 -2
  72. package/build/react/shared/WeglotContext.mjs.map +1 -1
  73. package/build/react/shared/WeglotProvider.cjs +4 -0
  74. package/build/react/shared/WeglotProvider.d.cts +2 -2
  75. package/build/react/shared/WeglotProvider.d.cts.map +1 -1
  76. package/build/react/shared/WeglotProvider.d.mts +2 -2
  77. package/build/react/shared/WeglotProvider.d.mts.map +1 -1
  78. package/build/react/shared/WeglotProvider.mjs +4 -0
  79. package/build/react/shared/WeglotProvider.mjs.map +1 -1
  80. package/build/react/shared/msg.cjs +50 -0
  81. package/build/react/shared/msg.d.cts +26 -0
  82. package/build/react/shared/msg.d.cts.map +1 -0
  83. package/build/react/shared/msg.d.mts +26 -0
  84. package/build/react/shared/msg.d.mts.map +1 -0
  85. package/build/react/shared/msg.mjs +47 -0
  86. package/build/react/shared/msg.mjs.map +1 -0
  87. package/build/react/types.d.cts +7 -3
  88. package/build/react/types.d.cts.map +1 -1
  89. package/build/react/types.d.mts +7 -3
  90. package/build/react/types.d.mts.map +1 -1
  91. package/build/runtime/lru-cache.cjs +38 -0
  92. package/build/runtime/lru-cache.mjs +38 -0
  93. package/build/runtime/lru-cache.mjs.map +1 -0
  94. package/build/runtime/translate-dynamic.cjs +71 -17
  95. package/build/runtime/translate-dynamic.d.cts +2 -0
  96. package/build/runtime/translate-dynamic.d.cts.map +1 -1
  97. package/build/runtime/translate-dynamic.d.mts +2 -0
  98. package/build/runtime/translate-dynamic.d.mts.map +1 -1
  99. package/build/runtime/translate-dynamic.mjs +71 -17
  100. package/build/runtime/translate-dynamic.mjs.map +1 -1
  101. package/build/translators/weglot/api-client.cjs +4 -1
  102. package/build/translators/weglot/api-client.mjs +4 -1
  103. package/build/translators/weglot/api-client.mjs.map +1 -1
  104. package/build/types.d.cts +7 -1
  105. package/build/types.d.cts.map +1 -1
  106. package/build/types.d.mts +7 -1
  107. package/build/types.d.mts.map +1 -1
  108. package/build/utils/package-version.cjs +12 -0
  109. package/build/utils/package-version.mjs +12 -0
  110. package/build/utils/package-version.mjs.map +1 -0
  111. package/package.json +4 -2
@@ -4,6 +4,7 @@ const require_timeout = require('../utils/timeout.cjs');
4
4
  const require_definitions_generated = require('../translators/weglot/definitions/definitions.generated.cjs');
5
5
  const require_api_client = require('../translators/weglot/api-client.cjs');
6
6
  const require_segmenter = require('./html/segmenter.cjs');
7
+ const require_lru_cache = require('./lru-cache.cjs');
7
8
  let react = require("react");
8
9
  let _weglot_translate_react_virtual_config = require("@weglot/translate-react/virtual/config");
9
10
  let _weglot_translate_react_virtual_locale_server = require("@weglot/translate-react/virtual/locale/server");
@@ -11,23 +12,37 @@ let _weglot_translate_react_virtual_locale_server = require("@weglot/translate-r
11
12
  //#region src/runtime/translate-dynamic.ts
12
13
  /**
13
14
  * Runtime translation for content the compiler cannot see — a CMS title, an API
14
- * record. No cache: the API already stores repeated segments.
15
+ * record. Translations are kept in memory across requests, so content is only
16
+ * slow on its first view.
15
17
  */
16
18
  /** Matches the translate API's own limit, as in the build-time translator. */
17
19
  const MAX_WORDS_PER_REQUEST = 100;
18
20
  /** Batches are shared across concurrent renders, so a busy server queues many pages. */
19
21
  const MAX_CONCURRENT_REQUESTS = 4;
22
+ /** Collection window: server components render concurrently, so this gathers a
23
+ * whole page into one call. */
24
+ const DEFAULT_BATCH_WINDOW_MS = 5;
25
+ /** Measured round trips are ~150ms warm and ~750ms cold: this clears a warm
26
+ * call and cuts off a cold one. */
27
+ const DEFAULT_TIMEOUT_MS = 500;
28
+ const DEFAULT_CACHE_SIZE = 1e4;
29
+ /** Seconds a render that served source text stays cached before Next renders it again. */
30
+ const FALLBACK_REVALIDATE_SECONDS = 1;
20
31
  let config = {
21
32
  apiKey: void 0,
22
- timeoutMs: 500,
23
- batchWindowMs: 5
33
+ timeoutMs: DEFAULT_TIMEOUT_MS,
34
+ batchWindowMs: DEFAULT_BATCH_WINDOW_MS,
35
+ cacheSize: DEFAULT_CACHE_SIZE
24
36
  };
37
+ const translations = new require_lru_cache.LruCache(DEFAULT_CACHE_SIZE);
38
+ const cacheKey = (locale, text, type) => `${locale}\u0000${type}\u0000${text}`;
25
39
  /** Optional: the key otherwise comes from WEGLOT_API_KEY. */
26
40
  function configureDynamicTranslation(next) {
27
41
  config = {
28
42
  ...config,
29
43
  ...next
30
44
  };
45
+ translations.resize(config.cacheSize);
31
46
  }
32
47
  function resolveApiKey() {
33
48
  return config.apiKey ?? process.env.WEGLOT_API_KEY;
@@ -45,6 +60,23 @@ function memoFor() {
45
60
  return null;
46
61
  }
47
62
  }
63
+ /** Cuts the page's revalidation so Next does not keep serving the source text. */
64
+ async function shortenRevalidation() {
65
+ try {
66
+ const { unstable_cache } = await import("next/cache");
67
+ await unstable_cache(async () => null, ["weglot-dynamic-fallback"], { revalidate: FALLBACK_REVALIDATE_SECONDS })();
68
+ } catch (error) {
69
+ require_logger.logger.debug(`Could not shorten the revalidation of a page with untranslated dynamic content: ${error instanceof Error ? error.message : String(error)}`);
70
+ }
71
+ }
72
+ function translateWord(locale, text, timeoutMs, type = require_definitions_generated.WORD_TYPE.TEXT) {
73
+ const cached = translations.get(cacheKey(locale, text, type));
74
+ if (cached !== void 0) return Promise.resolve({
75
+ text: cached,
76
+ fallback: false
77
+ });
78
+ return enqueue(locale, text, timeoutMs, type);
79
+ }
48
80
  function enqueue(locale, text, timeoutMs, type) {
49
81
  const key = batchKey(locale, timeoutMs);
50
82
  return new Promise((resolve) => {
@@ -66,7 +98,10 @@ async function flush(key, locale, timeoutMs) {
66
98
  const apiKey = resolveApiKey();
67
99
  if (!apiKey) {
68
100
  require_logger.logger.warn("Weglot project key is missing, so dynamic content is served untranslated. Set WEGLOT_API_KEY or call configureDynamicTranslation({ apiKey }).");
69
- queue.forEach((word) => word.resolve(word.text));
101
+ queue.forEach((word) => word.resolve({
102
+ text: word.text,
103
+ fallback: false
104
+ }));
70
105
  return;
71
106
  }
72
107
  const client = new require_api_client.WeglotApiClient(apiKey, _weglot_translate_react_virtual_config.apiBaseUrl);
@@ -74,30 +109,45 @@ async function flush(key, locale, timeoutMs) {
74
109
  for (let i = 0; i < queue.length; i += MAX_WORDS_PER_REQUEST) chunks.push(queue.slice(i, i + MAX_WORDS_PER_REQUEST));
75
110
  const deadline = Date.now() + timeoutMs;
76
111
  let next = 0;
112
+ const fallBack = (chunk) => chunk.forEach((word) => word.resolve({
113
+ text: word.text,
114
+ fallback: true
115
+ }));
77
116
  const worker = async () => {
78
117
  while (next < chunks.length) {
79
118
  const chunk = chunks[next++];
80
119
  if (Date.now() >= deadline) {
81
- chunk.forEach((word) => word.resolve(word.text));
120
+ fallBack(chunk);
82
121
  continue;
83
122
  }
123
+ const request = client.translate({
124
+ from: _weglot_translate_react_virtual_config.sourceLocale,
125
+ to: _weglot_translate_react_virtual_config.apiLocales[locale] ?? locale,
126
+ words: chunk.map((word) => word.text),
127
+ types: chunk.map((word) => word.type),
128
+ live: true
129
+ });
130
+ request.then(({ words }) => chunk.forEach((word, index) => {
131
+ const result = words[index];
132
+ if (result != null) translations.set(cacheKey(locale, word.text, word.type), result);
133
+ })).catch(() => {});
84
134
  try {
85
- const { words: translated } = await require_timeout.withTimeout(client.translate({
86
- from: _weglot_translate_react_virtual_config.sourceLocale,
87
- to: _weglot_translate_react_virtual_config.apiLocales[locale] ?? locale,
88
- words: chunk.map((word) => word.text),
89
- types: chunk.map((word) => word.type ?? require_definitions_generated.WORD_TYPE.TEXT),
90
- live: true
91
- }), deadline - Date.now(), `Weglot dynamic translation to ${locale}`);
135
+ const { words: translated } = await require_timeout.withTimeout(request, deadline - Date.now(), `Weglot dynamic translation to ${locale}`);
92
136
  chunk.forEach((word, index) => {
93
137
  const result = translated[index];
94
138
  if (result === null) require_logger.logger.debug(`Weglot is still translating dynamic content for locale "${locale}".`);
95
139
  else if (result === word.text) require_logger.logger.debug(`Weglot returned dynamic content unchanged for locale "${locale}".`);
96
- word.resolve(result ?? word.text);
140
+ word.resolve(result === null ? {
141
+ text: word.text,
142
+ fallback: true
143
+ } : {
144
+ text: result,
145
+ fallback: false
146
+ });
97
147
  });
98
148
  } catch (error) {
99
149
  require_logger.logger.warn(`Dynamic translation to "${locale}" failed, serving source text: ${error instanceof Error ? error.message : String(error)}`);
100
- chunk.forEach((word) => word.resolve(word.text));
150
+ fallBack(chunk);
101
151
  }
102
152
  }
103
153
  };
@@ -113,7 +163,10 @@ async function tDynamic(text, options = {}) {
113
163
  const key = `${batchKey(locale, timeoutMs)}\u0000${text}`;
114
164
  const existing = memo?.get(key);
115
165
  if (existing) return existing;
116
- const pending = enqueue(locale, text, timeoutMs);
166
+ const pending = translateWord(locale, text, timeoutMs).then(async (result) => {
167
+ if (result.fallback) await shortenRevalidation();
168
+ return result.text;
169
+ });
117
170
  memo?.set(key, pending);
118
171
  return pending;
119
172
  }
@@ -129,8 +182,9 @@ async function tDynamicHtml(html, options = {}) {
129
182
  const segmenter = new require_segmenter.HtmlSegmenter(html, _weglot_translate_react_virtual_config.translationEngine);
130
183
  const segments = segmenter.extract();
131
184
  if (segments.length === 0) return html;
132
- const translated = await Promise.all(segments.map((segment) => enqueue(locale, segment.w, timeoutMs, segment.t)));
133
- return segmenter.apply(translated);
185
+ const translated = await Promise.all(segments.map((segment) => translateWord(locale, segment.w, timeoutMs, segment.t)));
186
+ if (translated.some((result) => result.fallback)) await shortenRevalidation();
187
+ return segmenter.apply(translated.map((result) => result.text));
134
188
  }
135
189
  /** Translates several strings in one pass, sharing a single request. */
136
190
  async function tDynamicAll(texts, options = {}) {
@@ -12,6 +12,8 @@ interface DynamicTranslationConfig {
12
12
  apiKey?: string;
13
13
  timeoutMs?: number;
14
14
  batchWindowMs?: number;
15
+ /** Translations kept in memory across requests. 0 disables the cache. */
16
+ cacheSize?: number;
15
17
  }
16
18
  /** Optional: the key otherwise comes from WEGLOT_API_KEY. */
17
19
  declare function configureDynamicTranslation(next: DynamicTranslationConfig): void;
@@ -1 +1 @@
1
- {"version":3,"file":"translate-dynamic.d.cts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;AA0DgB,UAvBC,yBAAA,CAuB0B;EAmJrB;EAwBA,MAAA,CAAA,EAhMX,UAgMuB;EAqBZ;;;UAhNL,wBAAA;;;;;;iBAgBD,2BAAA,OACR;;iBAkJc,QAAA,yBAEX,4BACR;;;;;iBAqBmB,YAAA,yBAEX,4BACR;;iBAkBmB,WAAA,4BAEX,4BACR"}
1
+ {"version":3,"file":"translate-dynamic.d.cts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;AAiRsB,UAvOL,yBAAA,CAyON;EA2BW;EA0BA,MAAA,CAAA,EA5RX,UA4RsB;;;;UAvRhB,wBAAA;;;;;;;;iBAwBD,2BAAA,OACR;;iBAuMc,QAAA,yBAEX,4BACR;;;;;iBA0BmB,YAAA,yBAEX,4BACR;;iBAuBmB,WAAA,4BAEX,4BACR"}
@@ -12,6 +12,8 @@ interface DynamicTranslationConfig {
12
12
  apiKey?: string;
13
13
  timeoutMs?: number;
14
14
  batchWindowMs?: number;
15
+ /** Translations kept in memory across requests. 0 disables the cache. */
16
+ cacheSize?: number;
15
17
  }
16
18
  /** Optional: the key otherwise comes from WEGLOT_API_KEY. */
17
19
  declare function configureDynamicTranslation(next: DynamicTranslationConfig): void;
@@ -1 +1 @@
1
- {"version":3,"file":"translate-dynamic.d.mts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;AA0DgB,UAvBC,yBAAA,CAuB0B;EAmJrB;EAwBA,MAAA,CAAA,EAhMX,UAgMuB;EAqBZ;;;UAhNL,wBAAA;;;;;;iBAgBD,2BAAA,OACR;;iBAkJc,QAAA,yBAEX,4BACR;;;;;iBAqBmB,YAAA,yBAEX,4BACR;;iBAkBmB,WAAA,4BAEX,4BACR"}
1
+ {"version":3,"file":"translate-dynamic.d.mts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;AAiRsB,UAvOL,yBAAA,CAyON;EA2BW;EA0BA,MAAA,CAAA,EA5RX,UA4RsB;;;;UAvRhB,wBAAA;;;;;;;;iBAwBD,2BAAA,OACR;;iBAuMc,QAAA,yBAEX,4BACR;;;;;iBA0BmB,YAAA,yBAEX,4BACR;;iBAuBmB,WAAA,4BAEX,4BACR"}
@@ -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. No cache: the API already stores repeated segments.
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: 500,
22
- batchWindowMs: 5
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(word.text));
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.forEach((word) => word.resolve(word.text));
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(client.translate({
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 ?? word.text);
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.forEach((word) => word.resolve(word.text));
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 = enqueue(locale, text, timeoutMs);
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) => enqueue(locale, segment.w, timeoutMs, segment.t)));
132
- return segmenter.apply(translated);
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;CAqBzB,eAzB8B;CA0B/B;;AAGD,SAAgB,4BACd,MACM;AACN,UAAS;EAAE,GAAG;EAAQ,GAAG;EAAM;;AAGjC,SAAS,gBAAoC;AAC3C,QAAO,OAAO,UAAU,QAAQ,IAAI;;AAYtC,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;;;AAIX,SAAS,QACP,QACA,MACA,WACA,MACiB;CACjB,MAAM,MAAM,SAAS,QAAQ,UAAU;AACvC,QAAO,IAAI,SAAiB,YAAY;EACtC,MAAM,QAAQ,OAAO,IAAI,IAAI,IAAI,EAAE;AACnC,QAAM,KAAK;GAAE;GAAM;GAAM;GAAS,CAAC;AACnC,SAAO,IAAI,KAAK,MAAM;AAEtB,MAAI,CAAC,OAAO,IAAI,IAAI,CAClB,QAAO,IACL,KACA,iBACQ,KAAK,MAAM,KAAK,QAAQ,UAAU,EACxC,OAAO,cACR,CACF;GAEH;;AAGJ,eAAe,MACb,KACA,QACA,WACe;AACf,QAAO,OAAO,IAAI;CAClB,MAAM,QAAQ,OAAO,IAAI,IAAI,IAAI,EAAE;AACnC,QAAO,OAAO,IAAI;AAClB,KAAI,MAAM,WAAW,EAAG;CAExB,MAAM,SAAS,eAAe;AAC9B,KAAI,CAAC,QAAQ;AACX,SAAO,KACL,gJACD;A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AAsB,SACpB,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,OAAO,SAAS;CACtB,MAAM,MAAM,GAAG,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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AAsB,YACpB,OACA,UAAqC,EAAE,EACpB;AACnB,QAAO,QAAQ,IAAI,MAAM,KAAK,SAAS,SAAS,MAAM,QAAQ,CAAC,CAAC"}
@@ -137,7 +137,10 @@ var WeglotApiClient = class {
137
137
  }
138
138
  }
139
139
  async fetchSettings() {
140
- const response = await require_timeout.withTimeout(fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, { headers: { Accept: "application/json" } }), require_timeout.DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
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: { Accept: "application/json" } }), DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
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,MAA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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"}
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,I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C,MAAM,QAAQ,KAAK,UAAU,CACvD,OAAM,IAAI,MACR,iFACD;EAIH,MAAM,YAAY,KAAK,UAAU,QAAQ,SAAS,KAAK,YAAY,MAAM;AAEzE,SAAO;GACL,cAAc,KAAK;GACnB,eAAe,UAAU,KAAK,SAAS,KAAK,eAAe,KAAK,YAAY;GAC5E,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"}
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"}