@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,237 @@
1
+ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
+ const require_use_i18n = require('./use-i18n.cjs');
3
+ const require_hash = require('../../utils/hash.cjs');
4
+ let _babel_types = require("@babel/types");
5
+ _babel_types = require_rolldown_runtime.__toESM(_babel_types);
6
+
7
+ //#region src/plugin/transform/utils.ts
8
+ const root = "@weglot/translate-react";
9
+ /**
10
+ * Normalize whitespace in translatable text.
11
+ * - Collapses multiple spaces/tabs/newlines into a single space
12
+ * - Preserves single spaces between words
13
+ * - Trims leading and trailing whitespace
14
+ *
15
+ * Example: "Hello\n world \n foo" → "Hello world foo"
16
+ */
17
+ function normalizeWhitespace(text) {
18
+ return text.replace(/\s+/g, " ").trim();
19
+ }
20
+ /**
21
+ * Escape literal angle brackets that are not part of ICU MessageFormat tags
22
+ */
23
+ function escapeTextForICU(text) {
24
+ return text.replace(/'/g, "''").replace(/\{/g, "'{'").replace(/}/g, "'}'").replace(/</g, "'<'").replace(/#/g, "'#'");
25
+ }
26
+ /**
27
+ * Detect if a function is a React component by checking if it returns JSX
28
+ */
29
+ function isReactComponent(path) {
30
+ if (path.isArrowFunctionExpression()) {
31
+ const body = path.node.body;
32
+ if (body.type === "JSXElement" || body.type === "JSXFragment") return true;
33
+ }
34
+ let returnsJSX = false;
35
+ path.traverse({ ReturnStatement(returnPath) {
36
+ const argument = returnPath.node.argument;
37
+ if (argument && (argument.type === "JSXElement" || argument.type === "JSXFragment")) returnsJSX = true;
38
+ } });
39
+ return returnsJSX;
40
+ }
41
+ /** Only a capitalised name can be rendered as an element, so only it may hold hooks. */
42
+ function isComponentName(name) {
43
+ return /^[A-Z]/.test(name);
44
+ }
45
+ /** A nested component runs its own pass; a lowercase `renderRow` helper belongs
46
+ * to the component declaring it. */
47
+ function isNestedComponent(path) {
48
+ if (!isReactComponent(path)) return false;
49
+ const name = inferComponentName(path);
50
+ return name !== null && isComponentName(name);
51
+ }
52
+ /**
53
+ * Infer component name from various patterns
54
+ */
55
+ function inferComponentName(path) {
56
+ if (path.node.id && path.node.id.name) return path.node.id.name;
57
+ const parent = path.parent;
58
+ if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") return parent.id.name;
59
+ if (parent.type === "ExportDefaultDeclaration") return "default";
60
+ return null;
61
+ }
62
+ /**
63
+ * Check for 'use i18n' directive at program level
64
+ */
65
+ function hasUseI18nDirective(program) {
66
+ return (program.node.directives || []).some((directive) => directive.value.value === require_use_i18n.useI18n);
67
+ }
68
+ function createTranslationEntry(type, text, context, filePath, line, column) {
69
+ const fullContext = {
70
+ ...context,
71
+ filePath
72
+ };
73
+ return {
74
+ type,
75
+ sourceText: text,
76
+ context: fullContext,
77
+ hash: require_hash.generateTranslationHash(text, fullContext),
78
+ location: {
79
+ filePath,
80
+ line,
81
+ column
82
+ }
83
+ };
84
+ }
85
+ /**
86
+ * Create {t(hash, fallback, { var1, var2, tag0: (chunks) => <Tag>{chunks}</Tag> })} call expression
87
+ */
88
+ function constructTranslationCall(hash, fallbackText, args, translator = DEFAULT_TRANSLATOR) {
89
+ const callArguments = [_babel_types.stringLiteral(hash), _babel_types.stringLiteral(fallbackText)];
90
+ if (args) {
91
+ const properties = [];
92
+ for (const varName of args.variables) properties.push(_babel_types.objectProperty(_babel_types.identifier(varName), _babel_types.identifier(varName), false, true));
93
+ for (const [name, expr] of args.expressions) properties.push(_babel_types.objectProperty(_babel_types.identifier(name), expr, false, false));
94
+ for (const [tagName, element] of args.components) {
95
+ const renderFn = element.extra?.shouldTranslate === false ? _babel_types.arrowFunctionExpression([], element) : _babel_types.arrowFunctionExpression([_babel_types.identifier("chunks")], _babel_types.jsxElement(_babel_types.jsxOpeningElement(element.openingElement.name, element.openingElement.attributes, false), _babel_types.jsxClosingElement(element.closingElement?.name || element.openingElement.name), [_babel_types.jsxExpressionContainer(_babel_types.identifier("chunks"))], false));
96
+ properties.push(_babel_types.objectProperty(_babel_types.identifier(tagName), renderFn, false, false));
97
+ }
98
+ if (properties.length > 0) callArguments.push(_babel_types.objectExpression(properties));
99
+ }
100
+ return _babel_types.jsxExpressionContainer(_babel_types.callExpression(_babel_types.identifier(translator), callArguments));
101
+ }
102
+ /** The same `t(hash, text)` call, for a position that is already an expression. */
103
+ function buildTranslationCall(hash, fallbackText, translator = DEFAULT_TRANSLATOR, params) {
104
+ const callArguments = [_babel_types.stringLiteral(hash), _babel_types.stringLiteral(fallbackText)];
105
+ if (params) {
106
+ const properties = [...params.variables.map((name) => _babel_types.objectProperty(_babel_types.identifier(name), _babel_types.identifier(name), false, true)), ...[...params.expressions].map(([name, expression]) => _babel_types.objectProperty(_babel_types.identifier(name), expression, false, false))];
107
+ if (properties.length > 0) callArguments.push(_babel_types.objectExpression(properties));
108
+ }
109
+ return _babel_types.callExpression(_babel_types.identifier(translator), callArguments);
110
+ }
111
+ /** Named `t` unless the component already binds it, e.g. from another i18n library. */
112
+ const DEFAULT_TRANSLATOR = "t";
113
+ function translatorNameFor(componentPath) {
114
+ const scope = componentPath.scope;
115
+ return scope.hasBinding(DEFAULT_TRANSLATOR) || scope.hasGlobal(DEFAULT_TRANSLATOR) || scope.hasReference(DEFAULT_TRANSLATOR) ? scope.generateUid(DEFAULT_TRANSLATOR) : DEFAULT_TRANSLATOR;
116
+ }
117
+ /**
118
+ * Check if a JSX element is self-closing or empty
119
+ */
120
+ function isVoidElement(element) {
121
+ return element.openingElement.selfClosing || element.children.length === 0;
122
+ }
123
+ /**
124
+ * Create unified import: import { useTranslation } from "@weglot/translate-react/react"
125
+ *
126
+ * Via conditional exports, this resolves to:
127
+ * - server.ts in Server Components (React cache + use)
128
+ * - index.ts in Client Components (Context)
129
+ */
130
+ function comstructUnifiedImport() {
131
+ return _babel_types.importDeclaration([_babel_types.importSpecifier(_babel_types.identifier("useTranslation"), _babel_types.identifier("useTranslation"))], _babel_types.stringLiteral(`${root}/react`));
132
+ }
133
+ /**
134
+ * Create import for server components: import { getServerTranslations } from "..."
135
+ */
136
+ function constructServerImport() {
137
+ return _babel_types.importDeclaration([_babel_types.importSpecifier(_babel_types.identifier("getServerTranslations"), _babel_types.identifier("getServerTranslations"))], _babel_types.stringLiteral(`${root}/react/server`));
138
+ }
139
+ /**
140
+ * Constructs a server translation hook call using provided configuration, server port, and hashes.
141
+ * const { t } = await getServerTranslations({ ... })
142
+ *
143
+ * @param {Object} options - The input parameters.
144
+ * @param {string[]} options.hashes - An array of hash strings related to translations.
145
+ * @return {VariableDeclaration} - Returns an object containing the constructed translation hook code to be used on the server.
146
+ */
147
+ function constructServerTranslationHookCall({ hashes, needsLocale = false, translator = DEFAULT_TRANSLATOR }) {
148
+ const optionsProperties = [];
149
+ const hashArray = _babel_types.arrayExpression(hashes.map((hash) => _babel_types.stringLiteral(hash)));
150
+ optionsProperties.push(_babel_types.objectProperty(_babel_types.identifier("hashes"), hashArray));
151
+ const destructureProperties = [_babel_types.objectProperty(_babel_types.identifier(DEFAULT_TRANSLATOR), _babel_types.identifier(translator), false, translator === DEFAULT_TRANSLATOR)];
152
+ if (needsLocale) destructureProperties.push(_babel_types.objectProperty(_babel_types.identifier("locale"), _babel_types.identifier("locale"), false, true));
153
+ return _babel_types.variableDeclaration("const", [_babel_types.variableDeclarator(_babel_types.objectPattern(destructureProperties), _babel_types.awaitExpression(_babel_types.callExpression(_babel_types.identifier("getServerTranslations"), [_babel_types.objectExpression(optionsProperties)])))]);
154
+ }
155
+ /**
156
+ * Inject unified `const t = useTranslation([...hashes])` at component start
157
+ *
158
+ * This hook works in BOTH Server and Client Components via conditional exports:
159
+ * - In Server Components: loads server.ts (uses React cache() + use())
160
+ * - In Client Components: loads index.ts (uses Context)
161
+ *
162
+ * This is the new default for non-async components!
163
+ *
164
+ * @param componentPath
165
+ * @param hashes
166
+ * @param needsLocale If true, destructures locale from hook: const { t, locale } = ...
167
+ */
168
+ function injectUnifiedHook(componentPath, hashes, needsLocale = false, translator = DEFAULT_TRANSLATOR) {
169
+ const body = componentPath.get("body");
170
+ let blockBody;
171
+ if (!body.isBlockStatement()) {
172
+ if (componentPath.isArrowFunctionExpression() && body.isExpression()) {
173
+ const returnStatement = _babel_types.returnStatement(body.node);
174
+ componentPath.node.body = _babel_types.blockStatement([returnStatement]);
175
+ blockBody = componentPath.get("body");
176
+ }
177
+ } else blockBody = body;
178
+ if (!blockBody) return;
179
+ const hashArray = _babel_types.arrayExpression(hashes.map((hash) => _babel_types.stringLiteral(hash)));
180
+ const pattern = _babel_types.objectPattern([_babel_types.objectProperty(_babel_types.identifier(DEFAULT_TRANSLATOR), _babel_types.identifier(translator), false, translator === DEFAULT_TRANSLATOR)]);
181
+ if (needsLocale) pattern.properties.push(_babel_types.objectProperty(_babel_types.identifier("locale"), _babel_types.identifier("locale"), false, true));
182
+ const hookCall = _babel_types.variableDeclaration("const", [_babel_types.variableDeclarator(pattern, _babel_types.callExpression(_babel_types.identifier("useTranslation"), [hashArray]))]);
183
+ blockBody.node.body.unshift(hookCall);
184
+ }
185
+ /**
186
+ * Inject `const { t } = await getServerTranslations([...hashes])` at component start (Server Components)
187
+ * Makes the component async if needed
188
+ *
189
+ * @param componentPath
190
+ * @param hashes
191
+ * @param needsLocale If true, destructures locale from hook: const { t, locale } = ...
192
+ */
193
+ function injectServerHook(componentPath, hashes, needsLocale = false, translator = DEFAULT_TRANSLATOR) {
194
+ const body = componentPath.get("body");
195
+ if (!body.isBlockStatement()) {
196
+ if (componentPath.isArrowFunctionExpression() && body.isExpression()) {
197
+ const returnStatement = _babel_types.returnStatement(body.node);
198
+ componentPath.node.body = _babel_types.blockStatement([returnStatement]);
199
+ componentPath.node.async = true;
200
+ const newBody = componentPath.get("body");
201
+ const serverCall$1 = constructServerTranslationHookCall({
202
+ hashes,
203
+ needsLocale,
204
+ translator
205
+ });
206
+ newBody.node.body.unshift(serverCall$1);
207
+ }
208
+ return;
209
+ }
210
+ if (!componentPath.node.async) componentPath.node.async = true;
211
+ const serverCall = constructServerTranslationHookCall({
212
+ hashes,
213
+ needsLocale,
214
+ translator
215
+ });
216
+ body.node.body.unshift(serverCall);
217
+ }
218
+
219
+ //#endregion
220
+ exports.DEFAULT_TRANSLATOR = DEFAULT_TRANSLATOR;
221
+ exports.buildTranslationCall = buildTranslationCall;
222
+ exports.comstructUnifiedImport = comstructUnifiedImport;
223
+ exports.constructServerImport = constructServerImport;
224
+ exports.constructServerTranslationHookCall = constructServerTranslationHookCall;
225
+ exports.constructTranslationCall = constructTranslationCall;
226
+ exports.createTranslationEntry = createTranslationEntry;
227
+ exports.escapeTextForICU = escapeTextForICU;
228
+ exports.hasUseI18nDirective = hasUseI18nDirective;
229
+ exports.inferComponentName = inferComponentName;
230
+ exports.injectServerHook = injectServerHook;
231
+ exports.injectUnifiedHook = injectUnifiedHook;
232
+ exports.isComponentName = isComponentName;
233
+ exports.isNestedComponent = isNestedComponent;
234
+ exports.isReactComponent = isReactComponent;
235
+ exports.isVoidElement = isVoidElement;
236
+ exports.normalizeWhitespace = normalizeWhitespace;
237
+ exports.translatorNameFor = translatorNameFor;
@@ -0,0 +1,219 @@
1
+ import { useI18n } from "./use-i18n.mjs";
2
+ import { generateTranslationHash } from "../../utils/hash.mjs";
3
+ import * as t from "@babel/types";
4
+
5
+ //#region src/plugin/transform/utils.ts
6
+ const root = "@weglot/translate-react";
7
+ /**
8
+ * Normalize whitespace in translatable text.
9
+ * - Collapses multiple spaces/tabs/newlines into a single space
10
+ * - Preserves single spaces between words
11
+ * - Trims leading and trailing whitespace
12
+ *
13
+ * Example: "Hello\n world \n foo" → "Hello world foo"
14
+ */
15
+ function normalizeWhitespace(text) {
16
+ return text.replace(/\s+/g, " ").trim();
17
+ }
18
+ /**
19
+ * Escape literal angle brackets that are not part of ICU MessageFormat tags
20
+ */
21
+ function escapeTextForICU(text) {
22
+ return text.replace(/'/g, "''").replace(/\{/g, "'{'").replace(/}/g, "'}'").replace(/</g, "'<'").replace(/#/g, "'#'");
23
+ }
24
+ /**
25
+ * Detect if a function is a React component by checking if it returns JSX
26
+ */
27
+ function isReactComponent(path) {
28
+ if (path.isArrowFunctionExpression()) {
29
+ const body = path.node.body;
30
+ if (body.type === "JSXElement" || body.type === "JSXFragment") return true;
31
+ }
32
+ let returnsJSX = false;
33
+ path.traverse({ ReturnStatement(returnPath) {
34
+ const argument = returnPath.node.argument;
35
+ if (argument && (argument.type === "JSXElement" || argument.type === "JSXFragment")) returnsJSX = true;
36
+ } });
37
+ return returnsJSX;
38
+ }
39
+ /** Only a capitalised name can be rendered as an element, so only it may hold hooks. */
40
+ function isComponentName(name) {
41
+ return /^[A-Z]/.test(name);
42
+ }
43
+ /** A nested component runs its own pass; a lowercase `renderRow` helper belongs
44
+ * to the component declaring it. */
45
+ function isNestedComponent(path) {
46
+ if (!isReactComponent(path)) return false;
47
+ const name = inferComponentName(path);
48
+ return name !== null && isComponentName(name);
49
+ }
50
+ /**
51
+ * Infer component name from various patterns
52
+ */
53
+ function inferComponentName(path) {
54
+ if (path.node.id && path.node.id.name) return path.node.id.name;
55
+ const parent = path.parent;
56
+ if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") return parent.id.name;
57
+ if (parent.type === "ExportDefaultDeclaration") return "default";
58
+ return null;
59
+ }
60
+ /**
61
+ * Check for 'use i18n' directive at program level
62
+ */
63
+ function hasUseI18nDirective(program) {
64
+ return (program.node.directives || []).some((directive) => directive.value.value === useI18n);
65
+ }
66
+ function createTranslationEntry(type, text, context, filePath, line, column) {
67
+ const fullContext = {
68
+ ...context,
69
+ filePath
70
+ };
71
+ return {
72
+ type,
73
+ sourceText: text,
74
+ context: fullContext,
75
+ hash: generateTranslationHash(text, fullContext),
76
+ location: {
77
+ filePath,
78
+ line,
79
+ column
80
+ }
81
+ };
82
+ }
83
+ /**
84
+ * Create {t(hash, fallback, { var1, var2, tag0: (chunks) => <Tag>{chunks}</Tag> })} call expression
85
+ */
86
+ function constructTranslationCall(hash, fallbackText, args, translator = DEFAULT_TRANSLATOR) {
87
+ const callArguments = [t.stringLiteral(hash), t.stringLiteral(fallbackText)];
88
+ if (args) {
89
+ const properties = [];
90
+ for (const varName of args.variables) properties.push(t.objectProperty(t.identifier(varName), t.identifier(varName), false, true));
91
+ for (const [name, expr] of args.expressions) properties.push(t.objectProperty(t.identifier(name), expr, false, false));
92
+ for (const [tagName, element] of args.components) {
93
+ const renderFn = element.extra?.shouldTranslate === false ? t.arrowFunctionExpression([], element) : t.arrowFunctionExpression([t.identifier("chunks")], t.jsxElement(t.jsxOpeningElement(element.openingElement.name, element.openingElement.attributes, false), t.jsxClosingElement(element.closingElement?.name || element.openingElement.name), [t.jsxExpressionContainer(t.identifier("chunks"))], false));
94
+ properties.push(t.objectProperty(t.identifier(tagName), renderFn, false, false));
95
+ }
96
+ if (properties.length > 0) callArguments.push(t.objectExpression(properties));
97
+ }
98
+ return t.jsxExpressionContainer(t.callExpression(t.identifier(translator), callArguments));
99
+ }
100
+ /** The same `t(hash, text)` call, for a position that is already an expression. */
101
+ function buildTranslationCall(hash, fallbackText, translator = DEFAULT_TRANSLATOR, params) {
102
+ const callArguments = [t.stringLiteral(hash), t.stringLiteral(fallbackText)];
103
+ if (params) {
104
+ const properties = [...params.variables.map((name) => t.objectProperty(t.identifier(name), t.identifier(name), false, true)), ...[...params.expressions].map(([name, expression]) => t.objectProperty(t.identifier(name), expression, false, false))];
105
+ if (properties.length > 0) callArguments.push(t.objectExpression(properties));
106
+ }
107
+ return t.callExpression(t.identifier(translator), callArguments);
108
+ }
109
+ /** Named `t` unless the component already binds it, e.g. from another i18n library. */
110
+ const DEFAULT_TRANSLATOR = "t";
111
+ function translatorNameFor(componentPath) {
112
+ const scope = componentPath.scope;
113
+ return scope.hasBinding(DEFAULT_TRANSLATOR) || scope.hasGlobal(DEFAULT_TRANSLATOR) || scope.hasReference(DEFAULT_TRANSLATOR) ? scope.generateUid(DEFAULT_TRANSLATOR) : DEFAULT_TRANSLATOR;
114
+ }
115
+ /**
116
+ * Check if a JSX element is self-closing or empty
117
+ */
118
+ function isVoidElement(element) {
119
+ return element.openingElement.selfClosing || element.children.length === 0;
120
+ }
121
+ /**
122
+ * Create unified import: import { useTranslation } from "@weglot/translate-react/react"
123
+ *
124
+ * Via conditional exports, this resolves to:
125
+ * - server.ts in Server Components (React cache + use)
126
+ * - index.ts in Client Components (Context)
127
+ */
128
+ function comstructUnifiedImport() {
129
+ return t.importDeclaration([t.importSpecifier(t.identifier("useTranslation"), t.identifier("useTranslation"))], t.stringLiteral(`${root}/react`));
130
+ }
131
+ /**
132
+ * Create import for server components: import { getServerTranslations } from "..."
133
+ */
134
+ function constructServerImport() {
135
+ return t.importDeclaration([t.importSpecifier(t.identifier("getServerTranslations"), t.identifier("getServerTranslations"))], t.stringLiteral(`${root}/react/server`));
136
+ }
137
+ /**
138
+ * Constructs a server translation hook call using provided configuration, server port, and hashes.
139
+ * const { t } = await getServerTranslations({ ... })
140
+ *
141
+ * @param {Object} options - The input parameters.
142
+ * @param {string[]} options.hashes - An array of hash strings related to translations.
143
+ * @return {VariableDeclaration} - Returns an object containing the constructed translation hook code to be used on the server.
144
+ */
145
+ function constructServerTranslationHookCall({ hashes, needsLocale = false, translator = DEFAULT_TRANSLATOR }) {
146
+ const optionsProperties = [];
147
+ const hashArray = t.arrayExpression(hashes.map((hash) => t.stringLiteral(hash)));
148
+ optionsProperties.push(t.objectProperty(t.identifier("hashes"), hashArray));
149
+ const destructureProperties = [t.objectProperty(t.identifier(DEFAULT_TRANSLATOR), t.identifier(translator), false, translator === DEFAULT_TRANSLATOR)];
150
+ if (needsLocale) destructureProperties.push(t.objectProperty(t.identifier("locale"), t.identifier("locale"), false, true));
151
+ return t.variableDeclaration("const", [t.variableDeclarator(t.objectPattern(destructureProperties), t.awaitExpression(t.callExpression(t.identifier("getServerTranslations"), [t.objectExpression(optionsProperties)])))]);
152
+ }
153
+ /**
154
+ * Inject unified `const t = useTranslation([...hashes])` at component start
155
+ *
156
+ * This hook works in BOTH Server and Client Components via conditional exports:
157
+ * - In Server Components: loads server.ts (uses React cache() + use())
158
+ * - In Client Components: loads index.ts (uses Context)
159
+ *
160
+ * This is the new default for non-async components!
161
+ *
162
+ * @param componentPath
163
+ * @param hashes
164
+ * @param needsLocale If true, destructures locale from hook: const { t, locale } = ...
165
+ */
166
+ function injectUnifiedHook(componentPath, hashes, needsLocale = false, translator = DEFAULT_TRANSLATOR) {
167
+ const body = componentPath.get("body");
168
+ let blockBody;
169
+ if (!body.isBlockStatement()) {
170
+ if (componentPath.isArrowFunctionExpression() && body.isExpression()) {
171
+ const returnStatement = t.returnStatement(body.node);
172
+ componentPath.node.body = t.blockStatement([returnStatement]);
173
+ blockBody = componentPath.get("body");
174
+ }
175
+ } else blockBody = body;
176
+ if (!blockBody) return;
177
+ const hashArray = t.arrayExpression(hashes.map((hash) => t.stringLiteral(hash)));
178
+ const pattern = t.objectPattern([t.objectProperty(t.identifier(DEFAULT_TRANSLATOR), t.identifier(translator), false, translator === DEFAULT_TRANSLATOR)]);
179
+ if (needsLocale) pattern.properties.push(t.objectProperty(t.identifier("locale"), t.identifier("locale"), false, true));
180
+ const hookCall = t.variableDeclaration("const", [t.variableDeclarator(pattern, t.callExpression(t.identifier("useTranslation"), [hashArray]))]);
181
+ blockBody.node.body.unshift(hookCall);
182
+ }
183
+ /**
184
+ * Inject `const { t } = await getServerTranslations([...hashes])` at component start (Server Components)
185
+ * Makes the component async if needed
186
+ *
187
+ * @param componentPath
188
+ * @param hashes
189
+ * @param needsLocale If true, destructures locale from hook: const { t, locale } = ...
190
+ */
191
+ function injectServerHook(componentPath, hashes, needsLocale = false, translator = DEFAULT_TRANSLATOR) {
192
+ const body = componentPath.get("body");
193
+ if (!body.isBlockStatement()) {
194
+ if (componentPath.isArrowFunctionExpression() && body.isExpression()) {
195
+ const returnStatement = t.returnStatement(body.node);
196
+ componentPath.node.body = t.blockStatement([returnStatement]);
197
+ componentPath.node.async = true;
198
+ const newBody = componentPath.get("body");
199
+ const serverCall$1 = constructServerTranslationHookCall({
200
+ hashes,
201
+ needsLocale,
202
+ translator
203
+ });
204
+ newBody.node.body.unshift(serverCall$1);
205
+ }
206
+ return;
207
+ }
208
+ if (!componentPath.node.async) componentPath.node.async = true;
209
+ const serverCall = constructServerTranslationHookCall({
210
+ hashes,
211
+ needsLocale,
212
+ translator
213
+ });
214
+ body.node.body.unshift(serverCall);
215
+ }
216
+
217
+ //#endregion
218
+ export { DEFAULT_TRANSLATOR, buildTranslationCall, comstructUnifiedImport, constructServerImport, constructServerTranslationHookCall, constructTranslationCall, createTranslationEntry, escapeTextForICU, hasUseI18nDirective, inferComponentName, injectServerHook, injectUnifiedHook, isComponentName, isNestedComponent, isReactComponent, isVoidElement, normalizeWhitespace, translatorNameFor };
219
+ //# sourceMappingURL=utils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.mjs","names":["callArguments: t.Expression[]","properties: t.ObjectProperty[]","blockBody: NodePath<t.BlockStatement> | undefined","serverCall"],"sources":["../../../src/plugin/transform/utils.ts"],"sourcesContent":["import type { TranslationEntry } from \"../../types\";\nimport type { NodePath } from \"@babel/traverse\";\nimport type { VariableDeclaration } from \"@babel/types\";\nimport * as t from \"@babel/types\";\nimport { generateTranslationHash } from \"../../utils/hash\";\nimport { useI18n } from \"./use-i18n\";\n\ntype TranslationEntryByType = {\n [T in TranslationEntry as T[\"type\"]]: T;\n};\n\nconst root = \"@weglot/translate-react\";\n// TODO (AleksandrSl 28/11/2025): See jsx-content.ts in the old compiler for future improvements.\n\n/**\n * Normalize whitespace in translatable text.\n * - Collapses multiple spaces/tabs/newlines into a single space\n * - Preserves single spaces between words\n * - Trims leading and trailing whitespace\n *\n * Example: \"Hello\\n world \\n foo\" → \"Hello world foo\"\n */\nexport function normalizeWhitespace(text: string): string {\n return text\n .replace(/\\s+/g, \" \") // Collapse all whitespace sequences to single space\n .trim(); // Remove leading/trailing whitespace\n}\n\n/**\n * Escape literal angle brackets that are not part of ICU MessageFormat tags\n */\nexport function escapeTextForICU(text: string): string {\n // Related spec - https://unicode-org.github.io/icu/userguide/format_parse/messages/#quotingescaping\n return text\n .replace(/'/g, \"''\")\n .replace(/\\{/g, \"'{'\")\n .replace(/}/g, \"'}'\")\n .replace(/</g, \"'<'\")\n .replace(/#/g, \"'#'\");\n}\n\n/**\n * Detect if a function is a React component by checking if it returns JSX\n */\nexport function isReactComponent(\n path: NodePath<\n t.FunctionDeclaration | t.FunctionExpression | t.ArrowFunctionExpression\n >,\n): boolean {\n // Check for arrow function with JSX expression body: () => <div>...</div>\n if (path.isArrowFunctionExpression()) {\n const body = path.node.body;\n if (body.type === \"JSXElement\" || body.type === \"JSXFragment\") {\n return true;\n }\n }\n\n // Babel traverses with DFS so we get the innermost function return first if any.\n // But if at least one function returns JSX I guess we should transform the whole function.\n // It's a weird corner case.\n\n // Check for explicit return statements with JSX\n // We could also check for the first JSX?\n let returnsJSX = false;\n path.traverse({\n ReturnStatement(returnPath) {\n const argument = returnPath.node.argument;\n if (\n argument &&\n (argument.type === \"JSXElement\" || argument.type === \"JSXFragment\")\n ) {\n returnsJSX = true;\n }\n },\n });\n\n // ts doesn't see what happens inside path.traverse, and erroneously narrows returnsJsx to false\n return returnsJSX as boolean;\n}\n\n/** Only a capitalised name can be rendered as an element, so only it may hold hooks. */\nexport function isComponentName(name: string): boolean {\n return /^[A-Z]/.test(name);\n}\n\n/** A nested component runs its own pass; a lowercase `renderRow` helper belongs\n * to the component declaring it. */\nexport function isNestedComponent(\n path: NodePath<\n t.FunctionDeclaration | t.FunctionExpression | t.ArrowFunctionExpression\n >,\n): boolean {\n if (!isReactComponent(path)) return false;\n const name = inferComponentName(path);\n return name !== null && isComponentName(name);\n}\n\n/**\n * Infer component name from various patterns\n */\nexport function inferComponentName(path: NodePath<any>): string | null {\n // Named function: function MyComponent() {}\n if (path.node.id && path.node.id.name) {\n return path.node.id.name;\n }\n\n // Variable declaration: const MyComponent = () => {}\n const parent = path.parent;\n if (parent.type === \"VariableDeclarator\" && parent.id.type === \"Identifier\") {\n return parent.id.name;\n }\n\n // TODO (AleksandrSl 25/11/2025): It should support export const $NAME$\n // Export: export default function() {}\n if (parent.type === \"ExportDefaultDeclaration\") {\n return \"default\";\n }\n\n return null;\n}\n\n/**\n * Check for 'use i18n' directive at program level\n */\nexport function hasUseI18nDirective(program: NodePath<t.Program>): boolean {\n const directives = program.node.directives || [];\n return directives.some(\n (directive: t.Directive) => directive.value.value === useI18n,\n );\n}\n\nexport function createTranslationEntry<T extends keyof TranslationEntryByType>(\n type: T,\n text: string,\n context: Omit<TranslationEntryByType[T][\"context\"], \"filePath\">,\n filePath: string,\n line?: number,\n column?: number,\n): TranslationEntryByType[T] {\n const fullContext = { ...context, filePath };\n const hash = generateTranslationHash(text, fullContext);\n\n return {\n type,\n sourceText: text,\n context: fullContext,\n hash,\n location: {\n filePath,\n line,\n column,\n },\n // Seems like the only approach without the cast is function overloads, which are noisy. The type cast is not that bad since it's inside the function.\n } as TranslationEntryByType[T];\n}\n\n/**\n * Create {t(hash, fallback, { var1, var2, tag0: (chunks) => <Tag>{chunks}</Tag> })} call expression\n */\nexport function constructTranslationCall(\n hash: string,\n fallbackText: string,\n args?: {\n variables: string[];\n expressions: Map<string, t.Expression>;\n components: Map<string, t.JSXElement>;\n },\n translator: string = DEFAULT_TRANSLATOR,\n): t.JSXExpressionContainer {\n const callArguments: t.Expression[] = [\n t.stringLiteral(hash),\n t.stringLiteral(fallbackText),\n ];\n\n if (args) {\n const properties: t.ObjectProperty[] = [];\n\n // Add variable properties (shorthand)\n for (const varName of args.variables) {\n properties.push(\n t.objectProperty(\n t.identifier(varName),\n t.identifier(varName),\n false,\n true, // shorthand\n ),\n );\n }\n\n for (const [name, expr] of args.expressions) {\n properties.push(t.objectProperty(t.identifier(name), expr, false, false));\n }\n\n // Add component renderer functions\n for (const [tagName, element] of args.components) {\n const renderFn =\n element.extra?.shouldTranslate === false\n ? // Even when doing: tagName: () => <Element />, we need a function for formatjs to work.\n t.arrowFunctionExpression([], element)\n : // Create: tagName: (chunks) => <Element>{chunks}</Element>\n t.arrowFunctionExpression(\n [t.identifier(\"chunks\")],\n t.jsxElement(\n t.jsxOpeningElement(\n element.openingElement.name,\n element.openingElement.attributes,\n false,\n ),\n t.jsxClosingElement(\n element.closingElement?.name || element.openingElement.name,\n ),\n [t.jsxExpressionContainer(t.identifier(\"chunks\"))],\n false,\n ),\n );\n\n properties.push(\n t.objectProperty(t.identifier(tagName), renderFn, false, false),\n );\n }\n\n if (properties.length > 0) {\n callArguments.push(t.objectExpression(properties));\n }\n }\n\n return t.jsxExpressionContainer(\n t.callExpression(t.identifier(translator), callArguments),\n );\n}\n\n/** The same `t(hash, text)` call, for a position that is already an expression. */\nexport function buildTranslationCall(\n hash: string,\n fallbackText: string,\n translator: string = DEFAULT_TRANSLATOR,\n params?: {\n variables: string[];\n expressions: Map<string, t.Expression>;\n },\n): t.CallExpression {\n const callArguments: t.Expression[] = [\n t.stringLiteral(hash),\n t.stringLiteral(fallbackText),\n ];\n\n if (params) {\n const properties: t.ObjectProperty[] = [\n ...params.variables.map((name) =>\n t.objectProperty(t.identifier(name), t.identifier(name), false, true),\n ),\n ...[...params.expressions].map(([name, expression]) =>\n t.objectProperty(t.identifier(name), expression, false, false),\n ),\n ];\n\n if (properties.length > 0) {\n callArguments.push(t.objectExpression(properties));\n }\n }\n\n return t.callExpression(t.identifier(translator), callArguments);\n}\n\n/** Named `t` unless the component already binds it, e.g. from another i18n library. */\nexport const DEFAULT_TRANSLATOR = \"t\";\n\nexport function translatorNameFor(\n componentPath: NodePath<\n t.FunctionDeclaration | t.FunctionExpression | t.ArrowFunctionExpression\n >,\n): string {\n const scope = componentPath.scope;\n return scope.hasBinding(DEFAULT_TRANSLATOR) ||\n scope.hasGlobal(DEFAULT_TRANSLATOR) ||\n scope.hasReference(DEFAULT_TRANSLATOR)\n ? scope.generateUid(DEFAULT_TRANSLATOR)\n : DEFAULT_TRANSLATOR;\n}\n\n/**\n * Check if a JSX element is self-closing or empty\n */\nexport function isVoidElement(element: t.JSXElement): boolean {\n return element.openingElement.selfClosing || element.children.length === 0;\n}\n\n/**\n * Create unified import: import { useTranslation } from \"@weglot/translate-react/react\"\n *\n * Via conditional exports, this resolves to:\n * - server.ts in Server Components (React cache + use)\n * - index.ts in Client Components (Context)\n */\nexport function comstructUnifiedImport(): t.ImportDeclaration {\n return t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier(\"useTranslation\"),\n t.identifier(\"useTranslation\"),\n ),\n ],\n t.stringLiteral(`${root}/react`),\n );\n}\n\n/**\n * Create import for server components: import { getServerTranslations } from \"...\"\n */\nexport function constructServerImport(): t.ImportDeclaration {\n return t.importDeclaration(\n [\n t.importSpecifier(\n t.identifier(\"getServerTranslations\"),\n t.identifier(\"getServerTranslations\"),\n ),\n ],\n t.stringLiteral(`${root}/react/server`),\n );\n}\n\n/**\n * Constructs a server translation hook call using provided configuration, server port, and hashes.\n * const { t } = await getServerTranslations({ ... })\n *\n * @param {Object} options - The input parameters.\n * @param {string[]} options.hashes - An array of hash strings related to translations.\n * @return {VariableDeclaration} - Returns an object containing the constructed translation hook code to be used on the server.\n */\nexport function constructServerTranslationHookCall({\n hashes,\n needsLocale = false,\n translator = DEFAULT_TRANSLATOR,\n}: {\n hashes: string[];\n needsLocale?: boolean;\n translator?: string;\n}): VariableDeclaration {\n const optionsProperties = [];\n\n const hashArray = t.arrayExpression(\n hashes.map((hash) => t.stringLiteral(hash)),\n );\n optionsProperties.push(t.objectProperty(t.identifier(\"hashes\"), hashArray));\n\n const destructureProperties = [\n t.objectProperty(\n t.identifier(DEFAULT_TRANSLATOR),\n t.identifier(translator),\n false,\n translator === DEFAULT_TRANSLATOR, // shorthand\n ),\n ];\n\n if (needsLocale) {\n destructureProperties.push(\n t.objectProperty(\n t.identifier(\"locale\"),\n t.identifier(\"locale\"),\n false,\n true, // shorthand\n ),\n );\n }\n\n return t.variableDeclaration(\"const\", [\n t.variableDeclarator(\n t.objectPattern(destructureProperties),\n t.awaitExpression(\n t.callExpression(t.identifier(\"getServerTranslations\"), [\n t.objectExpression(optionsProperties),\n ]),\n ),\n ),\n ]);\n}\n\n/**\n * Inject unified `const t = useTranslation([...hashes])` at component start\n *\n * This hook works in BOTH Server and Client Components via conditional exports:\n * - In Server Components: loads server.ts (uses React cache() + use())\n * - In Client Components: loads index.ts (uses Context)\n *\n * This is the new default for non-async components!\n *\n * @param componentPath\n * @param hashes\n * @param needsLocale If true, destructures locale from hook: const { t, locale } = ...\n */\nexport function injectUnifiedHook(\n componentPath: NodePath<\n t.FunctionDeclaration | t.FunctionExpression | t.ArrowFunctionExpression\n >,\n hashes: string[],\n needsLocale: boolean = false,\n translator: string = DEFAULT_TRANSLATOR,\n): void {\n const body = componentPath.get(\"body\");\n\n let blockBody: NodePath<t.BlockStatement> | undefined;\n // Handle arrow functions with expression bodies: () => <jsx>\n // Convert to block statement: () => { const t = ...; return <jsx>; }\n if (!body.isBlockStatement()) {\n if (componentPath.isArrowFunctionExpression() && body.isExpression()) {\n const returnStatement = t.returnStatement(body.node as t.Expression);\n componentPath.node.body = t.blockStatement([returnStatement]);\n // Re-get the body after conversion\n blockBody = componentPath.get(\"body\") as NodePath<t.BlockStatement>;\n }\n } else {\n blockBody = body;\n }\n\n if (!blockBody) {\n return;\n }\n\n const hashArray = t.arrayExpression(\n hashes.map((hash) => t.stringLiteral(hash)),\n );\n\n const pattern = t.objectPattern([\n t.objectProperty(\n t.identifier(DEFAULT_TRANSLATOR),\n t.identifier(translator),\n false,\n translator === DEFAULT_TRANSLATOR,\n ),\n ]);\n if (needsLocale) {\n pattern.properties.push(\n t.objectProperty(\n t.identifier(\"locale\"),\n t.identifier(\"locale\"),\n false,\n true,\n ),\n );\n }\n\n const hookCall = t.variableDeclaration(\"const\", [\n t.variableDeclarator(\n pattern,\n t.callExpression(t.identifier(\"useTranslation\"), [hashArray]),\n ),\n ]);\n\n blockBody.node.body.unshift(hookCall);\n}\n\n/**\n * Inject `const { t } = await getServerTranslations([...hashes])` at component start (Server Components)\n * Makes the component async if needed\n *\n * @param componentPath\n * @param hashes\n * @param needsLocale If true, destructures locale from hook: const { t, locale } = ...\n */\nexport function injectServerHook(\n componentPath: NodePath<\n t.FunctionDeclaration | t.FunctionExpression | t.ArrowFunctionExpression\n >,\n hashes: string[],\n needsLocale: boolean = false,\n translator: string = DEFAULT_TRANSLATOR,\n): void {\n const body = componentPath.get(\"body\");\n\n // Handle arrow functions with expression bodies: () => <jsx>\n // Convert to block statement: async () => { const { t } = await ...; return <jsx>; }\n if (!body.isBlockStatement()) {\n if (componentPath.isArrowFunctionExpression() && body.isExpression()) {\n const returnStatement = t.returnStatement(body.node as t.Expression);\n componentPath.node.body = t.blockStatement([returnStatement]);\n componentPath.node.async = true;\n // Re-get the body after conversion\n const newBody = componentPath.get(\"body\") as NodePath<t.BlockStatement>;\n\n // Create: const { t } = await getServerTranslations({ ... })\n const serverCall = constructServerTranslationHookCall({\n hashes,\n needsLocale,\n translator,\n });\n\n newBody.node.body.unshift(serverCall);\n }\n return;\n }\n\n if (!componentPath.node.async) {\n componentPath.node.async = true;\n }\n\n // Create: const { t } = await getServerTranslations({ ... })\n const serverCall = constructServerTranslationHookCall({\n hashes,\n needsLocale,\n translator,\n });\n\n body.node.body.unshift(serverCall);\n}\n"],"mappings":";;;;;AAWA,MAAM,OAAO;;;;;;;;;AAWb,SAAgB,oBAAoB,MAAsB;AACxD,QAAO,KACJ,QAAQ,QAAQ,IAAI,CACpB,MAAM;;;;;AAMX,SAAgB,iBAAiB,MAAsB;AAErD,QAAO,KACJ,QAAQ,MAAM,KAAK,CACnB,QAAQ,OAAO,MAAM,CACrB,QAAQ,MAAM,MAAM,CACpB,QAAQ,MAAM,MAAM,CACpB,QAAQ,MAAM,MAAM;;;;;AAMzB,SAAgB,iBACd,MAGS;AAET,KAAI,KAAK,2BAA2B,EAAE;EACpC,MAAM,OAAO,KAAK,KAAK;AACvB,MAAI,KAAK,SAAS,gBAAgB,KAAK,SAAS,cAC9C,QAAO;;CAUX,IAAI,aAAa;AACjB,MAAK,SAAS,EACZ,gBAAgB,YAAY;EAC1B,MAAM,WAAW,WAAW,KAAK;AACjC,MACE,aACC,SAAS,SAAS,gBAAgB,SAAS,SAAS,eAErD,cAAa;IAGlB,CAAC;AAGF,QAAO;;;AAIT,SAAgB,gBAAgB,MAAuB;AACrD,QAAO,SAAS,KAAK,KAAK;;;;AAK5B,SAAgB,kBACd,MAGS;AACT,KAAI,CAAC,iBAAiB,KAAK,CAAE,QAAO;CACpC,MAAM,OAAO,mBAAmB,KAAK;AACrC,QAAO,SAAS,QAAQ,gBAAgB,KAAK;;;;;AAM/C,SAAgB,mBAAmB,MAAoC;AAErE,KAAI,KAAK,KAAK,MAAM,KAAK,KAAK,GAAG,KAC/B,QAAO,KAAK,KAAK,GAAG;CAItB,MAA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