@weglot/translate-react 0.0.0-stage → 0.2.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 +199 -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 +210 -0
  18. package/build/plugin/build-translator.mjs +208 -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 +227 -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 +229 -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 +144 -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 +141 -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 +139 -0
  229. package/build/translators/translation-service.mjs +140 -0
  230. package/build/translators/translation-service.mjs.map +1 -0
  231. package/build/translators/weglot/api-client.cjs +131 -0
  232. package/build/translators/weglot/api-client.mjs +130 -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 +43 -0
  238. package/build/translators/weglot/engine.mjs +40 -0
  239. package/build/translators/weglot/engine.mjs.map +1 -0
  240. package/build/translators/weglot/translator.cjs +67 -0
  241. package/build/translators/weglot/translator.mjs +68 -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 +153 -0
  247. package/build/types.d.cts.map +1 -0
  248. package/build/types.d.mts +153 -0
  249. package/build/types.d.mts.map +1 -0
  250. package/build/utils/config-factory.cjs +100 -0
  251. package/build/utils/config-factory.mjs +97 -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 +58 -0
  269. package/build/virtual/code-generator.mjs +57 -0
  270. package/build/virtual/code-generator.mjs.map +1 -0
  271. package/build/virtual/config.cjs +19 -0
  272. package/build/virtual/config.d.cts +15 -0
  273. package/build/virtual/config.d.cts.map +1 -0
  274. package/build/virtual/config.d.mts +15 -0
  275. package/build/virtual/config.d.mts.map +1 -0
  276. package/build/virtual/config.mjs +14 -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,128 @@
