@weglot/translate-react 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (292) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +6 -0
  3. package/README.md +190 -2
  4. package/build/_virtual/rolldown_runtime.cjs +29 -0
  5. package/build/_virtual/rolldown_runtime.mjs +7 -0
  6. package/build/index.cjs +0 -0
  7. package/build/index.d.cts +2 -0
  8. package/build/index.d.mts +2 -0
  9. package/build/index.mjs +1 -0
  10. package/build/locale.d.cts +6 -0
  11. package/build/locale.d.cts.map +1 -0
  12. package/build/locale.d.mts +6 -0
  13. package/build/locale.d.mts.map +1 -0
  14. package/build/metadata/manager.cjs +119 -0
  15. package/build/metadata/manager.mjs +114 -0
  16. package/build/metadata/manager.mjs.map +1 -0
  17. package/build/plugin/build-translator.cjs +207 -0
  18. package/build/plugin/build-translator.mjs +205 -0
  19. package/build/plugin/build-translator.mjs.map +1 -0
  20. package/build/plugin/cleanup.cjs +20 -0
  21. package/build/plugin/cleanup.mjs +20 -0
  22. package/build/plugin/cleanup.mjs.map +1 -0
  23. package/build/plugin/index.cjs +0 -0
  24. package/build/plugin/index.d.cts +2 -0
  25. package/build/plugin/index.d.mts +2 -0
  26. package/build/plugin/index.mjs +1 -0
  27. package/build/plugin/next-compiler-loader.cjs +40 -0
  28. package/build/plugin/next-compiler-loader.d.cts +12 -0
  29. package/build/plugin/next-compiler-loader.d.cts.map +1 -0
  30. package/build/plugin/next-compiler-loader.d.mts +13 -0
  31. package/build/plugin/next-compiler-loader.d.mts.map +1 -0
  32. package/build/plugin/next-compiler-loader.mjs +41 -0
  33. package/build/plugin/next-compiler-loader.mjs.map +1 -0
  34. package/build/plugin/next-config-loader.cjs +13 -0
  35. package/build/plugin/next-config-loader.d.cts +8 -0
  36. package/build/plugin/next-config-loader.d.cts.map +1 -0
  37. package/build/plugin/next-config-loader.d.mts +9 -0
  38. package/build/plugin/next-config-loader.d.mts.map +1 -0
  39. package/build/plugin/next-config-loader.mjs +14 -0
  40. package/build/plugin/next-config-loader.mjs.map +1 -0
  41. package/build/plugin/next-locale-client-loader.cjs +9 -0
  42. package/build/plugin/next-locale-client-loader.d.cts +8 -0
  43. package/build/plugin/next-locale-client-loader.d.cts.map +1 -0
  44. package/build/plugin/next-locale-client-loader.d.mts +9 -0
  45. package/build/plugin/next-locale-client-loader.d.mts.map +1 -0
  46. package/build/plugin/next-locale-client-loader.mjs +10 -0
  47. package/build/plugin/next-locale-client-loader.mjs.map +1 -0
  48. package/build/plugin/next-locale-server-loader.cjs +9 -0
  49. package/build/plugin/next-locale-server-loader.d.cts +8 -0
  50. package/build/plugin/next-locale-server-loader.d.cts.map +1 -0
  51. package/build/plugin/next-locale-server-loader.d.mts +9 -0
  52. package/build/plugin/next-locale-server-loader.d.mts.map +1 -0
  53. package/build/plugin/next-locale-server-loader.mjs +10 -0
  54. package/build/plugin/next-locale-server-loader.mjs.map +1 -0
  55. package/build/plugin/next.cjs +226 -0
  56. package/build/plugin/next.d.cts +9 -0
  57. package/build/plugin/next.d.cts.map +1 -0
  58. package/build/plugin/next.d.mts +9 -0
  59. package/build/plugin/next.d.mts.map +1 -0
  60. package/build/plugin/next.mjs +228 -0
  61. package/build/plugin/next.mjs.map +1 -0
  62. package/build/plugin/transform/babel-compat.cjs +13 -0
  63. package/build/plugin/transform/babel-compat.mjs +10 -0
  64. package/build/plugin/transform/babel-compat.mjs.map +1 -0
  65. package/build/plugin/transform/expression-strings.cjs +145 -0
  66. package/build/plugin/transform/expression-strings.mjs +140 -0
  67. package/build/plugin/transform/expression-strings.mjs.map +1 -0
  68. package/build/plugin/transform/index.cjs +45 -0
  69. package/build/plugin/transform/index.mjs +43 -0
  70. package/build/plugin/transform/index.mjs.map +1 -0
  71. package/build/plugin/transform/metadata.cjs +142 -0
  72. package/build/plugin/transform/metadata.mjs +141 -0
  73. package/build/plugin/transform/metadata.mjs.map +1 -0
  74. package/build/plugin/transform/process-file.cjs +525 -0
  75. package/build/plugin/transform/process-file.mjs +524 -0
  76. package/build/plugin/transform/process-file.mjs.map +1 -0
  77. package/build/plugin/transform/use-i18n.cjs +8 -0
  78. package/build/plugin/transform/use-i18n.mjs +7 -0
  79. package/build/plugin/transform/use-i18n.mjs.map +1 -0
  80. package/build/plugin/transform/utils.cjs +237 -0
  81. package/build/plugin/transform/utils.mjs +219 -0
  82. package/build/plugin/transform/utils.mjs.map +1 -0
  83. package/build/plugin/unplugin.cjs +188 -0
  84. package/build/plugin/unplugin.d.cts +8 -0
  85. package/build/plugin/unplugin.d.cts.map +1 -0
  86. package/build/plugin/unplugin.d.mts +8 -0
  87. package/build/plugin/unplugin.d.mts.map +1 -0
  88. package/build/plugin/unplugin.mjs +188 -0
  89. package/build/plugin/unplugin.mjs.map +1 -0
  90. package/build/plugin/vite.cjs +27 -0
  91. package/build/plugin/vite.d.cts +9 -0
  92. package/build/plugin/vite.d.cts.map +1 -0
  93. package/build/plugin/vite.d.mts +9 -0
  94. package/build/plugin/vite.d.mts.map +1 -0
  95. package/build/plugin/vite.mjs +28 -0
  96. package/build/plugin/vite.mjs.map +1 -0
  97. package/build/plugin/webpack.cjs +26 -0
  98. package/build/plugin/webpack.d.cts +8 -0
  99. package/build/plugin/webpack.d.cts.map +1 -0
  100. package/build/plugin/webpack.d.mts +8 -0
  101. package/build/plugin/webpack.d.mts.map +1 -0
  102. package/build/plugin/webpack.mjs +27 -0
  103. package/build/plugin/webpack.mjs.map +1 -0
  104. package/build/react/client/index.cjs +9 -0
  105. package/build/react/client/index.d.cts +5 -0
  106. package/build/react/client/index.d.mts +5 -0
  107. package/build/react/client/index.mjs +6 -0
  108. package/build/react/client/useTranslation.cjs +71 -0
  109. package/build/react/client/useTranslation.d.cts +42 -0
  110. package/build/react/client/useTranslation.d.cts.map +1 -0
  111. package/build/react/client/useTranslation.d.mts +42 -0
  112. package/build/react/client/useTranslation.d.mts.map +1 -0
  113. package/build/react/client/useTranslation.mjs +71 -0
  114. package/build/react/client/useTranslation.mjs.map +1 -0
  115. package/build/react/next/client.cjs +25 -0
  116. package/build/react/next/client.d.cts +9 -0
  117. package/build/react/next/client.d.cts.map +1 -0
  118. package/build/react/next/client.d.mts +9 -0
  119. package/build/react/next/client.d.mts.map +1 -0
  120. package/build/react/next/client.mjs +24 -0
  121. package/build/react/next/client.mjs.map +1 -0
  122. package/build/react/next/cookie-locale-resolver.cjs +29 -0
  123. package/build/react/next/cookie-locale-resolver.d.cts +33 -0
  124. package/build/react/next/cookie-locale-resolver.d.cts.map +1 -0
  125. package/build/react/next/cookie-locale-resolver.d.mts +33 -0
  126. package/build/react/next/cookie-locale-resolver.d.mts.map +1 -0
  127. package/build/react/next/cookie-locale-resolver.mjs +29 -0
  128. package/build/react/next/cookie-locale-resolver.mjs.map +1 -0
  129. package/build/react/next/server.cjs +21 -0
  130. package/build/react/next/server.d.cts +13 -0
  131. package/build/react/next/server.d.cts.map +1 -0
  132. package/build/react/next/server.d.mts +14 -0
  133. package/build/react/next/server.d.mts.map +1 -0
  134. package/build/react/next/server.mjs +20 -0
  135. package/build/react/next/server.mjs.map +1 -0
  136. package/build/react/server/ServerWeglotProvider.cjs +19 -0
  137. package/build/react/server/ServerWeglotProvider.d.cts +12 -0
  138. package/build/react/server/ServerWeglotProvider.d.cts.map +1 -0
  139. package/build/react/server/ServerWeglotProvider.d.mts +12 -0
  140. package/build/react/server/ServerWeglotProvider.d.mts.map +1 -0
  141. package/build/react/server/ServerWeglotProvider.mjs +19 -0
  142. package/build/react/server/ServerWeglotProvider.mjs.map +1 -0
  143. package/build/react/server/index.cjs +7 -0
  144. package/build/react/server/index.d.cts +4 -0
  145. package/build/react/server/index.d.mts +4 -0
  146. package/build/react/server/index.mjs +5 -0
  147. package/build/react/server/useTranslation.cjs +60 -0
  148. package/build/react/server/useTranslation.d.cts +36 -0
  149. package/build/react/server/useTranslation.d.cts.map +1 -0
  150. package/build/react/server/useTranslation.d.mts +36 -0
  151. package/build/react/server/useTranslation.d.mts.map +1 -0
  152. package/build/react/server/useTranslation.mjs +60 -0
  153. package/build/react/server/useTranslation.mjs.map +1 -0
  154. package/build/react/server-only/index.cjs +42 -0
  155. package/build/react/server-only/index.d.cts +38 -0
  156. package/build/react/server-only/index.d.cts.map +1 -0
  157. package/build/react/server-only/index.d.mts +38 -0
  158. package/build/react/server-only/index.d.mts.map +1 -0
  159. package/build/react/server-only/index.mjs +42 -0
  160. package/build/react/server-only/index.mjs.map +1 -0
  161. package/build/react/server-only/translations.cjs +86 -0
  162. package/build/react/server-only/translations.mjs +86 -0
  163. package/build/react/server-only/translations.mjs.map +1 -0
  164. package/build/react/shared/LocaleSwitcher.cjs +61 -0
  165. package/build/react/shared/LocaleSwitcher.d.cts +71 -0
  166. package/build/react/shared/LocaleSwitcher.d.cts.map +1 -0
  167. package/build/react/shared/LocaleSwitcher.d.mts +71 -0
  168. package/build/react/shared/LocaleSwitcher.d.mts.map +1 -0
  169. package/build/react/shared/LocaleSwitcher.mjs +61 -0
  170. package/build/react/shared/LocaleSwitcher.mjs.map +1 -0
  171. package/build/react/shared/WeglotContext.cjs +14 -0
  172. package/build/react/shared/WeglotContext.d.cts +34 -0
  173. package/build/react/shared/WeglotContext.d.cts.map +1 -0
  174. package/build/react/shared/WeglotContext.d.mts +34 -0
  175. package/build/react/shared/WeglotContext.d.mts.map +1 -0
  176. package/build/react/shared/WeglotContext.mjs +13 -0
  177. package/build/react/shared/WeglotContext.mjs.map +1 -0
  178. package/build/react/shared/WeglotProvider.cjs +250 -0
  179. package/build/react/shared/WeglotProvider.d.cts +60 -0
  180. package/build/react/shared/WeglotProvider.d.cts.map +1 -0
  181. package/build/react/shared/WeglotProvider.d.mts +60 -0
  182. package/build/react/shared/WeglotProvider.d.mts.map +1 -0
  183. package/build/react/shared/WeglotProvider.mjs +250 -0
  184. package/build/react/shared/WeglotProvider.mjs.map +1 -0
  185. package/build/react/shared/render-rich-text.cjs +56 -0
  186. package/build/react/shared/render-rich-text.d.cts +16 -0
  187. package/build/react/shared/render-rich-text.d.cts.map +1 -0
  188. package/build/react/shared/render-rich-text.d.mts +16 -0
  189. package/build/react/shared/render-rich-text.d.mts.map +1 -0
  190. package/build/react/shared/render-rich-text.mjs +55 -0
  191. package/build/react/shared/render-rich-text.mjs.map +1 -0
  192. package/build/react/shared/utils.cjs +34 -0
  193. package/build/react/shared/utils.mjs +35 -0
  194. package/build/react/shared/utils.mjs.map +1 -0
  195. package/build/react/types.d.cts +16 -0
  196. package/build/react/types.d.cts.map +1 -0
  197. package/build/react/types.d.mts +16 -0
  198. package/build/react/types.d.mts.map +1 -0
  199. package/build/runtime/html/segmenter.cjs +226 -0
  200. package/build/runtime/html/segmenter.mjs +225 -0
  201. package/build/runtime/html/segmenter.mjs.map +1 -0
  202. package/build/runtime/index.cjs +6 -0
  203. package/build/runtime/index.d.cts +2 -0
  204. package/build/runtime/index.d.mts +2 -0
  205. package/build/runtime/index.mjs +3 -0
  206. package/build/runtime/translate-dynamic.cjs +142 -0
  207. package/build/runtime/translate-dynamic.d.cts +29 -0
  208. package/build/runtime/translate-dynamic.d.cts.map +1 -0
  209. package/build/runtime/translate-dynamic.d.mts +29 -0
  210. package/build/runtime/translate-dynamic.d.mts.map +1 -0
  211. package/build/runtime/translate-dynamic.mjs +139 -0
  212. package/build/runtime/translate-dynamic.mjs.map +1 -0
  213. package/build/translation-server/logger.cjs +37 -0
  214. package/build/translation-server/logger.mjs +37 -0
  215. package/build/translation-server/logger.mjs.map +1 -0
  216. package/build/translation-server/translation-server.cjs +451 -0
  217. package/build/translation-server/translation-server.mjs +448 -0
  218. package/build/translation-server/translation-server.mjs.map +1 -0
  219. package/build/translators/api.cjs +12 -0
  220. package/build/translators/api.mjs +12 -0
  221. package/build/translators/api.mjs.map +1 -0
  222. package/build/translators/cache-factory.cjs +26 -0
  223. package/build/translators/cache-factory.mjs +27 -0
  224. package/build/translators/cache-factory.mjs.map +1 -0
  225. package/build/translators/local-cache.cjs +132 -0
  226. package/build/translators/local-cache.mjs +130 -0
  227. package/build/translators/local-cache.mjs.map +1 -0
  228. package/build/translators/translation-service.cjs +137 -0
  229. package/build/translators/translation-service.mjs +138 -0
  230. package/build/translators/translation-service.mjs.map +1 -0
  231. package/build/translators/weglot/api-client.cjs +79 -0
  232. package/build/translators/weglot/api-client.mjs +79 -0
  233. package/build/translators/weglot/api-client.mjs.map +1 -0
  234. package/build/translators/weglot/definitions/definitions.generated.cjs +53 -0
  235. package/build/translators/weglot/definitions/definitions.generated.mjs +52 -0
  236. package/build/translators/weglot/definitions/definitions.generated.mjs.map +1 -0
  237. package/build/translators/weglot/engine.cjs +46 -0
  238. package/build/translators/weglot/engine.mjs +43 -0
  239. package/build/translators/weglot/engine.mjs.map +1 -0
  240. package/build/translators/weglot/translator.cjs +61 -0
  241. package/build/translators/weglot/translator.mjs +62 -0
  242. package/build/translators/weglot/translator.mjs.map +1 -0
  243. package/build/translators/weglot/wire-format.cjs +128 -0
  244. package/build/translators/weglot/wire-format.mjs +129 -0
  245. package/build/translators/weglot/wire-format.mjs.map +1 -0
  246. package/build/types.d.cts +143 -0
  247. package/build/types.d.cts.map +1 -0
  248. package/build/types.d.mts +143 -0
  249. package/build/types.d.mts.map +1 -0
  250. package/build/utils/config-factory.cjs +86 -0
  251. package/build/utils/config-factory.mjs +83 -0
  252. package/build/utils/config-factory.mjs.map +1 -0
  253. package/build/utils/hash.cjs +17 -0
  254. package/build/utils/hash.mjs +16 -0
  255. package/build/utils/hash.mjs.map +1 -0
  256. package/build/utils/is-valid-locale.cjs +13 -0
  257. package/build/utils/is-valid-locale.mjs +13 -0
  258. package/build/utils/is-valid-locale.mjs.map +1 -0
  259. package/build/utils/logger.cjs +51 -0
  260. package/build/utils/logger.mjs +50 -0
  261. package/build/utils/logger.mjs.map +1 -0
  262. package/build/utils/path-helpers.cjs +49 -0
  263. package/build/utils/path-helpers.mjs +47 -0
  264. package/build/utils/path-helpers.mjs.map +1 -0
  265. package/build/utils/timeout.cjs +42 -0
  266. package/build/utils/timeout.mjs +41 -0
  267. package/build/utils/timeout.mjs.map +1 -0
  268. package/build/virtual/code-generator.cjs +56 -0
  269. package/build/virtual/code-generator.mjs +55 -0
  270. package/build/virtual/code-generator.mjs.map +1 -0
  271. package/build/virtual/config.cjs +16 -0
  272. package/build/virtual/config.d.cts +13 -0
  273. package/build/virtual/config.d.cts.map +1 -0
  274. package/build/virtual/config.d.mts +13 -0
  275. package/build/virtual/config.d.mts.map +1 -0
  276. package/build/virtual/config.mjs +12 -0
  277. package/build/virtual/config.mjs.map +1 -0
  278. package/build/virtual/locale/client.cjs +23 -0
  279. package/build/virtual/locale/client.d.cts +19 -0
  280. package/build/virtual/locale/client.d.cts.map +1 -0
  281. package/build/virtual/locale/client.d.mts +19 -0
  282. package/build/virtual/locale/client.d.mts.map +1 -0
  283. package/build/virtual/locale/client.mjs +22 -0
  284. package/build/virtual/locale/client.mjs.map +1 -0
  285. package/build/virtual/locale/server.cjs +13 -0
  286. package/build/virtual/locale/server.d.cts +13 -0
  287. package/build/virtual/locale/server.d.cts.map +1 -0
  288. package/build/virtual/locale/server.d.mts +13 -0
  289. package/build/virtual/locale/server.d.mts.map +1 -0
  290. package/build/virtual/locale/server.mjs +13 -0
  291. package/build/virtual/locale/server.mjs.map +1 -0
  292. package/package.json +260 -4
