@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,229 @@
1
+ import { __require } from "../_virtual/rolldown_runtime.mjs";
2
+ import { logger } from "../utils/logger.mjs";
3
+ import { createWeglotConfig, resolveProjectLanguages } from "../utils/config-factory.mjs";
4
+ import { TranslationService } from "../translators/translation-service.mjs";
5
+ import { cleanupMetadataForEnvironment, getMetadataPath } from "../metadata/manager.mjs";
6
+ import { startOrGetTranslationServer } from "../translation-server/translation-server.mjs";
7
+ import { processBuildTranslations } from "./build-translator.mjs";
8
+ import { registerCleanupOnCurrentProcess } from "./cleanup.mjs";
9
+ import { useI18nRegex } from "./transform/use-i18n.mjs";
10
+
11
+ //#region src/plugin/next.ts
12
+ function loaders({ weglotConfig, metadataFilePath, translationServerUrl }) {
13
+ const common = {
14
+ sourceRoot: weglotConfig.sourceRoot,
15
+ weglotDir: weglotConfig.weglotDir,
16
+ sourceLocale: weglotConfig.sourceLocale
17
+ };
18
+ const compilerLoader = {
19
+ loader: "@weglot/translate-react/next-compiler-loader",
20
+ options: {
21
+ ...common,
22
+ useDirective: weglotConfig.useDirective,
23
+ translatableAttributes: weglotConfig.translatableAttributes,
24
+ metadataFilePath
25
+ }
26
+ };
27
+ const configLoader = {
28
+ loader: "@weglot/translate-react/next-config-loader",
29
+ options: {
30
+ ...common,
31
+ apiLocales: weglotConfig.apiLocales,
32
+ translationEngine: weglotConfig.translationEngine,
33
+ apiBaseUrl: weglotConfig.apiBaseUrl,
34
+ dev: Object.fromEntries(Object.entries({
35
+ translationServerUrl,
36
+ ...weglotConfig.dev
37
+ }).filter(([, value]) => value !== void 0))
38
+ }
39
+ };
40
+ const localeServerLoader = {
41
+ loader: "@weglot/translate-react/next-locale-server-loader",
42
+ options: {
43
+ ...common,
44
+ localePersistence: weglotConfig.localePersistence
45
+ }
46
+ };
47
+ const localeClientLoader = {
48
+ loader: "@weglot/translate-react/next-locale-client-loader",
49
+ options: {
50
+ ...common,
51
+ localePersistence: weglotConfig.localePersistence
52
+ }
53
+ };
54
+ return {
55
+ compiler: {
56
+ turbopack: {
57
+ pattern: "*.{tsx,jsx}",
58
+ config: {
59
+ condition: { content: weglotConfig.useDirective ? useI18nRegex : void 0 },
60
+ loaders: [compilerLoader]
61
+ }
62
+ },
63
+ webpack: {
64
+ enforce: "pre",
65
+ test: /\.(tsx|jsx)$/i,
66
+ exclude: /node_modules/,
67
+ use: [compilerLoader]
68
+ }
69
+ },
70
+ config: {
71
+ turbopack: {
72
+ pattern: "**/virtual/config.mjs",
73
+ config: { loaders: [configLoader] }
74
+ },
75
+ webpack: {
76
+ enforce: "pre",
77
+ test: /virtual\/config\.mjs$/i,
78
+ use: [configLoader]
79
+ }
80
+ },
81
+ localeServer: {
82
+ turbopack: {
83
+ pattern: "**/virtual/locale/server.mjs",
84
+ config: { loaders: [localeServerLoader] }
85
+ },
86
+ webpack: {
87
+ enforce: "pre",
88
+ test: /virtual\/locale[\\/]server\.mjs$/i,
89
+ use: [localeServerLoader]
90
+ }
91
+ },
92
+ localeClient: {
93
+ turbopack: {
94
+ pattern: "**/virtual/locale/client.mjs",
95
+ config: { loaders: [localeClientLoader] }
96
+ },
97
+ webpack: {
98
+ enforce: "pre",
99
+ test: /virtual\/locale[\\/]client\.mjs$/i,
100
+ use: [localeClientLoader]
101
+ }
102
+ }
103
+ };
104
+ }
105
+ /**
106
+ * Check if Next.js supports stable turbopack config (Next.js 16+)
107
+ */
108
+ function hasStableTurboConfig() {
109
+ try {
110
+ const nextPackage = __require("next/package.json");
111
+ return parseInt(nextPackage.version.split(".")[0], 10) >= 16;
112
+ } catch {
113
+ return false;
114
+ }
115
+ }
116
+ function getTurbopackConfig(userConfig) {
117
+ return (hasStableTurboConfig() ? userConfig?.turbopack : userConfig?.experimental?.turbo) || {};
118
+ }
119
+ /**
120
+ * Merge Turbopack rules without mutating original
121
+ */
122
+ function mergeTurbopackRules(existingRules, newRules) {
123
+ const mergedRules = { ...existingRules };
124
+ for (const newRule of newRules) {
125
+ if (!newRule) continue;
126
+ const { pattern, config } = newRule;
127
+ if (mergedRules[pattern]) if (Array.isArray(mergedRules[pattern])) mergedRules[pattern] = [...mergedRules[pattern], config];
128
+ else mergedRules[pattern] = [mergedRules[pattern], config];
129
+ else mergedRules[pattern] = config;
130
+ }
131
+ return mergedRules;
132
+ }
133
+ function isMainRunner() {
134
+ return !process.env.NEXT_PRIVATE_BUILD_WORKER && !process.env.IS_NEXT_WORKER && !process.env.NEXT_PRIVATE_WORKER;
135
+ }
136
+ async function withWeglot(nextConfig = {}, weglotOptions) {
137
+ const weglotConfig = createWeglotConfig(weglotOptions);
138
+ await resolveProjectLanguages(weglotConfig);
139
+ let metadataFilePath = getMetadataPath(weglotConfig);
140
+ const isDev = weglotConfig.environment === "development";
141
+ logger.debug(`Initializing Weglot. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`);
142
+ if (isDev && !process.env.WEGLOT_TRANSLATION_SERVER_URL) if (weglotConfig.dev.translationServerUrl) {
143
+ logger.info(`Using existing translation server URL (${weglotConfig.dev.translationServerUrl}) from config`);
144
+ process.env.WEGLOT_TRANSLATION_SERVER_URL = weglotConfig.dev.translationServerUrl;
145
+ } else {
146
+ const translationServer = await startOrGetTranslationServer({
147
+ translationService: new TranslationService(weglotConfig, logger),
148
+ onError: (err) => {
149
+ logger.error("Translation server error:", err);
150
+ },
151
+ onReady: (port) => {
152
+ logger.info(`Translation server started successfully on port: ${port}`);
153
+ },
154
+ config: weglotConfig
155
+ });
156
+ process.env.WEGLOT_TRANSLATION_SERVER_URL = translationServer.url;
157
+ if (translationServer.server) registerCleanupOnCurrentProcess({ asyncCleanup: async () => {
158
+ await translationServer.server.stop();
159
+ } });
160
+ }
161
+ const translationServerUrl = process.env.WEGLOT_TRANSLATION_SERVER_URL;
162
+ if (isMainRunner()) {
163
+ const environment = weglotConfig.environment;
164
+ cleanupMetadataForEnvironment(metadataFilePath, environment);
165
+ registerCleanupOnCurrentProcess({ cleanup: () => cleanupMetadataForEnvironment(metadataFilePath, environment) });
166
+ }
167
+ const existingTurbopackConfig = getTurbopackConfig(nextConfig);
168
+ let mergedRules = mergeTurbopackRules(existingTurbopackConfig.rules ?? {}, Object.values(loaders({
169
+ weglotConfig,
170
+ metadataFilePath,
171
+ translationServerUrl
172
+ })).map((rules) => rules.turbopack));
173
+ const mergedResolveAlias = { ...existingTurbopackConfig.resolveAlias };
174
+ let turbopackConfig;
175
+ if (hasStableTurboConfig()) turbopackConfig = { turbopack: {
176
+ ...nextConfig.turbopack,
177
+ rules: mergedRules,
178
+ resolveAlias: mergedResolveAlias
179
+ } };
180
+ else turbopackConfig = { experimental: {
181
+ ...nextConfig.experimental,
182
+ turbo: {
183
+ ...nextConfig.experimental?.turbo,
184
+ rules: mergedRules,
185
+ resolveAlias: mergedResolveAlias
186
+ }
187
+ } };
188
+ const runAfterProductionCompile = async ({ distDir, projectDir }) => {
189
+ if (typeof nextConfig.compiler?.runAfterProductionCompile === "function") await nextConfig.compiler.runAfterProductionCompile({
190
+ distDir,
191
+ projectDir
192
+ });
193
+ logger.info("Running post-build translation generation...");
194
+ try {
195
+ await processBuildTranslations({
196
+ config: weglotConfig,
197
+ publicOutputPath: distDir,
198
+ metadataFilePath
199
+ });
200
+ } catch (error) {
201
+ logger.error("Translation generation failed:", error instanceof Error ? error.message : error);
202
+ throw error;
203
+ }
204
+ };
205
+ const webpack = (config, options) => {
206
+ let modifiedConfig = config;
207
+ if (typeof nextConfig.webpack === "function") modifiedConfig = nextConfig.webpack(config, options);
208
+ const weglotRules = Object.values(loaders({
209
+ weglotConfig,
210
+ metadataFilePath,
211
+ translationServerUrl
212
+ })).map((rules) => rules.webpack).filter(Boolean);
213
+ modifiedConfig.module.rules.unshift(...weglotRules);
214
+ return modifiedConfig;
215
+ };
216
+ return {
217
+ ...nextConfig,
218
+ ...turbopackConfig,
219
+ compiler: {
220
+ ...nextConfig.compiler,
221
+ runAfterProductionCompile
222
+ },
223
+ webpack
224
+ };
225
+ }
226
+
227
+ //#endregion
228
+ export { withWeglot };
229
+ //# sourceMappingURL=next.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next.mjs","names":["turbopackConfig: Partial<NextConfig>","webpack: NextJsWebpackConfig"],"sources":["../../src/plugin/next.ts"],"sourcesContent":["import type { NextConfig } from \"next\";\nimport type {\n NextJsWebpackConfig,\n TurbopackOptions,\n WebpackConfigContext,\n} from \"next/dist/server/config-shared\";\nimport {\n createWeglotConfig,\n resolveProjectLanguages,\n} from \"../utils/config-factory\";\nimport { logger } from \"../utils/logger\";\nimport type { WeglotConfig, PartialWeglotConfig } from \"../types\";\nimport { processBuildTranslations } from \"./build-translator\";\nimport { startOrGetTranslationServer } from \"../translation-server/translation-server\";\nimport { cleanupMetadataForEnvironment, getMetadataPath } from \"../metadata/manager\";\nimport { registerCleanupOnCurrentProcess } from \"./cleanup\";\nimport { useI18nRegex } from \"./transform/use-i18n\";\nimport { TranslationService } from \"../translators\";\n\nexport type WeglotNextPluginOptions = PartialWeglotConfig;\n\ntype RuleKey = \"compiler\" | \"config\" | \"localeServer\" | \"localeClient\";\n\nfunction loaders({\n weglotConfig,\n metadataFilePath,\n translationServerUrl,\n}: {\n weglotConfig: WeglotConfig;\n metadataFilePath: string;\n translationServerUrl?: string;\n}): Record<RuleKey, { turbopack?: any; webpack?: any }> {\n const common = {\n sourceRoot: weglotConfig.sourceRoot,\n weglotDir: weglotConfig.weglotDir,\n sourceLocale: weglotConfig.sourceLocale,\n };\n\n // TODO (AleksandrSl 14/12/2025): Type options.\n const compilerLoader = {\n loader: \"@weglot/translate-react/next-compiler-loader\",\n options: {\n ...common,\n useDirective: weglotConfig.useDirective,\n translatableAttributes: weglotConfig.translatableAttributes,\n metadataFilePath,\n },\n };\n\n const configLoader = {\n loader: \"@weglot/translate-react/next-config-loader\",\n options: {\n ...common,\n // The runtime reads these to address the API without a settings call.\n apiLocales: weglotConfig.apiLocales,\n translationEngine: weglotConfig.translationEngine,\n apiBaseUrl: weglotConfig.apiBaseUrl,\n // Turbopack rejects undefined options, left by an absent server URL.\n dev: Object.fromEntries(\n Object.entries({ translationServerUrl, ...weglotConfig.dev }).filter(\n ([, value]) => value !== undefined,\n ),\n ),\n },\n };\n const localeServerLoader = {\n loader: \"@weglot/translate-react/next-locale-server-loader\",\n options: {\n ...common,\n localePersistence: weglotConfig.localePersistence,\n },\n };\n\n const localeClientLoader = {\n loader: \"@weglot/translate-react/next-locale-client-loader\",\n options: {\n ...common,\n localePersistence: weglotConfig.localePersistence,\n },\n };\n\n return {\n compiler: {\n turbopack: {\n pattern: \"*.{tsx,jsx}\",\n config: {\n condition: {\n content: weglotConfig.useDirective ? useI18nRegex : undefined,\n },\n loaders: [compilerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /\\.(tsx|jsx)$/i,\n exclude: /node_modules/,\n use: [compilerLoader],\n },\n },\n\n // Every environment, not just dev: it also carries the locale map and engine,\n // whose placeholders would otherwise reach the browser.\n config: {\n turbopack: {\n pattern: \"**/virtual/config.mjs\",\n config: {\n loaders: [configLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/config\\.mjs$/i,\n use: [configLoader],\n },\n },\n\n localeServer: {\n turbopack: {\n pattern: \"**/virtual/locale/server.mjs\",\n config: {\n loaders: [localeServerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]server\\.mjs$/i,\n use: [localeServerLoader],\n },\n },\n\n localeClient: {\n turbopack: {\n pattern: \"**/virtual/locale/client.mjs\",\n config: {\n loaders: [localeClientLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]client\\.mjs$/i,\n use: [localeClientLoader],\n },\n },\n };\n}\n\n/**\n * Check if Next.js supports stable turbopack config (Next.js 16+)\n */\nfunction hasStableTurboConfig(): boolean {\n try {\n const nextPackage = require(\"next/package.json\");\n const majorVersion = parseInt(nextPackage.version.split(\".\")[0], 10);\n return majorVersion >= 16;\n } catch {\n return false;\n }\n}\n\nfunction getTurbopackConfig(userConfig: NextConfig): TurbopackOptions {\n return (\n (hasStableTurboConfig()\n ? userConfig?.turbopack\n : // @ts-expect-error - experimental.turbo for Next.js <16\n userConfig?.experimental?.turbo) || {}\n );\n}\n\n/**\n * Merge Turbopack rules without mutating original\n */\nfunction mergeTurbopackRules(\n existingRules: Record<string, any>,\n newRules: ({ pattern: string; config: any } | undefined)[],\n): Record<string, any> {\n const mergedRules = { ...existingRules };\n\n for (const newRule of newRules) {\n if (!newRule) continue;\n const { pattern, config } = newRule;\n\n if (mergedRules[pattern]) {\n if (Array.isArray(mergedRules[pattern])) {\n mergedRules[pattern] = [...mergedRules[pattern], config];\n } else {\n mergedRules[pattern] = [mergedRules[pattern], config];\n }\n } else {\n mergedRules[pattern] = config;\n }\n }\n\n return mergedRules;\n}\n\n// Next read config several times. Once in the main runner,\n// and ~ twice in the build workers which cannot get the config otherwise, because it's not serializable.\n// Workers start in separate processed by get most of the env from the main loader\nfunction isMainRunner() {\n return (\n !process.env.NEXT_PRIVATE_BUILD_WORKER &&\n !process.env.IS_NEXT_WORKER &&\n !process.env.NEXT_PRIVATE_WORKER\n );\n}\n\nexport async function withWeglot(\n nextConfig: NextConfig = {},\n weglotOptions: WeglotNextPluginOptions,\n): Promise<NextConfig> {\n const weglotConfig = createWeglotConfig(weglotOptions);\n await resolveProjectLanguages(weglotConfig);\n let metadataFilePath = getMetadataPath(weglotConfig);\n const isDev = weglotConfig.environment === \"development\";\n\n logger.debug(\n `Initializing Weglot. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`,\n );\n\n // Try to start up the translation server once.\n // We have two barriers, a simple one here and a more complex one inside the startTranslationServer which doesn't start the server if it can find one running.\n // We do not use isMainRunner here, because we need to start the server as early as possible, so the loaders get the translation server url. The main runner in dev mode runs after a dev server process is started.\n if (isDev && !process.env.WEGLOT_TRANSLATION_SERVER_URL) {\n if (weglotConfig.dev.translationServerUrl) {\n logger.info(`Using existing translation server URL (${weglotConfig.dev.translationServerUrl}) from config`);\n process.env.WEGLOT_TRANSLATION_SERVER_URL =\n weglotConfig.dev.translationServerUrl;\n } else {\n const translationServer = await startOrGetTranslationServer({\n translationService: new TranslationService(weglotConfig, logger),\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n onReady: (port) => {\n logger.info(\n `Translation server started successfully on port: ${port}`,\n );\n },\n config: weglotConfig,\n });\n process.env.WEGLOT_TRANSLATION_SERVER_URL = translationServer.url;\n if (translationServer.server) {\n // We start the server in the same process, so we should be fine without any sync cleanup. Server should be killed with the process.\n registerCleanupOnCurrentProcess({\n asyncCleanup: async () => {\n await translationServer.server.stop();\n },\n });\n }\n }\n }\n\n const translationServerUrl = process.env.WEGLOT_TRANSLATION_SERVER_URL;\n\n if (isMainRunner()) {\n const environment = weglotConfig.environment;\n cleanupMetadataForEnvironment(metadataFilePath, environment);\n\n registerCleanupOnCurrentProcess({\n cleanup: () => cleanupMetadataForEnvironment(metadataFilePath, environment),\n });\n }\n\n const existingTurbopackConfig = getTurbopackConfig(nextConfig);\n let mergedRules = mergeTurbopackRules(\n existingTurbopackConfig.rules ?? {},\n Object.values(\n loaders({ weglotConfig, metadataFilePath, translationServerUrl }),\n ).map((rules) => rules.turbopack),\n );\n\n const existingResolveAlias = existingTurbopackConfig.resolveAlias;\n const mergedResolveAlias = {\n ...existingResolveAlias,\n };\n\n let turbopackConfig: Partial<NextConfig>;\n if (hasStableTurboConfig()) {\n turbopackConfig = {\n turbopack: {\n ...nextConfig.turbopack, // Preserve existing turbopack options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n };\n } else {\n turbopackConfig = {\n experimental: {\n ...nextConfig.experimental, // Preserve ALL experimental options\n // @ts-expect-error - turbo for Next.js <16\n turbo: {\n // @ts-expect-error - turbo for Next.js <16\n ...nextConfig.experimental?.turbo, // Preserve existing turbo options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n },\n };\n }\n\n const runAfterProductionCompile = async ({\n distDir,\n projectDir,\n }: {\n distDir: string;\n projectDir: string;\n }) => {\n if (typeof nextConfig.compiler?.runAfterProductionCompile === \"function\") {\n await nextConfig.compiler.runAfterProductionCompile({\n distDir,\n projectDir,\n });\n }\n\n logger.info(\"Running post-build translation generation...\");\n\n try {\n await processBuildTranslations({\n config: weglotConfig,\n publicOutputPath: distDir,\n metadataFilePath,\n });\n } catch (error) {\n logger.error(\n \"Translation generation failed:\",\n error instanceof Error ? error.message : error,\n );\n throw error;\n }\n };\n\n const webpack: NextJsWebpackConfig = (\n config: any,\n options: WebpackConfigContext,\n ) => {\n // Apply user's webpack config first if it exists\n let modifiedConfig = config;\n if (typeof nextConfig.webpack === \"function\") {\n modifiedConfig = nextConfig.webpack(config, options);\n }\n\n const weglotRules = Object.values(\n loaders({ weglotConfig, metadataFilePath, translationServerUrl }),\n )\n .map((rules) => rules.webpack)\n .filter(Boolean);\n\n // I tried using plugin from unplugin, but with all the loaders stuff it works poorly.\n // Failing with weird errors which appear on the later compilations, probably something with the cache and virtual modules\n modifiedConfig.module.rules.unshift(...weglotRules);\n\n return modifiedConfig;\n };\n\n return {\n ...nextConfig,\n ...turbopackConfig,\n compiler: {\n ...nextConfig.compiler,\n runAfterProductionCompile,\n },\n webpack,\n };\n}\n"],"mappings":";;;;;;;;;;;AAuBA,SAAS,QAAQ,EACf,cACA,kBACA,wBAKsD;CACtD,MAAM,SAAS;EACb,YAAY,aAAa;EACzB,WAAW,aAAa;EACxB,cAAc,aAAa;EAC5B;CAGD,MAAM,iBAAiB;EACrB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,cAAc,aAAa;GAC3B,wBAAwB,aAAa;GACrC;GACD;EACF;CAED,MAAM,eAAe;EACnB,QAAQ;EACR,SAAS;GACP,GAAG;GAEH,YAAY,aAAa;GACzB,mBAAmB,aAAa;GAChC,YAAY,aAAa;GAEzB,KAAK,OAAO,YACV,OAAO,QAAQ;IAAE;IAAsB,GAAG,aAAa;IAAK,CAAC,CAAC,QAC3D,GAAG,WAAW,UAAU,OAC1B,CACF;GACF;EACF;CACD,MAAM,qBAAqB;EACzB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,mBAAmB,aAAa;GACjC;EACF;CAED,MAAM,qBAAqB;EACzB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,mBAAmB,aAAa;GACjC;EACF;AAED,QAAO;EACL,UAAU;GACR,WAAW;IACT,SAAS;IACT,QAAQ;KACN,WAAW,EACT,SAAS,aAAa,eAAe,eAAe,QACrD;KACD,SAAS,CAAC,eAAe;KAC1B;IACF;GACD,SAAS;IACP,SAAS;IACT,MAAM;IACN,SAAS;IACT,KAAK,CAAC,eAAe;IACtB;GACF;EAID,QAAQ;GACN,WAAW;IACT,SAAS;IACT,QAAQ,EACN,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MAAM,4BAA4B,OAAO,EACvC,SACA,iBAII;AACJ,MAAI,OAAO,WAAW,UAAU,8BAA8B,WAC5D,OAAM,WAAW,SAAS,0BAA0B;GAClD;GACA;GACD,CAAC;AAGJ,SAAO,KAAK,+CAA+C;AAE3D,MAAI;AACF,SAAM,yBAAyB;IAC7B,QAAQ;IACR,kBAAkB;IAClB;IACD,CAAC;WACK,OAAO;AACd,UAAO,MACL,kCACA,iBAAiB,QAAQ,MAAM,UAAU,MAC1C;AACD,SAAM;;;CAIV,MAAMC,WACJ,QACA,YACG;EAEH,IAAI,iBAAiB;AACrB,MAAI,OAAO,WAAW,YAAY,WAChC,kBAAiB,WAAW,QAAQ,QAAQ,QAAQ;EAGtD,MAAM,cAAc,OAAO,OACzB,QAAQ;GAAE;GAAc;GAAkB;GAAsB,CAAC,CAClE,CACE,KAAK,UAAU,MAAM,QAAQ,CAC7B,OAAO,QAAQ;AAIlB,iBAAe,OAAO,MAAM,QAAQ,GAAG,YAAY;AAEnD,SAAO;;AAGT,QAAO;EACL,GAAG;EACH,GAAG;EACH,UAAU;GACR,GAAG,WAAW;GACd;GACD;EACD;EACD"}
@@ -0,0 +1,13 @@
1
+ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
+ let _babel_traverse = require("@babel/traverse");
3
+ _babel_traverse = require_rolldown_runtime.__toESM(_babel_traverse);
4
+ let _babel_generator = require("@babel/generator");
5
+ _babel_generator = require_rolldown_runtime.__toESM(_babel_generator);
6
+
7
+ //#region src/plugin/transform/babel-compat.ts
8
+ const traverse = _babel_traverse.default.default ?? _babel_traverse.default;
9
+ const generate = _babel_generator.default.default ?? _babel_generator.default;
10
+
11
+ //#endregion
12
+ exports.generate = generate;
13
+ exports.traverse = traverse;
@@ -0,0 +1,10 @@
1
+ import traverseDefault from "@babel/traverse";
2
+ import generateDefault from "@babel/generator";
3
+
4
+ //#region src/plugin/transform/babel-compat.ts
5
+ const traverse = traverseDefault.default ?? traverseDefault;
6
+ const generate = generateDefault.default ?? generateDefault;
7
+
8
+ //#endregion
9
+ export { generate, traverse };
10
+ //# sourceMappingURL=babel-compat.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"babel-compat.mjs","names":["traverse: typeof traverseDefault","generate: typeof generateDefault"],"sources":["../../../src/plugin/transform/babel-compat.ts"],"sourcesContent":["import traverseDefault from \"@babel/traverse\";\nimport generateDefault from \"@babel/generator\";\n\n// Handle ESM/CJS interop - these packages may export differently\nconst traverse: typeof traverseDefault =\n // @ts-expect-error - Handle both default and named exports\n traverseDefault.default ?? traverseDefault;\nconst generate: typeof generateDefault =\n // @ts-expect-error - Handle both default and named exports\n generateDefault.default ?? generateDefault;\n\nexport { traverse, generate };\n"],"mappings":";;;;AAIA,MAAMA,WAEJ,gBAAgB,WAAW;AAC7B,MAAMC,WAEJ,gBAAgB,WAAW"}
@@ -0,0 +1,145 @@
1
+ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
+ const require_utils = require('./utils.cjs');
3
+ let _babel_types = require("@babel/types");
4
+ _babel_types = require_rolldown_runtime.__toESM(_babel_types);
5
+
6
+ //#region src/plugin/transform/expression-strings.ts
7
+ /**
8
+ * String literals inside JSX expressions, which the JSX text walker never sees.
9
+ * Only JSX children and already-translated attributes are considered.
10
+ */
11
+ /** A single lowercase token is an identifier or class name, never a sentence. */
12
+ const IDENTIFIER_LIKE = /^[a-z0-9]+([_-][a-z0-9]+)*$/;
13
+ /** A path, a URL, or a file name: addresses, not copy. */
14
+ const ADDRESS_LIKE = /^(\/|\.{1,2}\/|#|[a-z][a-z0-9+.-]*:)|\.[a-z0-9]{2,4}$/i;
15
+ /** A dotted identifier path is a lookup key: `features.words`. Copy has spaces. */
16
+ const KEY_LIKE = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
17
+ function isTranslatableText(value) {
18
+ const text = value.trim();
19
+ if (text.length === 0) return false;
20
+ if (!/\p{L}/u.test(text)) return false;
21
+ if (IDENTIFIER_LIKE.test(text)) return false;
22
+ if (ADDRESS_LIKE.test(text)) return false;
23
+ if (KEY_LIKE.test(text)) return false;
24
+ return true;
25
+ }
26
+ function isTranslatablePosition(path, translatableAttributes) {
27
+ const parent = path.parent;
28
+ if (parent.type === "JSXElement" || parent.type === "JSXFragment") return true;
29
+ if (parent.type === "JSXAttribute" && parent.name.type === "JSXIdentifier") return translatableAttributes.has(parent.name.name.toLowerCase());
30
+ return false;
31
+ }
32
+ /** Literals in value position, following only these shapes so no arbitrary call is searched. */
33
+ function collectLiteralPaths(path) {
34
+ const node = path.node;
35
+ if (_babel_types.isStringLiteral(node) || _babel_types.isTemplateLiteral(node)) return [path];
36
+ if (_babel_types.isConditionalExpression(node)) return [...collectLiteralPaths(path.get("consequent")), ...collectLiteralPaths(path.get("alternate"))];
37
+ if (_babel_types.isLogicalExpression(node)) {
38
+ const right = collectLiteralPaths(path.get("right"));
39
+ return node.operator === "??" ? [...collectLiteralPaths(path.get("left")), ...right] : right;
40
+ }
41
+ if (_babel_types.isMemberExpression(node)) return collectLiteralPaths(path.get("object"));
42
+ if (_babel_types.isArrayExpression(node)) return path.get("elements").flatMap((element) => collectLiteralPaths(element));
43
+ if (_babel_types.isObjectExpression(node)) return path.get("properties").flatMap((property) => property.isObjectProperty() ? collectLiteralPaths(property.get("value")) : []);
44
+ return [];
45
+ }
46
+ function isStaticStringHolder(node) {
47
+ if (_babel_types.isStringLiteral(node)) return true;
48
+ if (_babel_types.isArrayExpression(node)) return node.elements.every((element) => isStaticStringHolder(element));
49
+ if (_babel_types.isObjectExpression(node)) return node.properties.every((property) => _babel_types.isObjectProperty(property) && !property.computed && isStaticStringHolder(property.value));
50
+ return false;
51
+ }
52
+ function holdsTranslatableText(node) {
53
+ if (_babel_types.isStringLiteral(node)) return isTranslatableText(node.value);
54
+ if (_babel_types.isArrayExpression(node)) return node.elements.some((element) => element != null && holdsTranslatableText(element));
55
+ if (_babel_types.isObjectExpression(node)) return node.properties.some((property) => _babel_types.isObjectProperty(property) && holdsTranslatableText(property.value));
56
+ return false;
57
+ }
58
+ function constantValue(path) {
59
+ if (!path.isIdentifier()) return null;
60
+ const binding = path.scope.getBinding(path.node.name);
61
+ if (!binding || binding.kind !== "const" || !binding.constant) return null;
62
+ if (!binding.path.isVariableDeclarator()) return null;
63
+ const initializer = binding.path.node.init;
64
+ if (!initializer || !isStaticStringHolder(initializer)) return null;
65
+ return initializer;
66
+ }
67
+ function staticKey(node) {
68
+ if (!node.computed && _babel_types.isIdentifier(node.property)) return node.property.name;
69
+ if (node.computed && _babel_types.isStringLiteral(node.property)) return node.property.value;
70
+ return null;
71
+ }
72
+ /** What a member access on a constant yields: `LABELS.title` is copy, `.length` is not. */
73
+ function readThrough(node, value) {
74
+ if (_babel_types.isArrayExpression(value)) return node.computed ? {
75
+ whole: false,
76
+ replacement: value
77
+ } : null;
78
+ if (_babel_types.isObjectExpression(value)) {
79
+ const key = staticKey(node);
80
+ if (key === null) return {
81
+ whole: false,
82
+ replacement: value
83
+ };
84
+ const property = value.properties.find((candidate) => _babel_types.isObjectProperty(candidate) && !candidate.computed && (_babel_types.isIdentifier(candidate.key) ? candidate.key.name === key : _babel_types.isStringLiteral(candidate.key) && candidate.key.value === key));
85
+ if (!property || !_babel_types.isObjectProperty(property)) return null;
86
+ return {
87
+ whole: true,
88
+ replacement: property.value
89
+ };
90
+ }
91
+ return null;
92
+ }
93
+ /** Only a constant read through a member access: a bare `{label}` is already
94
+ * an ICU parameter. */
95
+ function collectConstantReferences(path) {
96
+ const node = path.node;
97
+ const follow = (key) => collectConstantReferences(path.get(key));
98
+ if (_babel_types.isConditionalExpression(node)) return [...follow("consequent"), ...follow("alternate")];
99
+ if (_babel_types.isLogicalExpression(node)) return node.operator === "??" ? [...follow("left"), ...follow("right")] : follow("right");
100
+ if (_babel_types.isMemberExpression(node)) {
101
+ const objectPath = path.get("object");
102
+ const value = constantValue(objectPath);
103
+ if (!value) return follow("object");
104
+ const read = readThrough(node, value);
105
+ if (!read || !holdsTranslatableText(read.replacement)) return [];
106
+ return [{
107
+ path: read.whole ? path : objectPath,
108
+ replacement: read.replacement
109
+ }];
110
+ }
111
+ return [];
112
+ }
113
+ /** `` `Invite ${name}` `` becomes `Invite {name}`, holes named after the
114
+ * identifier they read. Null when the static half carries no copy. */
115
+ function templateToMessage(node) {
116
+ const variables = [];
117
+ const expressions = /* @__PURE__ */ new Map();
118
+ let text = "";
119
+ node.quasis.forEach((quasi, index) => {
120
+ text += require_utils.escapeTextForICU(quasi.value.cooked ?? quasi.value.raw);
121
+ const expression = node.expressions[index];
122
+ if (!expression || !_babel_types.isExpression(expression)) return;
123
+ if (_babel_types.isIdentifier(expression)) {
124
+ text += `{${expression.name}}`;
125
+ if (!variables.includes(expression.name)) variables.push(expression.name);
126
+ return;
127
+ }
128
+ const name = `expression${expressions.size}`;
129
+ text += `{${name}}`;
130
+ expressions.set(name, expression);
131
+ });
132
+ if (!isTranslatableText(node.quasis.map((quasi) => quasi.value.cooked ?? quasi.value.raw).join(" "))) return null;
133
+ return {
134
+ text,
135
+ variables,
136
+ expressions
137
+ };
138
+ }
139
+
140
+ //#endregion
141
+ exports.collectConstantReferences = collectConstantReferences;
142
+ exports.collectLiteralPaths = collectLiteralPaths;
143
+ exports.isTranslatablePosition = isTranslatablePosition;
144
+ exports.isTranslatableText = isTranslatableText;
145
+ exports.templateToMessage = templateToMessage;
@@ -0,0 +1,140 @@
1
+ import { escapeTextForICU } from "./utils.mjs";
2
+ import * as t from "@babel/types";
3
+
4
+ //#region src/plugin/transform/expression-strings.ts
5
+ /**
6
+ * String literals inside JSX expressions, which the JSX text walker never sees.
7
+ * Only JSX children and already-translated attributes are considered.
8
+ */
9
+ /** A single lowercase token is an identifier or class name, never a sentence. */
10
+ const IDENTIFIER_LIKE = /^[a-z0-9]+([_-][a-z0-9]+)*$/;
11
+ /** A path, a URL, or a file name: addresses, not copy. */
12
+ const ADDRESS_LIKE = /^(\/|\.{1,2}\/|#|[a-z][a-z0-9+.-]*:)|\.[a-z0-9]{2,4}$/i;
13
+ /** A dotted identifier path is a lookup key: `features.words`. Copy has spaces. */
14
+ const KEY_LIKE = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
15
+ function isTranslatableText(value) {
16
+ const text = value.trim();
17
+ if (text.length === 0) return false;
18
+ if (!/\p{L}/u.test(text)) return false;
19
+ if (IDENTIFIER_LIKE.test(text)) return false;
20
+ if (ADDRESS_LIKE.test(text)) return false;
21
+ if (KEY_LIKE.test(text)) return false;
22
+ return true;
23
+ }
24
+ function isTranslatablePosition(path, translatableAttributes) {
25
+ const parent = path.parent;
26
+ if (parent.type === "JSXElement" || parent.type === "JSXFragment") return true;
27
+ if (parent.type === "JSXAttribute" && parent.name.type === "JSXIdentifier") return translatableAttributes.has(parent.name.name.toLowerCase());
28
+ return false;
29
+ }
30
+ /** Literals in value position, following only these shapes so no arbitrary call is searched. */
31
+ function collectLiteralPaths(path) {
32
+ const node = path.node;
33
+ if (t.isStringLiteral(node) || t.isTemplateLiteral(node)) return [path];
34
+ if (t.isConditionalExpression(node)) return [...collectLiteralPaths(path.get("consequent")), ...collectLiteralPaths(path.get("alternate"))];
35
+ if (t.isLogicalExpression(node)) {
36
+ const right = collectLiteralPaths(path.get("right"));
37
+ return node.operator === "??" ? [...collectLiteralPaths(path.get("left")), ...right] : right;
38
+ }
39
+ if (t.isMemberExpression(node)) return collectLiteralPaths(path.get("object"));
40
+ if (t.isArrayExpression(node)) return path.get("elements").flatMap((element) => collectLiteralPaths(element));
41
+ if (t.isObjectExpression(node)) return path.get("properties").flatMap((property) => property.isObjectProperty() ? collectLiteralPaths(property.get("value")) : []);
42
+ return [];
43
+ }
44
+ function isStaticStringHolder(node) {
45
+ if (t.isStringLiteral(node)) return true;
46
+ if (t.isArrayExpression(node)) return node.elements.every((element) => isStaticStringHolder(element));
47
+ if (t.isObjectExpression(node)) return node.properties.every((property) => t.isObjectProperty(property) && !property.computed && isStaticStringHolder(property.value));
48
+ return false;
49
+ }
50
+ function holdsTranslatableText(node) {
51
+ if (t.isStringLiteral(node)) return isTranslatableText(node.value);
52
+ if (t.isArrayExpression(node)) return node.elements.some((element) => element != null && holdsTranslatableText(element));
53
+ if (t.isObjectExpression(node)) return node.properties.some((property) => t.isObjectProperty(property) && holdsTranslatableText(property.value));
54
+ return false;
55
+ }
56
+ function constantValue(path) {
57
+ if (!path.isIdentifier()) return null;
58
+ const binding = path.scope.getBinding(path.node.name);
59
+ if (!binding || binding.kind !== "const" || !binding.constant) return null;
60
+ if (!binding.path.isVariableDeclarator()) return null;
61
+ const initializer = binding.path.node.init;
62
+ if (!initializer || !isStaticStringHolder(initializer)) return null;
63
+ return initializer;
64
+ }
65
+ function staticKey(node) {
66
+ if (!node.computed && t.isIdentifier(node.property)) return node.property.name;
67
+ if (node.computed && t.isStringLiteral(node.property)) return node.property.value;
68
+ return null;
69
+ }
70
+ /** What a member access on a constant yields: `LABELS.title` is copy, `.length` is not. */
71
+ function readThrough(node, value) {
72
+ if (t.isArrayExpression(value)) return node.computed ? {
73
+ whole: false,
74
+ replacement: value
75
+ } : null;
76
+ if (t.isObjectExpression(value)) {
77
+ const key = staticKey(node);
78
+ if (key === null) return {
79
+ whole: false,
80
+ replacement: value
81
+ };
82
+ const property = value.properties.find((candidate) => t.isObjectProperty(candidate) && !candidate.computed && (t.isIdentifier(candidate.key) ? candidate.key.name === key : t.isStringLiteral(candidate.key) && candidate.key.value === key));
83
+ if (!property || !t.isObjectProperty(property)) return null;
84
+ return {
85
+ whole: true,
86
+ replacement: property.value
87
+ };
88
+ }
89
+ return null;
90
+ }
91
+ /** Only a constant read through a member access: a bare `{label}` is already
92
+ * an ICU parameter. */
93
+ function collectConstantReferences(path) {
94
+ const node = path.node;
95
+ const follow = (key) => collectConstantReferences(path.get(key));
96
+ if (t.isConditionalExpression(node)) return [...follow("consequent"), ...follow("alternate")];
97
+ if (t.isLogicalExpression(node)) return node.operator === "??" ? [...follow("left"), ...follow("right")] : follow("right");
98
+ if (t.isMemberExpression(node)) {
99
+ const objectPath = path.get("object");
100
+ const value = constantValue(objectPath);
101
+ if (!value) return follow("object");
102
+ const read = readThrough(node, value);
103
+ if (!read || !holdsTranslatableText(read.replacement)) return [];
104
+ return [{
105
+ path: read.whole ? path : objectPath,
106
+ replacement: read.replacement
107
+ }];
108
+ }
109
+ return [];
110
+ }
111
+ /** `` `Invite ${name}` `` becomes `Invite {name}`, holes named after the
112
+ * identifier they read. Null when the static half carries no copy. */
113
+ function templateToMessage(node) {
114
+ const variables = [];
115
+ const expressions = /* @__PURE__ */ new Map();
116
+ let text = "";
117
+ node.quasis.forEach((quasi, index) => {
118
+ text += escapeTextForICU(quasi.value.cooked ?? quasi.value.raw);
119
+ const expression = node.expressions[index];
120
+ if (!expression || !t.isExpression(expression)) return;
121
+ if (t.isIdentifier(expression)) {
122
+ text += `{${expression.name}}`;
123
+ if (!variables.includes(expression.name)) variables.push(expression.name);
124
+ return;
125
+ }
126
+ const name = `expression${expressions.size}`;
127
+ text += `{${name}}`;
128
+ expressions.set(name, expression);
129
+ });
130
+ if (!isTranslatableText(node.quasis.map((quasi) => quasi.value.cooked ?? quasi.value.raw).join(" "))) return null;
131
+ return {
132
+ text,
133
+ variables,
134
+ expressions
135
+ };
136
+ }
137
+
138
+ //#endregion
139
+ export { collectConstantReferences, collectLiteralPaths, isTranslatablePosition, isTranslatableText, templateToMessage };
140
+ //# sourceMappingURL=expression-strings.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"expression-strings.mjs","names":["variables: string[]"],"sources":["../../../src/plugin/transform/expression-strings.ts"],"sourcesContent":["/**\n * String literals inside JSX expressions, which the JSX text walker never sees.\n * Only JSX children and already-translated attributes are considered.\n */\n\nimport * as t from \"@babel/types\";\nimport type { NodePath } from \"@babel/traverse\";\nimport { escapeTextForICU } from \"./utils\";\n\n/** A single lowercase token is an identifier or class name, never a sentence. */\nconst IDENTIFIER_LIKE = /^[a-z0-9]+([_-][a-z0-9]+)*$/;\n\n/** A path, a URL, or a file name: addresses, not copy. */\nconst ADDRESS_LIKE = /^(\\/|\\.{1,2}\\/|#|[a-z][a-z0-9+.-]*:)|\\.[a-z0-9]{2,4}$/i;\n\n/** A dotted identifier path is a lookup key: `features.words`. Copy has spaces. */\nconst KEY_LIKE = /^[a-z][A-Za-z0-9]*(\\.[a-z][A-Za-z0-9]*)+$/;\n\nexport function isTranslatableText(value: string): boolean {\n const text = value.trim();\n if (text.length === 0) return false;\n if (!/\\p{L}/u.test(text)) return false;\n if (IDENTIFIER_LIKE.test(text)) return false;\n if (ADDRESS_LIKE.test(text)) return false;\n if (KEY_LIKE.test(text)) return false;\n return true;\n}\n\nexport function isTranslatablePosition(\n path: NodePath<t.JSXExpressionContainer>,\n translatableAttributes: ReadonlySet<string>,\n): boolean {\n const parent = path.parent;\n\n if (parent.type === \"JSXElement\" || parent.type === \"JSXFragment\") {\n return true;\n }\n\n if (parent.type === \"JSXAttribute\" && parent.name.type === \"JSXIdentifier\") {\n return translatableAttributes.has(parent.name.name.toLowerCase());\n }\n\n return false;\n}\n\nexport type TranslatableLiteral = t.StringLiteral | t.TemplateLiteral;\n\n/** Literals in value position, following only these shapes so no arbitrary call is searched. */\nexport function collectLiteralPaths(\n path: NodePath<t.Node>,\n): NodePath<TranslatableLiteral>[] {\n const node = path.node;\n\n if (t.isStringLiteral(node) || t.isTemplateLiteral(node)) {\n return [path as NodePath<TranslatableLiteral>];\n }\n\n if (t.isConditionalExpression(node)) {\n return [\n ...collectLiteralPaths(path.get(\"consequent\") as NodePath<t.Node>),\n ...collectLiteralPaths(path.get(\"alternate\") as NodePath<t.Node>),\n ];\n }\n\n if (t.isLogicalExpression(node)) {\n const right = collectLiteralPaths(path.get(\"right\") as NodePath<t.Node>);\n // The left of && or || is a condition; the left of ?? is a value.\n return node.operator === \"??\"\n ? [...collectLiteralPaths(path.get(\"left\") as NodePath<t.Node>), ...right]\n : right;\n }\n\n // A copied-in constant: `{STATUSES[i]}` is an array literal indexed in place.\n if (t.isMemberExpression(node)) {\n return collectLiteralPaths(path.get(\"object\") as NodePath<t.Node>);\n }\n\n if (t.isArrayExpression(node)) {\n return (path.get(\"elements\") as NodePath<t.Node>[]).flatMap((element) =>\n collectLiteralPaths(element),\n );\n }\n\n if (t.isObjectExpression(node)) {\n return (path.get(\"properties\") as NodePath<t.Node>[]).flatMap((property) =>\n property.isObjectProperty()\n ? collectLiteralPaths(property.get(\"value\") as NodePath<t.Node>)\n : [],\n );\n }\n\n return [];\n}\n\n/** A constant is copied to where it is read: a declaration outside the\n * component cannot call the translation hook. */\nexport interface ConstantReference {\n path: NodePath<t.Node>;\n replacement: t.Expression;\n}\n\nfunction isStaticStringHolder(node: t.Node | null | undefined): boolean {\n if (t.isStringLiteral(node)) return true;\n if (t.isArrayExpression(node)) {\n return node.elements.every((element) => isStaticStringHolder(element));\n }\n if (t.isObjectExpression(node)) {\n return node.properties.every(\n (property) =>\n t.isObjectProperty(property) &&\n !property.computed &&\n isStaticStringHolder(property.value),\n );\n }\n return false;\n}\n\nfunction holdsTranslatableText(node: t.Node): boolean {\n if (t.isStringLiteral(node)) return isTranslatableText(node.value);\n if (t.isArrayExpression(node)) {\n return node.elements.some(\n (element) => element != null && holdsTranslatableText(element),\n );\n }\n if (t.isObjectExpression(node)) {\n return node.properties.some(\n (property) =>\n t.isObjectProperty(property) && holdsTranslatableText(property.value),\n );\n }\n return false;\n}\n\nfunction constantValue(path: NodePath<t.Node>): t.Expression | null {\n if (!path.isIdentifier()) return null;\n const binding = path.scope.getBinding(path.node.name);\n if (!binding || binding.kind !== \"const\" || !binding.constant) return null;\n if (!binding.path.isVariableDeclarator()) return null;\n\n const initializer = binding.path.node.init;\n if (!initializer || !isStaticStringHolder(initializer)) return null;\n return initializer;\n}\n\nfunction staticKey(node: t.MemberExpression): string | null {\n if (!node.computed && t.isIdentifier(node.property)) return node.property.name;\n if (node.computed && t.isStringLiteral(node.property)) return node.property.value;\n return null;\n}\n\n/** What a member access on a constant yields: `LABELS.title` is copy, `.length` is not. */\nfunction readThrough(\n node: t.MemberExpression,\n value: t.Expression,\n): { whole: boolean; replacement: t.Expression } | null {\n if (t.isArrayExpression(value)) {\n return node.computed ? { whole: false, replacement: value } : null;\n }\n\n if (t.isObjectExpression(value)) {\n const key = staticKey(node);\n if (key === null) return { whole: false, replacement: value };\n const property = value.properties.find(\n (candidate) =>\n t.isObjectProperty(candidate) &&\n !candidate.computed &&\n (t.isIdentifier(candidate.key)\n ? candidate.key.name === key\n : t.isStringLiteral(candidate.key) && candidate.key.value === key),\n );\n if (!property || !t.isObjectProperty(property)) return null;\n return { whole: true, replacement: property.value as t.Expression };\n }\n\n return null;\n}\n\n/** Only a constant read through a member access: a bare `{label}` is already\n * an ICU parameter. */\nexport function collectConstantReferences(\n path: NodePath<t.Node>,\n): ConstantReference[] {\n const node = path.node;\n const follow = (key: string) =>\n collectConstantReferences(path.get(key) as NodePath<t.Node>);\n\n if (t.isConditionalExpression(node)) {\n return [...follow(\"consequent\"), ...follow(\"alternate\")];\n }\n\n if (t.isLogicalExpression(node)) {\n return node.operator === \"??\"\n ? [...follow(\"left\"), ...follow(\"right\")]\n : follow(\"right\");\n }\n\n if (t.isMemberExpression(node)) {\n const objectPath = path.get(\"object\") as NodePath<t.Node>;\n const value = constantValue(objectPath);\n if (!value) return follow(\"object\");\n\n const read = readThrough(node, value);\n if (!read || !holdsTranslatableText(read.replacement)) return [];\n return [\n {\n path: read.whole ? path : objectPath,\n replacement: read.replacement,\n },\n ];\n }\n\n return [];\n}\n\nexport interface TemplateMessage {\n text: string;\n variables: string[];\n expressions: Map<string, t.Expression>;\n}\n\n/** `` `Invite ${name}` `` becomes `Invite {name}`, holes named after the\n * identifier they read. Null when the static half carries no copy. */\nexport function templateToMessage(node: t.TemplateLiteral): TemplateMessage | null {\n const variables: string[] = [];\n const expressions = new Map<string, t.Expression>();\n let text = \"\";\n\n node.quasis.forEach((quasi, index) => {\n text += escapeTextForICU(quasi.value.cooked ?? quasi.value.raw);\n\n const expression = node.expressions[index];\n if (!expression || !t.isExpression(expression)) return;\n\n if (t.isIdentifier(expression)) {\n text += `{${expression.name}}`;\n if (!variables.includes(expression.name)) {\n variables.push(expression.name);\n }\n return;\n }\n\n const name = `expression${expressions.size}`;\n text += `{${name}}`;\n expressions.set(name, expression);\n });\n\n const staticText = node.quasis\n .map((quasi) => quasi.value.cooked ?? quasi.value.raw)\n .join(\" \");\n if (!isTranslatableText(staticText)) return null;\n\n return { text, variables, expressions };\n}\n"],"mappings":";;;;;;;;;AAUA,MAAM,kBAAkB;;AAGxB,MAAM,eAAe;;AAGrB,MAAM,WAAW;AAEjB,SAAgB,mBAAmB,OAAwB;CACzD,MAAM,OAAO,MAAM,MAAM;AACzB,KAAI,KAAK,WAAW,EAAG,QAAO;AAC9B,KAAI,CAAC,SAAS,KAAK,KAAK,CAAE,QAAO;AACjC,KAAI,gBAAgB,KAAK,KAAK,CAAE,QAAO;AACvC,KAAI,aAAa,KAAK,KAAK,CAAE,QAAO;AACpC,KAAI,SAAS,KAAK,KAAK,CAAE,QAAO;AAChC,QAAO;;AAGT,SAAgB,uBACd,MACA,wBACS;CACT,MAAM,SAAS,KAAK;AAEpB,KAAI,OAAO,SAAS,gBAAgB,OAAO,SAAS,cAClD,QAAO;AAGT,KAAI,OAAO,SAAS,kBAAkB,OAAO,KAAK,SAAS,gBACzD,QAAO,uBAAuB,IAAI,OAAO,KAAK,KAAK,aAAa,CAAC;AAGnE,QAAO;;;AAMT,SAAgB,oBACd,MACiC;CACjC,MAAM,OAAO,KAAK;AAElB,KAAI,EAAE,gBAAgB,KAAK,IAAI,EAAE,kBAAkB,KAAK,CACtD,QAAO,CAAC,KAAsC;AAGhD,KAAI,EAAE,wBAAwB,KAAK,CACjC,QAAO,CACL,GAAG,oBAAoB,KAAK,IAAI,aAAa,CAAqB,EAClE,GAAG,oBAAoB,KAAK,IAAI,YAAY,CAAqB,CAClE;AAGH,KAAI,EAAE,oBAAoB,KAAK,EAAE;EAC/B,M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0 +1,45 @@
1
+ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
+ const require_logger = require('../../utils/logger.cjs');
3
+ const require_babel_compat = require('./babel-compat.cjs');
4
+ const require_process_file = require('./process-file.cjs');
5
+ let path = require("path");
6
+ path = require_rolldown_runtime.__toESM(path);
7
+ let _babel_parser = require("@babel/parser");
8
+ _babel_parser = require_rolldown_runtime.__toESM(_babel_parser);
9
+
10
+ //#region src/plugin/transform/index.ts
11
+ /**
12
+ * Transform component code to inject translation calls
13
+ */
14
+ function transformComponent({ code, filePath, config }) {
15
+ const relativeFilePath = path.default.relative(path.default.resolve(config.sourceRoot), filePath).split(path.default.sep).join("/");
16
+ try {
17
+ const ast = _babel_parser.parse(code, {
18
+ sourceType: "module",
19
+ plugins: ["jsx", "typescript"]
20
+ });
21
+ require_logger.logger.debug(`Transforming ${filePath}`);
22
+ const translationEntries = require_process_file.processFile(ast, {
23
+ relativeFilePath,
24
+ needsDirective: config.useDirective,
25
+ translatableAttributes: config.translatableAttributes
26
+ });
27
+ const output = require_babel_compat.generate(ast, { sourceMaps: true }, code);
28
+ require_logger.logger.debug(`Transformed ${filePath}. Code: ${output.code}`);
29
+ return {
30
+ code: output.code,
31
+ map: output.map,
32
+ newEntries: translationEntries,
33
+ transformed: translationEntries.length > 0
34
+ };
35
+ } catch (error) {
36
+ require_logger.logger.error(`Failed to transform ${filePath}:`, error);
37
+ return {
38
+ code,
39
+ transformed: false
40
+ };
41
+ }
42
+ }
43
+
44
+ //#endregion
45
+ exports.transformComponent = transformComponent;