1
+ const require_engine = require('./engine.cjs');
2
+
3
+ //#region src/translators/weglot/wire-format.ts
4
+ /**
5
+ * Converts the stored ICU form to the wire form the API accepts and back:
6
+ * `Read <strong0>this</strong0>` ↔ `Read <strong wg-1="">this</strong>`.
7
+ */
8
+ const STORED_TOKEN = /\{[^{}]+\}|<([A-Za-z][A-Za-z0-9]*)\s*>|<\/([A-Za-z][A-Za-z0-9]*)\s*>/g;
9
+ const WIRE_TOKEN = /<([A-Za-z][A-Za-z0-9]*)\s+wg-(\d+)(?:="")?\s*>|<\/([A-Za-z][A-Za-z0-9]*)\s*>/g;
10
+ const TAG_SHAPED = /<\/?([A-Za-z][A-Za-z0-9]*)(\s[^<>]*?)?\s*\/?>/g;
11
+ const ICU_QUOTE_BEFORE_SYNTAX = /(?<!')'(?=[{}<])/g;
12
+ const VOID_TAGS = new Set([
13
+ "area",
14
+ "base",
15
+ "br",
16
+ "col",
17
+ "embed",
18
+ "hr",
19
+ "img",
20
+ "input",
21
+ "link",
22
+ "meta",
23
+ "source",
24
+ "track",
25
+ "wbr"
26
+ ]);
27
+ function wireTagFor(icuName, tags, fallbackTag) {
28
+ const base = icuName.replace(/\d+$/, "");
29
+ if (VOID_TAGS.has(base)) return fallbackTag;
30
+ return tags.has(base) ? base : fallbackTag;
31
+ }
32
+ function encodeForApi(text, engine = require_engine.DEFAULT_MODERN_ENGINE) {
33
+ const tags = require_engine.mergeableTagsFor(engine);
34
+ const fallbackTag = require_engine.fallbackWireTagFor(tags);
35
+ const slots = [];
36
+ const openSlots = [];
37
+ let wire = "";
38
+ let cursor = 0;
39
+ if (fallbackTag === void 0) {
40
+ const carriesMarkup = STORED_TOKEN.test(text);
41
+ STORED_TOKEN.lastIndex = 0;
42
+ return {
43
+ wire: text,
44
+ restore: (translated) => ({
45
+ text: translated,
46
+ damaged: false
47
+ }),
48
+ encodable: !carriesMarkup
49
+ };
50
+ }
51
+ for (const match of text.matchAll(STORED_TOKEN)) {
52
+ wire += text.slice(cursor, match.index);
53
+ cursor = match.index + match[0].length;
54
+ const [token, openName, closeName] = match;
55
+ if (openName !== void 0) {
56
+ const slot = {
57
+ kind: "tag",
58
+ icuName: openName,
59
+ wireName: wireTagFor(openName, tags, fallbackTag)
60
+ };
61
+ openSlots.push(slots.push(slot) - 1);
62
+ wire += `<${slot.wireName} wg-${slots.length}="">`;
63
+ } else if (closeName !== void 0) {
64
+ const index = openSlots.pop();
65
+ const slot = index === void 0 ? void 0 : slots[index];
66
+ if (slot?.kind === "tag") wire += `</${slot.wireName}>`;
67
+ } else {
68
+ slots.push({
69
+ kind: "placeholder",
70
+ value: token
71
+ });
72
+ wire += `<${fallbackTag} wg-${slots.length}=""></${fallbackTag}>`;
73
+ }
74
+ }
75
+ wire += text.slice(cursor);
76
+ return {
77
+ wire,
78
+ restore: (translated) => restore(translated, slots),
79
+ encodable: true
80
+ };
81
+ }
82
+ function restore(translated, slots) {
83
+ const stack = [];
84
+ const seen = /* @__PURE__ */ new Set();
85
+ let text = "";
86
+ let cursor = 0;
87
+ let suppressed = 0;
88
+ for (const match of translated.matchAll(WIRE_TOKEN)) {
89
+ if (!suppressed) text += translated.slice(cursor, match.index);
90
+ cursor = match.index + match[0].length;
91
+ const [, , markerIndex, closeName] = match;
92
+ if (markerIndex !== void 0) {
93
+ const index = Number(markerIndex) - 1;
94
+ const slot = slots[index];
95
+ if (!slot) {
96
+ stack.push(void 0);
97
+ continue;
98
+ }
99
+ seen.add(index);
100
+ stack.push(slot);
101
+ if (slot.kind === "placeholder") {
102
+ if (!suppressed) text += slot.value;
103
+ suppressed++;
104
+ } else if (!suppressed) text += `<${slot.icuName}>`;
105
+ } else if (closeName !== void 0) {
106
+ const slot = stack.pop();
107
+ if (!slot) continue;
108
+ if (slot.kind === "placeholder") suppressed--;
109
+ else if (!suppressed) text += `</${slot.icuName}>`;
110
+ }
111
+ }
112
+ if (!suppressed) text += translated.slice(cursor);
113
+ text = text.replace(ICU_QUOTE_BEFORE_SYNTAX, "''");
114
+ const lostSlot = slots.some((_, index) => !seen.has(index));
115
+ return {
116
+ text,
117
+ damaged: lostSlot || hasStrayMarkup(text, slots)
118
+ };
119
+ }
120
+ /** Invented markup or a leftover marker would reach intl-messageformat as an
121
+ * unknown tag and throw at render time. */
122
+ function hasStrayMarkup(text, slots) {
123
+ const known = new Set(slots.flatMap((slot) => slot.kind === "tag" ? [slot.icuName] : []));
124
+ return [...text.matchAll(TAG_SHAPED)].some(([, name, attributes]) => !known.has(name) || attributes !== void 0);
125
+ }
126
+
127
+ //#endregion
128
+ exports.encodeForApi = encodeForApi;
@@ -0,0 +1,129 @@
1
+ import { DEFAULT_MODERN_ENGINE, fallbackWireTagFor, mergeableTagsFor } from "./engine.mjs";
2
+
3
+ //#region src/translators/weglot/wire-format.ts
4
+ /**
5
+ * Converts the stored ICU form to the wire form the API accepts and back:
6
+ * `Read <strong0>this</strong0>` ↔ `Read <strong wg-1="">this</strong>`.
7
+ */
8
+ const STORED_TOKEN = /\{[^{}]+\}|<([A-Za-z][A-Za-z0-9]*)\s*>|<\/([A-Za-z][A-Za-z0-9]*)\s*>/g;
9
+ const WIRE_TOKEN = /<([A-Za-z][A-Za-z0-9]*)\s+wg-(\d+)(?:="")?\s*>|<\/([A-Za-z][A-Za-z0-9]*)\s*>/g;
10
+ const TAG_SHAPED = /<\/?([A-Za-z][A-Za-z0-9]*)(\s[^<>]*?)?\s*\/?>/g;
11
+ const ICU_QUOTE_BEFORE_SYNTAX = /(?<!')'(?=[{}<])/g;
12
+ const VOID_TAGS = new Set([
13
+ "area",
14
+ "base",
15
+ "br",
16
+ "col",
17
+ "embed",
18
+ "hr",
19
+ "img",
20
+ "input",
21
+ "link",
22
+ "meta",
23
+ "source",
24
+ "track",
25
+ "wbr"
26
+ ]);
27
+ function wireTagFor(icuName, tags, fallbackTag) {
28
+ const base = icuName.replace(/\d+$/, "");
29
+ if (VOID_TAGS.has(base)) return fallbackTag;
30
+ return tags.has(base) ? base : fallbackTag;
31
+ }
32
+ function encodeForApi(text, engine = DEFAULT_MODERN_ENGINE) {
33
+ const tags = mergeableTagsFor(engine);
34
+ const fallbackTag = fallbackWireTagFor(tags);
35
+ const slots = [];
36
+ const openSlots = [];
37
+ let wire = "";
38
+ let cursor = 0;
39
+ if (fallbackTag === void 0) {
40
+ const carriesMarkup = STORED_TOKEN.test(text);
41
+ STORED_TOKEN.lastIndex = 0;
42
+ return {
43
+ wire: text,
44
+ restore: (translated) => ({
45
+ text: translated,
46
+ damaged: false
47
+ }),
48
+ encodable: !carriesMarkup
49
+ };
50
+ }
51
+ for (const match of text.matchAll(STORED_TOKEN)) {
52
+ wire += text.slice(cursor, match.index);
53
+ cursor = match.index + match[0].length;
54
+ const [token, openName, closeName] = match;
55
+ if (openName !== void 0) {
56
+ const slot = {
57
+ kind: "tag",
58
+ icuName: openName,
59
+ wireName: wireTagFor(openName, tags, fallbackTag)
60
+ };
61
+ openSlots.push(slots.push(slot) - 1);
62
+ wire += `<${slot.wireName} wg-${slots.length}="">`;
63
+ } else if (closeName !== void 0) {
64
+ const index = openSlots.pop();
65
+ const slot = index === void 0 ? void 0 : slots[index];
66
+ if (slot?.kind === "tag") wire += `</${slot.wireName}>`;
67
+ } else {
68
+ slots.push({
69
+ kind: "placeholder",
70
+ value: token
71
+ });
72
+ wire += `<${fallbackTag} wg-${slots.length}=""></${fallbackTag}>`;
73
+ }
74
+ }
75
+ wire += text.slice(cursor);
76
+ return {
77
+ wire,
78
+ restore: (translated) => restore(translated, slots),
79
+ encodable: true
80
+ };
81
+ }
82
+ function restore(translated, slots) {
83
+ const stack = [];
84
+ const seen = /* @__PURE__ */ new Set();
85
+ let text = "";
86
+ let cursor = 0;
87
+ let suppressed = 0;
88
+ for (const match of translated.matchAll(WIRE_TOKEN)) {
89
+ if (!suppressed) text += translated.slice(cursor, match.index);
90
+ cursor = match.index + match[0].length;
91
+ const [, , markerIndex, closeName] = match;
92
+ if (markerIndex !== void 0) {
93
+ const index = Number(markerIndex) - 1;
94
+ const slot = slots[index];
95
+ if (!slot) {
96
+ stack.push(void 0);
97
+ continue;
98
+ }
99
+ seen.add(index);
100
+ stack.push(slot);
101
+ if (slot.kind === "placeholder") {
102
+ if (!suppressed) text += slot.value;
103
+ suppressed++;
104
+ } else if (!suppressed) text += `<${slot.icuName}>`;
105
+ } else if (closeName !== void 0) {
106
+ const slot = stack.pop();
107
+ if (!slot) continue;
108
+ if (slot.kind === "placeholder") suppressed--;
109
+ else if (!suppressed) text += `</${slot.icuName}>`;
110
+ }
111
+ }
112
+ if (!suppressed) text += translated.slice(cursor);
113
+ text = text.replace(ICU_QUOTE_BEFORE_SYNTAX, "''");
114
+ const lostSlot = slots.some((_, index) => !seen.has(index));
115
+ return {
116
+ text,
117
+ damaged: lostSlot || hasStrayMarkup(text, slots)
118
+ };
119
+ }
120
+ /** Invented markup or a leftover marker would reach intl-messageformat as an
121
+ * unknown tag and throw at render time. */
122
+ function hasStrayMarkup(text, slots) {
123
+ const known = new Set(slots.flatMap((slot) => slot.kind === "tag" ? [slot.icuName] : []));
124
+ return [...text.matchAll(TAG_SHAPED)].some(([, name, attributes]) => !known.has(name) || attributes !== void 0);
125
+ }
126
+
127
+ //#endregion
128
+ export { encodeForApi };
129
+ //# sourceMappingURL=wire-format.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire-format.mjs","names":["VOID_TAGS: ReadonlySet<string>","slots: Slot[]","openSlots: number[]","slot: Slot","stack: (Slot | undefined)[]"],"sources":["../../../src/translators/weglot/wire-format.ts"],"sourcesContent":["/**\n * Converts the stored ICU form to the wire form the API accepts and back:\n * `Read <strong0>this</strong0>` ↔ `Read <strong wg-1=\"\">this</strong>`.\n */\n\nimport {\n DEFAULT_MODERN_ENGINE,\n fallbackWireTagFor,\n mergeableTagsFor,\n} from \"./engine\";\n\n// A placeholder, an opening ICU tag, or a closing ICU tag in the stored form.\nconst STORED_TOKEN =\n /\\{[^{}]+\\}|<([A-Za-z][A-Za-z0-9]*)\\s*>|<\\/([A-Za-z][A-Za-z0-9]*)\\s*>/g;\n\n// An opening tag carrying a marker, or any closing tag, in the API response.\n// The `=\"\"` is optional: machine translation sometimes drops the empty value.\nconst WIRE_TOKEN =\n /<([A-Za-z][A-Za-z0-9]*)\\s+wg-(\\d+)(?:=\"\")?\\s*>|<\\/([A-Za-z][A-Za-z0-9]*)\\s*>/g;\n\n// Anything shaped like a tag, with its attributes if it carries any: a\n// leftover marker or an element the engine invented.\nconst TAG_SHAPED = /<\\/?([A-Za-z][A-Za-z0-9]*)(\\s[^<>]*?)?\\s*\\/?>/g;\n\n// A lone apostrophe before markup opens an ICU quoted literal, turning the\n// markup into text (\"l'<strong>\"). Doubling keeps it text; a pair is escaped.\nconst ICU_QUOTE_BEFORE_SYNTAX = /(?<!')'(?=[{}<])/g;\n\ntype Slot =\n | { kind: \"placeholder\"; value: string }\n | { kind: \"tag\"; icuName: string; wireName: string };\n\nexport interface RestoredTranslation {\n text: string;\n /** True when a marker went missing or the result still holds stray markup. */\n damaged: boolean;\n}\n\n// The wire form always sends a pair, and `<br wg-1=\"\"></br>` comes back with a\n// stray closing tag. These travel under the fallback name; restore maps by index.\nconst VOID_TAGS: ReadonlySet<string> = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\nfunction wireTagFor(\n icuName: string,\n tags: ReadonlySet<string>,\n fallbackTag: string,\n): string {\n const base = icuName.replace(/\\d+$/, \"\");\n if (VOID_TAGS.has(base)) return fallbackTag;\n return tags.has(base) ? base : fallbackTag;\n}\n\nexport interface EncodedForApi {\n wire: string;\n restore: (translated: string) => RestoredTranslation;\n /** False when the engine permits no tag for the markup (engine 1 only), so the\n * caller keeps the source text. */\n encodable: boolean;\n}\n\nexport function encodeForApi(\n text: string,\n engine: number = DEFAULT_MODERN_ENGINE,\n): EncodedForApi {\n const tags = mergeableTagsFor(engine);\n const fallbackTag = fallbackWireTagFor(tags);\n const slots: Slot[] = [];\n const openSlots: number[] = [];\n let wire = \"\";\n let cursor = 0;\n\n if (fallbackTag === undefined) {\n const carriesMarkup = STORED_TOKEN.test(text);\n STORED_TOKEN.lastIndex = 0;\n return {\n wire: text,\n restore: (translated) => ({ text: translated, damaged: false }),\n encodable: !carriesMarkup,\n };\n }\n\n for (const match of text.matchAll(STORED_TOKEN)) {\n wire += text.slice(cursor, match.index);\n cursor = match.index + match[0].length;\n\n const [token, openName, closeName] = match;\n\n if (openName !== undefined) {\n const slot: Slot = {\n kind: \"tag\",\n icuName: openName,\n wireName: wireTagFor(openName, tags, fallbackTag),\n };\n openSlots.push(slots.push(slot) - 1);\n wire += `<${slot.wireName} wg-${slots.length}=\"\">`;\n } else if (closeName !== undefined) {\n const index = openSlots.pop();\n const slot = index === undefined ? undefined : slots[index];\n // A closing tag with no opening cannot be mapped back; drop it.\n if (slot?.kind === \"tag\") {\n wire += `</${slot.wireName}>`;\n }\n } else {\n slots.push({ kind: \"placeholder\", value: token });\n wire += `<${fallbackTag} wg-${slots.length}=\"\"></${fallbackTag}>`;\n }\n }\n\n wire += text.slice(cursor);\n\n return {\n wire,\n restore: (translated) => restore(translated, slots),\n encodable: true,\n };\n}\n\nfunction restore(translated: string, slots: Slot[]): RestoredTranslation {\n const stack: (Slot | undefined)[] = [];\n const seen = new Set<number>();\n let text = \"\";\n let cursor = 0;\n // Content translation put inside an empty placeholder tag is dropped.\n let suppressed = 0;\n\n for (const match of translated.matchAll(WIRE_TOKEN)) {\n if (!suppressed) {\n text += translated.slice(cursor, match.index);\n }\n cursor = match.index + match[0].length;\n\n const [, , markerIndex, closeName] = match;\n\n if (markerIndex !== undefined) {\n const index = Number(markerIndex) - 1;\n const slot = slots[index];\n if (!slot) {\n // Marker we never sent: keep the content, drop the tag.\n stack.push(undefined);\n continue;\n }\n seen.add(index);\n stack.push(slot);\n if (slot.kind === \"placeholder\") {\n if (!suppressed) text += slot.value;\n suppressed++;\n } else if (!suppressed) {\n text += `<${slot.icuName}>`;\n }\n } else if (closeName !== undefined) {\n const slot = stack.pop();\n if (!slot) continue;\n if (slot.kind === \"placeholder\") {\n suppressed--;\n } else if (!suppressed) {\n text += `</${slot.icuName}>`;\n }\n }\n }\n\n if (!suppressed) {\n text += translated.slice(cursor);\n }\n\n text = text.replace(ICU_QUOTE_BEFORE_SYNTAX, \"''\");\n\n const lostSlot = slots.some((_, index) => !seen.has(index));\n return { text, damaged: lostSlot || hasStrayMarkup(text, slots) };\n}\n\n/** Invented markup or a leftover marker would reach intl-messageformat as an\n * unknown tag and throw at render time. */\nfunction hasStrayMarkup(text: string, slots: Slot[]): boolean {\n const known = new Set(\n slots.flatMap((slot) => (slot.kind === \"tag\" ? [slot.icuName] : [])),\n );\n // Only tag-shaped leftovers matter; a bare \"<\" is legitimate text.\n return [...text.matchAll(TAG_SHAPED)].some(\n ([, name, attributes]) => !known.has(name) || attributes !== undefined,\n );\n}\n"],"mappings":"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"}
@@ -0,0 +1,153 @@
1
+ import { LocaleCode } from "./locale.cjs";
2
+
3
+ //#region src/types.d.ts
4
+
5
+ /**
6
+ * Cookie configuration for locale persistence
7
+ */
8
+ interface CookieConfig {
9
+ /**
10
+ * Name of the cookie to store the locale
11
+ * @default 'locale'
12
+ */
13
+ name: string;
14
+ /**
15
+ * Maximum age of the cookie in seconds
16
+ * @default 31536000 (1 year)
17
+ */
18
+ maxAge: number;
19
+ }
20
+ /**
21
+ * Locale persistence configuration
22
+ * Currently only supports cookie-based persistence
23
+ */
24
+ type LocalePersistenceConfig = {
25
+ type: "cookie";
26
+ config: CookieConfig;
27
+ };
28
+ /**
29
+ * Fields that are resolved internally (from the Weglot project settings or the
30
+ * environment) rather than provided by users.
31
+ */
32
+ type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "apiBaseUrl" | "weglotDir";
33
+ /**
34
+ * Configuration for @weglot/translate-react
35
+ */
36
+ type PartialWeglotConfig = Partial<Omit<WeglotConfig, WeglotInternalFields | "dev"> & {
37
+ dev: Partial<WeglotConfig["dev"]>;
38
+ }>;
39
+ type WeglotEnvironment = "development" | "production";
40
+ /**
41
+ * Weglot config with all the defaults applied
42
+ */
43
+ type WeglotConfig = {
44
+ /** Weglot project API key. Falls back to the WEGLOT_API_KEY env var. */
45
+ apiKey: string;
46
+ /**
47
+ * Root directory of the source code
48
+ */
49
+ sourceRoot: string;
50
+ /**
51
+ * Directory for weglot files, relative to sourceRoot (e.g. `src/weglot/`).
52
+ *
53
+ * Fixed; not publicly configurable.
54
+ *
55
+ * @default "weglot"
56
+ * @internal
57
+ */
58
+ weglotDir: string;
59
+ /**
60
+ * Environment mode
61
+ * Determines metadata file naming and translator behavior
62
+ *
63
+ * @default "production"
64
+ * @internal
65
+ */
66
+ environment: WeglotEnvironment;
67
+ /**
68
+ * Cache implementation type
69
+ * - "local": Local file system cache (default)
70
+ * - "remote": Remote cache (future)
71
+ *
72
+ * @default "local"
73
+ * @internal Since we do not support more types, there is no need to make it public, but it allows keeping the config in the single place
74
+ */
75
+ cacheType: "local";
76
+ /**
77
+ * The locale to translate from.
78
+ *
79
+ * Resolved from the Weglot project settings.
80
+ *
81
+ * @internal
82
+ */
83
+ sourceLocale: LocaleCode;
84
+ /**
85
+ * The locale(s) to translate to.
86
+ *
87
+ * Resolved from the Weglot project settings.
88
+ *
89
+ * @internal
90
+ */
91
+ targetLocales: LocaleCode[];
92
+ /** Public locale to the code the translate API expects, for languages with a
93
+ * custom code. Resolved from the project settings. @internal */
94
+ apiLocales: Record<string, LocaleCode>;
95
+ /** Inline elements allowed inside a segment, from the project settings.
96
+ * @internal */
97
+ translationEngine: number;
98
+ /** The project's regional API host, from the project settings. @internal */
99
+ apiBaseUrl: string;
100
+ /**
101
+ * Seconds to wait for translations Weglot is still generating. What is still
102
+ * missing then fails a `translate` build; in dev it shows up on a reload.
103
+ * Can be overridden by WEGLOT_TRANSLATION_TIMEOUT environment variable.
104
+ *
105
+ * @default 300 in a build, 10 in dev
106
+ */
107
+ translationTimeout: number;
108
+ /**
109
+ * Whether to require 'use i18n' directive
110
+ */
111
+ useDirective: boolean;
112
+ /**
113
+ * Which JSX attributes hold translatable text, per element, as deltas on the
114
+ * built-in list — `{ "*": ["!label"], PageTitle: ["subTitle"] }`. See the README.
115
+ */
116
+ translatableAttributes: Record<string, string[]>;
117
+ /**
118
+ * Development-specific settings
119
+ */
120
+ dev: {
121
+ /**
122
+ * Starting port for the translation server in development mode
123
+ * Server will try this port first, then increment if unavailable
124
+ *
125
+ * @default 60000
126
+ */
127
+ translationServerStartPort: number;
128
+ /**
129
+ * URL of the translation server in development mode if you manually start it
130
+ */
131
+ translationServerUrl?: string;
132
+ };
133
+ /**
134
+ * Locale persistence configuration
135
+ * Defines how locale changes should be persisted
136
+ *
137
+ * @default { type: 'cookie', config: { name: 'locale' } }
138
+ */
139
+ localePersistence: LocalePersistenceConfig;
140
+ /**
141
+ * Build mode for CI/production
142
+ * - "translate": Generate translations at build time, fail if translation fails (default)
143
+ * - "cache-only": Only use cached translations, fail if cache is incomplete
144
+ *
145
+ * Can be overridden by WEGLOT_BUILD_MODE environment variable
146
+ *
147
+ * @default "translate"
148
+ */
149
+ buildMode: "translate" | "cache-only";
150
+ };
151
+ //#endregion
152
+ export { CookieConfig, PartialWeglotConfig };
153
+ //# sourceMappingURL=types.d.cts.map
@@ -0,0 +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"}
@@ -0,0 +1,153 @@
1
+ import { LocaleCode } from "./locale.mjs";
2
+
3
+ //#region src/types.d.ts
4
+
5
+ /**
6
+ * Cookie configuration for locale persistence
7
+ */
8
+ interface CookieConfig {
9
+ /**
10
+ * Name of the cookie to store the locale
11
+ * @default 'locale'
12
+ */
13
+ name: string;
14
+ /**
15
+ * Maximum age of the cookie in seconds
16
+ * @default 31536000 (1 year)
17
+ */
18
+ maxAge: number;
19
+ }
20
+ /**
21
+ * Locale persistence configuration
22
+ * Currently only supports cookie-based persistence
23
+ */
24
+ type LocalePersistenceConfig = {
25
+ type: "cookie";
26
+ config: CookieConfig;
27
+ };
28
+ /**
29
+ * Fields that are resolved internally (from the Weglot project settings or the
30
+ * environment) rather than provided by users.
31
+ */
32
+ type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "apiBaseUrl" | "weglotDir";
33
+ /**
34
+ * Configuration for @weglot/translate-react
35
+ */
36
+ type PartialWeglotConfig = Partial<Omit<WeglotConfig, WeglotInternalFields | "dev"> & {
37
+ dev: Partial<WeglotConfig["dev"]>;
38
+ }>;
39
+ type WeglotEnvironment = "development" | "production";
40
+ /**
41
+ * Weglot config with all the defaults applied
42
+ */
43
+ type WeglotConfig = {
44
+ /** Weglot project API key. Falls back to the WEGLOT_API_KEY env var. */
45
+ apiKey: string;
46
+ /**
47
+ * Root directory of the source code
48
+ */
49
+ sourceRoot: string;
50
+ /**
51
+ * Directory for weglot files, relative to sourceRoot (e.g. `src/weglot/`).
52
+ *
53
+ * Fixed; not publicly configurable.
54
+ *
55
+ * @default "weglot"
56
+ * @internal
57
+ */
58
+ weglotDir: string;
59
+ /**
60
+ * Environment mode
61
+ * Determines metadata file naming and translator behavior
62
+ *
63
+ * @default "production"
64
+ * @internal
65
+ */
66
+ environment: WeglotEnvironment;
67
+ /**
68
+ * Cache implementation type
69
+ * - "local": Local file system cache (default)
70
+ * - "remote": Remote cache (future)
71
+ *
72
+ * @default "local"
73
+ * @internal Since we do not support more types, there is no need to make it public, but it allows keeping the config in the single place
74
+ */
75
+ cacheType: "local";
76
+ /**
77
+ * The locale to translate from.
78
+ *
79
+ * Resolved from the Weglot project settings.
80
+ *
81
+ * @internal
82
+ */
83
+ sourceLocale: LocaleCode;
84
+ /**
85
+ * The locale(s) to translate to.
86
+ *
87
+ * Resolved from the Weglot project settings.
88
+ *
89
+ * @internal
90
+ */
91
+ targetLocales: LocaleCode[];
92
+ /** Public locale to the code the translate API expects, for languages with a
93
+ * custom code. Resolved from the project settings. @internal */
94
+ apiLocales: Record<string, LocaleCode>;
95
+ /** Inline elements allowed inside a segment, from the project settings.
96
+ * @internal */
97
+ translationEngine: number;
98
+ /** The project's regional API host, from the project settings. @internal */
99
+ apiBaseUrl: string;
100
+ /**
101
+ * Seconds to wait for translations Weglot is still generating. What is still
102
+ * missing then fails a `translate` build; in dev it shows up on a reload.
103
+ * Can be overridden by WEGLOT_TRANSLATION_TIMEOUT environment variable.
104
+ *
105
+ * @default 300 in a build, 10 in dev
106
+ */
107
+ translationTimeout: number;
108
+ /**
109
+ * Whether to require 'use i18n' directive
110
+ */
111
+ useDirective: boolean;
112
+ /**
113
+ * Which JSX attributes hold translatable text, per element, as deltas on the
114
+ * built-in list — `{ "*": ["!label"], PageTitle: ["subTitle"] }`. See the README.
115
+ */
116
+ translatableAttributes: Record<string, string[]>;
117
+ /**
118
+ * Development-specific settings
119
+ */
120
+ dev: {
121
+ /**
122
+ * Starting port for the translation server in development mode
123
+ * Server will try this port first, then increment if unavailable
124
+ *
125
+ * @default 60000
126
+ */
127
+ translationServerStartPort: number;
128
+ /**
129
+ * URL of the translation server in development mode if you manually start it
130
+ */
131
+ translationServerUrl?: string;
132
+ };
133
+ /**
134
+ * Locale persistence configuration
135
+ * Defines how locale changes should be persisted
136
+ *
137
+ * @default { type: 'cookie', config: { name: 'locale' } }
138
+ */
139
+ localePersistence: LocalePersistenceConfig;
140
+ /**
141
+ * Build mode for CI/production
142
+ * - "translate": Generate translations at build time, fail if translation fails (default)
143
+ * - "cache-only": Only use cached translations, fail if cache is incomplete
144
+ *
145
+ * Can be overridden by WEGLOT_BUILD_MODE environment variable
146
+ *
147
+ * @default "translate"
148
+ */
149
+ buildMode: "translate" | "cache-only";
150
+ };
151
+ //#endregion
152
+ export { CookieConfig, PartialWeglotConfig };
153
+ //# sourceMappingURL=types.d.mts.map
@@ -0,0 +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"}
@@ -0,0 +1,100 @@
1
+ const require_api_client = require('../translators/weglot/api-client.cjs');
2
+ const require_engine = require('../translators/weglot/engine.cjs');
3
+ require("dotenv/config");
4
+
5
+ //#region src/utils/config-factory.ts
6
+ /**
7
+ * Config factory for creating LoaderConfig instances
8
+ */
9
+ /**
10
+ * Default configuration values
11
+ */
12
+ const DEFAULT_CONFIG = {
13
+ sourceRoot: "src",
14
+ weglotDir: "weglot",
15
+ useDirective: false,
16
+ translatableAttributes: {},
17
+ dev: { translationServerStartPort: 6e4 },
18
+ localePersistence: {
19
+ type: "cookie",
20
+ config: {
21
+ name: "locale",
22
+ maxAge: 31536e3
23
+ }
24
+ },
25
+ buildMode: "translate"
26
+ };
27
+ const DEFAULT_TRANSLATION_TIMEOUT = {
28
+ production: 300,
29
+ development: 10
30
+ };
31
+ function timeoutFromEnv() {
32
+ const raw = process.env.WEGLOT_TRANSLATION_TIMEOUT;
33
+ if (!raw) return void 0;
34
+ const value = Number(raw);
35
+ return Number.isFinite(value) && value >= 0 ? value : void 0;
36
+ }
37
+ /**
38
+ * Create a LoaderConfig with defaults applied
39
+ *
40
+ * @param options - Partial config to override defaults
41
+ * @returns Complete LoaderConfig with all defaults applied
42
+ *
43
+ */
44
+ function createWeglotConfig(options) {
45
+ const cleanOptions = { ...options };
46
+ const cleanObject = (obj) => {
47
+ if (!obj || typeof obj !== "object") return;
48
+ Object.keys(obj).forEach((key) => {
49
+ if (obj[key] === void 0) delete obj[key];
50
+ else if (obj[key] && typeof obj[key] === "object" && !Array.isArray(obj[key])) cleanObject(obj[key]);
51
+ });
52
+ };
53
+ cleanObject(cleanOptions);
54
+ const apiKey = cleanOptions.apiKey ?? process.env.WEGLOT_API_KEY;
55
+ if (!apiKey) throw new Error("Weglot project key is missing. Pass `apiKey` in the plugin options or set the WEGLOT_API_KEY environment variable.");
56
+ const environment = cleanOptions.environment ?? (process.env.NODE_ENV === "development" ? "development" : "production");
57
+ return {
58
+ ...DEFAULT_CONFIG,
59
+ ...cleanOptions,
60
+ apiKey,
61
+ sourceLocale: cleanOptions.sourceLocale ?? "",
62
+ targetLocales: cleanOptions.targetLocales ?? [],
63
+ apiLocales: cleanOptions.apiLocales ?? {},
64
+ translationEngine: require_engine.resolveTranslationEngine(cleanOptions.translationEngine),
65
+ apiBaseUrl: cleanOptions.apiBaseUrl ?? "",
66
+ translationTimeout: cleanOptions.translationTimeout ?? timeoutFromEnv() ?? DEFAULT_TRANSLATION_TIMEOUT[environment],
67
+ environment,
68
+ cacheType: cleanOptions.cacheType ?? "local",
69
+ dev: {
70
+ ...DEFAULT_CONFIG.dev,
71
+ ...cleanOptions.dev
72
+ },
73
+ localePersistence: {
74
+ ...DEFAULT_CONFIG.localePersistence,
75
+ ...cleanOptions.localePersistence,
76
+ config: {
77
+ ...DEFAULT_CONFIG.localePersistence.config,
78
+ ...cleanOptions.localePersistence?.config
79
+ }
80
+ }
81
+ };
82
+ }
83
+ /**
84
+ * Fetches source/target locales from the Weglot project settings.
85
+ * Idempotent: no-ops when locales are already resolved (e.g. passed
86
+ * through Next.js loader options).
87
+ */
88
+ async function resolveProjectLanguages(config, client = new require_api_client.WeglotApiClient(config.apiKey)) {
89
+ if (config.sourceLocale && config.targetLocales.length > 0 && config.apiBaseUrl) return;
90
+ const settings = await client.fetchSettings();
91
+ config.sourceLocale = settings.sourceLocale;
92
+ config.targetLocales = settings.targetLocales;
93
+ config.apiLocales = settings.apiLocales;
94
+ config.apiBaseUrl = settings.apiBaseUrl || require_api_client.DEFAULT_API_BASE_URL;
95
+ config.translationEngine = require_engine.resolveTranslationEngine(settings.translationEngine);
96
+ }
97
+
98
+ //#endregion
99
+ exports.createWeglotConfig = createWeglotConfig;
100
+ exports.resolveProjectLanguages = resolveProjectLanguages;