@@ -0,0 +1,142 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_logger = require('../utils/logger.cjs');
3
+ const require_timeout = require('../utils/timeout.cjs');
4
+ const require_definitions_generated = require('../translators/weglot/definitions/definitions.generated.cjs');
5
+ const require_api_client = require('../translators/weglot/api-client.cjs');
6
+ const require_segmenter = require('./html/segmenter.cjs');
7
+ let react = require("react");
8
+ let _weglot_translate_react_virtual_config = require("@weglot/translate-react/virtual/config");
9
+ let _weglot_translate_react_virtual_locale_server = require("@weglot/translate-react/virtual/locale/server");
10
+
11
+ //#region src/runtime/translate-dynamic.ts
12
+ /**
13
+ * Runtime translation for content the compiler cannot see — a CMS title, an API
14
+ * record. No cache: the API already stores repeated segments.
15
+ */
16
+ /** Matches the translate API's own limit, as in the build-time translator. */
17
+ const MAX_WORDS_PER_REQUEST = 100;
18
+ /** Batches are shared across concurrent renders, so a busy server queues many pages. */
19
+ const MAX_CONCURRENT_REQUESTS = 4;
20
+ let config = {
21
+ apiKey: void 0,
22
+ timeoutMs: 500,
23
+ batchWindowMs: 5
24
+ };
25
+ /** Optional: the key otherwise comes from WEGLOT_API_KEY. */
26
+ function configureDynamicTranslation(next) {
27
+ config = {
28
+ ...config,
29
+ ...next
30
+ };
31
+ }
32
+ function resolveApiKey() {
33
+ return config.apiKey ?? process.env.WEGLOT_API_KEY;
34
+ }
35
+ const queues = /* @__PURE__ */ new Map();
36
+ const timers = /* @__PURE__ */ new Map();
37
+ const batchKey = (locale, timeoutMs) => `${locale}\u0000${timeoutMs}`;
38
+ /** One map per request, so a title rendered twice is translated once. Outside a
39
+ * render, `cache` has nothing to key on and calls stand alone. */
40
+ const requestMemo = (0, react.cache)(() => /* @__PURE__ */ new Map());
41
+ function memoFor() {
42
+ try {
43
+ return requestMemo();
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+ function enqueue(locale, text, timeoutMs, type) {
49
+ const key = batchKey(locale, timeoutMs);
50
+ return new Promise((resolve) => {
51
+ const queue = queues.get(key) ?? [];
52
+ queue.push({
53
+ text,
54
+ type,
55
+ resolve
56
+ });
57
+ queues.set(key, queue);
58
+ if (!timers.has(key)) timers.set(key, setTimeout(() => void flush(key, locale, timeoutMs), config.batchWindowMs));
59
+ });
60
+ }
61
+ async function flush(key, locale, timeoutMs) {
62
+ timers.delete(key);
63
+ const queue = queues.get(key) ?? [];
64
+ queues.delete(key);
65
+ if (queue.length === 0) return;
66
+ const apiKey = resolveApiKey();
67
+ if (!apiKey) {
68
+ 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));
70
+ return;
71
+ }
72
+ const client = new require_api_client.WeglotApiClient(apiKey);
73
+ const chunks = [];
74
+ for (let i = 0; i < queue.length; i += MAX_WORDS_PER_REQUEST) chunks.push(queue.slice(i, i + MAX_WORDS_PER_REQUEST));
75
+ const deadline = Date.now() + timeoutMs;
76
+ let next = 0;
77
+ const worker = async () => {
78
+ while (next < chunks.length) {
79
+ const chunk = chunks[next++];
80
+ if (Date.now() >= deadline) {
81
+ chunk.forEach((word) => word.resolve(word.text));
82
+ continue;
83
+ }
84
+ try {
85
+ const 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
+ }), deadline - Date.now(), `Weglot dynamic translation to ${locale}`);
91
+ chunk.forEach((word, index) => {
92
+ const result = translated[index];
93
+ if (result === word.text) require_logger.logger.debug(`Weglot returned dynamic content unchanged for locale "${locale}".`);
94
+ word.resolve(result ?? word.text);
95
+ });
96
+ } catch (error) {
97
+ require_logger.logger.warn(`Dynamic translation to "${locale}" failed, serving source text: ${error instanceof Error ? error.message : String(error)}`);
98
+ chunk.forEach((word) => word.resolve(word.text));
99
+ }
100
+ }
101
+ };
102
+ await Promise.all(Array.from({ length: Math.min(MAX_CONCURRENT_REQUESTS, chunks.length) }, worker));
103
+ }
104
+ /** Translate a string that only exists at runtime: `await tDynamic(post.title)`. */
105
+ async function tDynamic(text, options = {}) {
106
+ if (!text.trim()) return text;
107
+ const locale = options.locale ?? await (0, _weglot_translate_react_virtual_locale_server.getServerLocale)();
108
+ if (!locale || locale === _weglot_translate_react_virtual_config.sourceLocale) return text;
109
+ const timeoutMs = options.timeoutMs ?? config.timeoutMs;
110
+ const memo = memoFor();
111
+ const key = `${batchKey(locale, timeoutMs)}\u0000${text}`;
112
+ const existing = memo?.get(key);
113
+ if (existing) return existing;
114
+ const pending = enqueue(locale, text, timeoutMs);
115
+ memo?.set(key, pending);
116
+ return pending;
117
+ }
118
+ /**
119
+ * Translate an HTML fragment, split into segments the way the proxy splits a
120
+ * page, so a sentence wrapped in `<strong>` travels whole.
121
+ */
122
+ async function tDynamicHtml(html, options = {}) {
123
+ if (!html.trim()) return html;
124
+ const locale = options.locale ?? await (0, _weglot_translate_react_virtual_locale_server.getServerLocale)();
125
+ if (!locale || locale === _weglot_translate_react_virtual_config.sourceLocale) return html;
126
+ const timeoutMs = options.timeoutMs ?? config.timeoutMs;
127
+ const segmenter = new require_segmenter.HtmlSegmenter(html, _weglot_translate_react_virtual_config.translationEngine);
128
+ const segments = segmenter.extract();
129
+ if (segments.length === 0) return html;
130
+ const translated = await Promise.all(segments.map((segment) => enqueue(locale, segment.w, timeoutMs, segment.t)));
131
+ return segmenter.apply(translated);
132
+ }
133
+ /** Translates several strings in one pass, sharing a single request. */
134
+ async function tDynamicAll(texts, options = {}) {
135
+ return Promise.all(texts.map((text) => tDynamic(text, options)));
136
+ }
137
+
138
+ //#endregion
139
+ exports.configureDynamicTranslation = configureDynamicTranslation;
140
+ exports.tDynamic = tDynamic;
141
+ exports.tDynamicAll = tDynamicAll;
142
+ exports.tDynamicHtml = tDynamicHtml;
@@ -0,0 +1,29 @@
1
+ import { LocaleCode } from "../locale.cjs";
2
+
3
+ //#region src/runtime/translate-dynamic.d.ts
4
+
5
+ interface DynamicTranslationOptions {
6
+ /** Overrides the locale resolved from the request. */
7
+ locale?: LocaleCode;
8
+ /** Overrides the per-call ceiling before the source text is served. */
9
+ timeoutMs?: number;
10
+ }
11
+ interface DynamicTranslationConfig {
12
+ apiKey?: string;
13
+ timeoutMs?: number;
14
+ batchWindowMs?: number;
15
+ }
16
+ /** Optional: the key otherwise comes from WEGLOT_API_KEY. */
17
+ declare function configureDynamicTranslation(next: DynamicTranslationConfig): void;
18
+ /** Translate a string that only exists at runtime: `await tDynamic(post.title)`. */
19
+ declare function tDynamic(text: string, options?: DynamicTranslationOptions): Promise<string>;
20
+ /**
21
+ * Translate an HTML fragment, split into segments the way the proxy splits a
22
+ * page, so a sentence wrapped in `<strong>` travels whole.
23
+ */
24
+ declare function tDynamicHtml(html: string, options?: DynamicTranslationOptions): Promise<string>;
25
+ /** Translates several strings in one pass, sharing a single request. */
26
+ declare function tDynamicAll(texts: string[], options?: DynamicTranslationOptions): Promise<string[]>;
27
+ //#endregion
28
+ export { DynamicTranslationConfig, DynamicTranslationOptions, configureDynamicTranslation, tDynamic, tDynamicAll, tDynamicHtml };
29
+ //# sourceMappingURL=translate-dynamic.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"translate-dynamic.d.cts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;AAsDgB,UAvBC,yBAAA,CAuB0B;EA6IrB;EAwBA,MAAA,CAAA,EA1LX,UA0LuB;EAqBZ;;;UA1ML,wBAAA;;;;;;iBAgBD,2BAAA,OACR;;iBA4Ic,QAAA,yBAEX,4BACR;;;;;iBAqBmB,YAAA,yBAEX,4BACR;;iBAkBmB,WAAA,4BAEX,4BACR"}
@@ -0,0 +1,29 @@
1
+ import { LocaleCode } from "../locale.mjs";
2
+
3
+ //#region src/runtime/translate-dynamic.d.ts
4
+
5
+ interface DynamicTranslationOptions {
6
+ /** Overrides the locale resolved from the request. */
7
+ locale?: LocaleCode;
8
+ /** Overrides the per-call ceiling before the source text is served. */
9
+ timeoutMs?: number;
10
+ }
11
+ interface DynamicTranslationConfig {
12
+ apiKey?: string;
13
+ timeoutMs?: number;
14
+ batchWindowMs?: number;
15
+ }
16
+ /** Optional: the key otherwise comes from WEGLOT_API_KEY. */
17
+ declare function configureDynamicTranslation(next: DynamicTranslationConfig): void;
18
+ /** Translate a string that only exists at runtime: `await tDynamic(post.title)`. */
19
+ declare function tDynamic(text: string, options?: DynamicTranslationOptions): Promise<string>;
20
+ /**
21
+ * Translate an HTML fragment, split into segments the way the proxy splits a
22
+ * page, so a sentence wrapped in `<strong>` travels whole.
23
+ */
24
+ declare function tDynamicHtml(html: string, options?: DynamicTranslationOptions): Promise<string>;
25
+ /** Translates several strings in one pass, sharing a single request. */
26
+ declare function tDynamicAll(texts: string[], options?: DynamicTranslationOptions): Promise<string[]>;
27
+ //#endregion
28
+ export { DynamicTranslationConfig, DynamicTranslationOptions, configureDynamicTranslation, tDynamic, tDynamicAll, tDynamicHtml };
29
+ //# sourceMappingURL=translate-dynamic.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"translate-dynamic.d.mts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;AAsDgB,UAvBC,yBAAA,CAuB0B;EA6IrB;EAwBA,MAAA,CAAA,EA1LX,UA0LuB;EAqBZ;;;UA1ML,wBAAA;;;;;;iBAgBD,2BAAA,OACR;;iBA4Ic,QAAA,yBAEX,4BACR;;;;;iBAqBmB,YAAA,yBAEX,4BACR;;iBAkBmB,WAAA,4BAEX,4BACR"}
@@ -0,0 +1,139 @@
1
+ import { logger } from "../utils/logger.mjs";
2
+ import { withTimeout } from "../utils/timeout.mjs";
3
+ import { WORD_TYPE } from "../translators/weglot/definitions/definitions.generated.mjs";
4
+ import { WeglotApiClient } from "../translators/weglot/api-client.mjs";
5
+ import { HtmlSegmenter } from "./html/segmenter.mjs";
6
+ import { cache } from "react";
7
+ import { apiLocales, sourceLocale, translationEngine } from "@weglot/translate-react/virtual/config";
8
+ import { getServerLocale } from "@weglot/translate-react/virtual/locale/server";
9
+
10
+ //#region src/runtime/translate-dynamic.ts
11
+ /**
12
+ * Runtime translation for content the compiler cannot see — a CMS title, an API
13
+ * record. No cache: the API already stores repeated segments.
14
+ */
15
+ /** Matches the translate API's own limit, as in the build-time translator. */
16
+ const MAX_WORDS_PER_REQUEST = 100;
17
+ /** Batches are shared across concurrent renders, so a busy server queues many pages. */
18
+ const MAX_CONCURRENT_REQUESTS = 4;
19
+ let config = {
20
+ apiKey: void 0,
21
+ timeoutMs: 500,
22
+ batchWindowMs: 5
23
+ };
24
+ /** Optional: the key otherwise comes from WEGLOT_API_KEY. */
25
+ function configureDynamicTranslation(next) {
26
+ config = {
27
+ ...config,
28
+ ...next
29
+ };
30
+ }
31
+ function resolveApiKey() {
32
+ return config.apiKey ?? process.env.WEGLOT_API_KEY;
33
+ }
34
+ const queues = /* @__PURE__ */ new Map();
35
+ const timers = /* @__PURE__ */ new Map();
36
+ const batchKey = (locale, timeoutMs) => `${locale}\u0000${timeoutMs}`;
37
+ /** One map per request, so a title rendered twice is translated once. Outside a
38
+ * render, `cache` has nothing to key on and calls stand alone. */
39
+ const requestMemo = cache(() => /* @__PURE__ */ new Map());
40
+ function memoFor() {
41
+ try {
42
+ return requestMemo();
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+ function enqueue(locale, text, timeoutMs, type) {
48
+ const key = batchKey(locale, timeoutMs);
49
+ return new Promise((resolve) => {
50
+ const queue = queues.get(key) ?? [];
51
+ queue.push({
52
+ text,
53
+ type,
54
+ resolve
55
+ });
56
+ queues.set(key, queue);
57
+ if (!timers.has(key)) timers.set(key, setTimeout(() => void flush(key, locale, timeoutMs), config.batchWindowMs));
58
+ });
59
+ }
60
+ async function flush(key, locale, timeoutMs) {
61
+ timers.delete(key);
62
+ const queue = queues.get(key) ?? [];
63
+ queues.delete(key);
64
+ if (queue.length === 0) return;
65
+ const apiKey = resolveApiKey();
66
+ if (!apiKey) {
67
+ 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));
69
+ return;
70
+ }
71
+ const client = new WeglotApiClient(apiKey);
72
+ const chunks = [];
73
+ for (let i = 0; i < queue.length; i += MAX_WORDS_PER_REQUEST) chunks.push(queue.slice(i, i + MAX_WORDS_PER_REQUEST));
74
+ const deadline = Date.now() + timeoutMs;
75
+ let next = 0;
76
+ const worker = async () => {
77
+ while (next < chunks.length) {
78
+ const chunk = chunks[next++];
79
+ if (Date.now() >= deadline) {
80
+ chunk.forEach((word) => word.resolve(word.text));
81
+ continue;
82
+ }
83
+ try {
84
+ const 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
+ }), deadline - Date.now(), `Weglot dynamic translation to ${locale}`);
90
+ chunk.forEach((word, index) => {
91
+ const result = translated[index];
92
+ if (result === word.text) logger.debug(`Weglot returned dynamic content unchanged for locale "${locale}".`);
93
+ word.resolve(result ?? word.text);
94
+ });
95
+ } catch (error) {
96
+ logger.warn(`Dynamic translation to "${locale}" failed, serving source text: ${error instanceof Error ? error.message : String(error)}`);
97
+ chunk.forEach((word) => word.resolve(word.text));
98
+ }
99
+ }
100
+ };
101
+ await Promise.all(Array.from({ length: Math.min(MAX_CONCURRENT_REQUESTS, chunks.length) }, worker));
102
+ }
103
+ /** Translate a string that only exists at runtime: `await tDynamic(post.title)`. */
104
+ async function tDynamic(text, options = {}) {
105
+ if (!text.trim()) return text;
106
+ const locale = options.locale ?? await getServerLocale();
107
+ if (!locale || locale === sourceLocale) return text;
108
+ const timeoutMs = options.timeoutMs ?? config.timeoutMs;
109
+ const memo = memoFor();
110
+ const key = `${batchKey(locale, timeoutMs)}\u0000${text}`;
111
+ const existing = memo?.get(key);
112
+ if (existing) return existing;
113
+ const pending = enqueue(locale, text, timeoutMs);
114
+ memo?.set(key, pending);
115
+ return pending;
116
+ }
117
+ /**
118
+ * Translate an HTML fragment, split into segments the way the proxy splits a
119
+ * page, so a sentence wrapped in `<strong>` travels whole.
120
+ */
121
+ async function tDynamicHtml(html, options = {}) {
122
+ if (!html.trim()) return html;
123
+ const locale = options.locale ?? await getServerLocale();
124
+ if (!locale || locale === sourceLocale) return html;
125
+ const timeoutMs = options.timeoutMs ?? config.timeoutMs;
126
+ const segmenter = new HtmlSegmenter(html, translationEngine);
127
+ const segments = segmenter.extract();
128
+ if (segments.length === 0) return html;
129
+ const translated = await Promise.all(segments.map((segment) => enqueue(locale, segment.w, timeoutMs, segment.t)));
130
+ return segmenter.apply(translated);
131
+ }
132
+ /** Translates several strings in one pass, sharing a single request. */
133
+ async function tDynamicAll(texts, options = {}) {
134
+ return Promise.all(texts.map((text) => tDynamic(text, options)));
135
+ }
136
+
137
+ //#endregion
138
+ export { configureDynamicTranslation, tDynamic, tDynamicAll, tDynamicHtml };
139
+ //# sourceMappingURL=translate-dynamic.mjs.map
@@ -0,0 +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 { apiLocales, sourceLocale } 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);\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 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 }),\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 === 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":"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"}
@@ -0,0 +1,37 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_logger = require('../utils/logger.cjs');
3
+ let fs_promises = require("fs/promises");
4
+ let path = require("path");
5
+
6
+ //#region src/translation-server/logger.ts
7
+ /**
8
+ * Such weird separation of file writer from logger
9
+ * is needed to avoid leaking node deps to the client build in next,
10
+ * but still keep the main logger logic in one place.
11
+ */
12
+ /**
13
+ * Create a file writer function for a specific log file
14
+ */
15
+ function createFileWriter(filePath, plainPrefix = "[Weglot]") {
16
+ let writeQueue = Promise.resolve();
17
+ return (level, message) => {
18
+ writeQueue = writeQueue.then(async () => {
19
+ try {
20
+ const logLine = `${(/* @__PURE__ */ new Date()).toISOString()} [${level.toUpperCase()}] ${plainPrefix} ${message}\n`;
21
+ await Promise.race([(0, fs_promises.appendFile)(filePath, logLine, "utf-8"), new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("File write timeout")), 1e3))]);
22
+ } catch (error) {}
23
+ }).catch(() => {});
24
+ };
25
+ }
26
+ let logger = void 0;
27
+ function getLogger(config) {
28
+ if (!logger) logger = new require_logger.Logger({
29
+ enableConsole: false,
30
+ enableDebug: true,
31
+ writeToFile: createFileWriter((0, path.join)(config.sourceRoot, config.weglotDir, "translation-server.log"))
32
+ });
33
+ return logger;
34
+ }
35
+
36
+ //#endregion
37
+ exports.getLogger = getLogger;
@@ -0,0 +1,37 @@
1
+ import { Logger } from "../utils/logger.mjs";
2
+ import { appendFile } from "fs/promises";
3
+ import { join } from "path";
4
+
5
+ //#region src/translation-server/logger.ts
6
+ /**
7
+ * Such weird separation of file writer from logger
8
+ * is needed to avoid leaking node deps to the client build in next,
9
+ * but still keep the main logger logic in one place.
10
+ */
11
+ /**
12
+ * Create a file writer function for a specific log file
13
+ */
14
+ function createFileWriter(filePath, plainPrefix = "[Weglot]") {
15
+ let writeQueue = Promise.resolve();
16
+ return (level, message) => {
17
+ writeQueue = writeQueue.then(async () => {
18
+ try {
19
+ const logLine = `${(/* @__PURE__ */ new Date()).toISOString()} [${level.toUpperCase()}] ${plainPrefix} ${message}\n`;
20
+ await Promise.race([appendFile(filePath, logLine, "utf-8"), new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("File write timeout")), 1e3))]);
21
+ } catch (error) {}
22
+ }).catch(() => {});
23
+ };
24
+ }
25
+ let logger = void 0;
26
+ function getLogger(config) {
27
+ if (!logger) logger = new Logger({
28
+ enableConsole: false,
29
+ enableDebug: true,
30
+ writeToFile: createFileWriter(join(config.sourceRoot, config.weglotDir, "translation-server.log"))
31
+ });
32
+ return logger;
33
+ }
34
+
35
+ //#endregion
36
+ export { getLogger };
37
+ //# sourceMappingURL=logger.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.mjs","names":["writeQueue: Promise<void>","logger: Logger | undefined"],"sources":["../../src/translation-server/logger.ts"],"sourcesContent":["import { Logger, type LogLevel } from \"../utils/logger\";\nimport { join } from \"path\";\nimport type { TranslationMiddlewareConfig } from \"../types\";\n\n/**\n * Such weird separation of file writer from logger\n * is needed to avoid leaking node deps to the client build in next,\n * but still keep the main logger logic in one place.\n */\nimport { appendFile } from \"fs/promises\";\n\n/**\n * Create a file writer function for a specific log file\n */\nexport function createFileWriter(\n filePath: string,\n plainPrefix: string = \"[Weglot]\",\n) {\n let writeQueue: Promise<void> = Promise.resolve();\n\n return (level: LogLevel, message: string) => {\n writeQueue = writeQueue\n .then(async () => {\n try {\n const timestamp = new Date().toISOString();\n const logLine = `${timestamp} [${level.toUpperCase()}] ${plainPrefix} ${message}\\n`;\n\n await Promise.race([\n appendFile(filePath, logLine, \"utf-8\"),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error(\"File write timeout\")), 1000),\n ),\n ]);\n } catch (error) {\n // Silently fail to avoid breaking the application\n }\n })\n .catch(() => {});\n };\n}\n\nlet logger: Logger | undefined = undefined;\n\nexport function getLogger(config: TranslationMiddlewareConfig) {\n if (!logger) {\n const translationServerLogPath = join(\n config.sourceRoot,\n config.weglotDir,\n \"translation-server.log\",\n );\n logger = new Logger({\n enableConsole: false,\n enableDebug: true,\n writeToFile: createFileWriter(translationServerLogPath),\n });\n }\n return logger;\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,SAAgB,iBACd,UACA,cAAsB,YACtB;CACA,IAAIA,aAA4B,QAAQ,SAAS;AAEjD,SAAQ,OAAiB,YAAoB;AAC3C,eAAa,WACV,KAAK,YAAY;AAChB,OAAI;IAEF,MAAM,UAAU,oBADE,IAAI,MAAM,EAAC,aAAa,CACb,IAAI,MAAM,aAAa,CAAC,IAAI,YAAY,GAAG,QAAQ;AAEhF,UAAM,QAAQ,KAAK,CACjB,WAAW,UAAU,SAAS,QAAQ,EACtC,IAAI,SAAS,GAAG,WACd,iBAAiB,uBAAO,IAAI,MAAM,qBAAqB,CAAC,EAAE,IAAK,CAChE,CACF,CAAC;YACK,OAAO;IAGhB,CACD,YAAY,GAAG;;;AAItB,IAAIC,SAA6B;AAEjC,SAAgB,UAAU,QAAqC;AAC7D,KAAI,CAAC,OAMH,UAAS,IAAI,OAAO;EAClB,eAAe;EACf,aAAa;EACb,aAAa,iBARkB,KAC/B,OAAO,YACP,OAAO,WACP,yBACD,CAIwD;EACxD,CAAC;AAEJ,QAAO"}