@weglot/translate-react 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +96 -9
  2. package/build/plugin/next.cjs +13 -2
  3. package/build/plugin/next.d.cts.map +1 -1
  4. package/build/plugin/next.d.mts.map +1 -1
  5. package/build/plugin/next.mjs +13 -2
  6. package/build/plugin/next.mjs.map +1 -1
  7. package/build/plugin/transform/index.cjs +17 -3
  8. package/build/plugin/transform/index.mjs +17 -3
  9. package/build/plugin/transform/index.mjs.map +1 -1
  10. package/build/plugin/transform/msg.cjs +66 -0
  11. package/build/plugin/transform/msg.mjs +64 -0
  12. package/build/plugin/transform/msg.mjs.map +1 -0
  13. package/build/plugin/transform/process-file.cjs +9 -7
  14. package/build/plugin/transform/process-file.mjs +9 -7
  15. package/build/plugin/transform/process-file.mjs.map +1 -1
  16. package/build/plugin/transform/utils.cjs +1 -0
  17. package/build/plugin/transform/utils.mjs +1 -1
  18. package/build/plugin/transform/utils.mjs.map +1 -1
  19. package/build/plugin/unplugin.cjs +3 -2
  20. package/build/plugin/unplugin.d.cts.map +1 -1
  21. package/build/plugin/unplugin.d.mts.map +1 -1
  22. package/build/plugin/unplugin.mjs +3 -2
  23. package/build/plugin/unplugin.mjs.map +1 -1
  24. package/build/react/client/index.cjs +2 -0
  25. package/build/react/client/index.d.cts +2 -1
  26. package/build/react/client/index.d.mts +2 -1
  27. package/build/react/client/index.mjs +2 -1
  28. package/build/react/client/useTranslation.cjs +14 -2
  29. package/build/react/client/useTranslation.d.cts +0 -35
  30. package/build/react/client/useTranslation.d.cts.map +1 -1
  31. package/build/react/client/useTranslation.d.mts +0 -35
  32. package/build/react/client/useTranslation.d.mts.map +1 -1
  33. package/build/react/client/useTranslation.mjs +15 -3
  34. package/build/react/client/useTranslation.mjs.map +1 -1
  35. package/build/react/server/ServerWeglotProvider.d.mts +2 -2
  36. package/build/react/server/index.cjs +2 -0
  37. package/build/react/server/index.d.cts +2 -1
  38. package/build/react/server/index.d.mts +2 -1
  39. package/build/react/server/index.mjs +2 -1
  40. package/build/react/server/useTranslation.cjs +6 -4
  41. package/build/react/server/useTranslation.d.cts.map +1 -1
  42. package/build/react/server/useTranslation.d.mts.map +1 -1
  43. package/build/react/server/useTranslation.mjs +6 -4
  44. package/build/react/server/useTranslation.mjs.map +1 -1
  45. package/build/react/server-only/index.cjs +5 -3
  46. package/build/react/server-only/index.d.cts +2 -3
  47. package/build/react/server-only/index.d.cts.map +1 -1
  48. package/build/react/server-only/index.d.mts +2 -3
  49. package/build/react/server-only/index.d.mts.map +1 -1
  50. package/build/react/server-only/index.mjs +5 -3
  51. package/build/react/server-only/index.mjs.map +1 -1
  52. package/build/react/server-only/translations.cjs +21 -1
  53. package/build/react/server-only/translations.mjs +22 -2
  54. package/build/react/server-only/translations.mjs.map +1 -1
  55. package/build/react/shared/LocaleSwitcher.d.mts +2 -2
  56. package/build/react/shared/WeglotContext.d.mts +1 -0
  57. package/build/react/shared/WeglotContext.d.mts.map +1 -1
  58. package/build/react/shared/WeglotProvider.d.mts +2 -2
  59. package/build/react/shared/msg.cjs +50 -0
  60. package/build/react/shared/msg.d.cts +26 -0
  61. package/build/react/shared/msg.d.cts.map +1 -0
  62. package/build/react/shared/msg.d.mts +26 -0
  63. package/build/react/shared/msg.d.mts.map +1 -0
  64. package/build/react/shared/msg.mjs +47 -0
  65. package/build/react/shared/msg.mjs.map +1 -0
  66. package/build/react/types.d.cts +7 -3
  67. package/build/react/types.d.cts.map +1 -1
  68. package/build/react/types.d.mts +7 -3
  69. package/build/react/types.d.mts.map +1 -1
  70. package/build/runtime/lru-cache.cjs +38 -0
  71. package/build/runtime/lru-cache.mjs +38 -0
  72. package/build/runtime/lru-cache.mjs.map +1 -0
  73. package/build/runtime/translate-dynamic.cjs +71 -17
  74. package/build/runtime/translate-dynamic.d.cts +2 -0
  75. package/build/runtime/translate-dynamic.d.cts.map +1 -1
  76. package/build/runtime/translate-dynamic.d.mts +2 -0
  77. package/build/runtime/translate-dynamic.d.mts.map +1 -1
  78. package/build/runtime/translate-dynamic.mjs +71 -17
  79. package/build/runtime/translate-dynamic.mjs.map +1 -1
  80. package/build/translators/weglot/api-client.cjs +4 -1
  81. package/build/translators/weglot/api-client.mjs +4 -1
  82. package/build/translators/weglot/api-client.mjs.map +1 -1
  83. package/package.json +1 -1
@@ -4,6 +4,7 @@ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
4
4
  const require_logger = require('../../utils/logger.cjs');
5
5
  const require_WeglotContext = require('../shared/WeglotContext.cjs');
6
6
  const require_render_rich_text = require('../shared/render-rich-text.cjs');
7
+ const require_msg = require('../shared/msg.cjs');
7
8
  let react = require("react");
8
9
 
9
10
  //#region src/react/client/useTranslation.ts
@@ -41,8 +42,10 @@ let react = require("react");
41
42
  * }
42
43
  * ```
43
44
  */
44
- const useTranslation = (hashes) => {
45
+ const NO_HASHES = [];
46
+ const useTranslation = (hashes = NO_HASHES) => {
45
47
  const { translations, registerHashes, locale, sourceLocale } = require_WeglotContext.useWeglotContext();
48
+ const messageHashes = (0, react.useRef)(/* @__PURE__ */ new Set());
46
49
  (0, react.useEffect)(() => {
47
50
  require_logger.logger.debug(`Registering ${hashes.length} hashes for component`);
48
51
  registerHashes(hashes);
@@ -52,8 +55,17 @@ const useTranslation = (hashes) => {
52
55
  locale,
53
56
  sourceLocale
54
57
  ]);
58
+ (0, react.useEffect)(() => {
59
+ if (messageHashes.current.size > 0) registerHashes([...messageHashes.current]);
60
+ });
55
61
  return {
56
- t: (0, react.useCallback)((hash, source, params) => {
62
+ t: (0, react.useCallback)((hashOrMessage, sourceOrParams, params) => {
63
+ if (require_msg.isMessageDescriptor(hashOrMessage)) {
64
+ if (hashOrMessage.hash) messageHashes.current.add(hashOrMessage.hash);
65
+ return require_msg.formatMessage(hashOrMessage, sourceOrParams, translations, locale);
66
+ }
67
+ const hash = hashOrMessage;
68
+ const source = sourceOrParams;
57
69
  require_logger.logger.debug(`Client. The translations for locale ${locale} are: ${JSON.stringify(translations)}`);
58
70
  const text = translations[hash] || source;
59
71
  if (!params) return text;
@@ -1,41 +1,6 @@
1
1
  import { TranslationHook } from "../types.cjs";
2
2
 
3
3
  //#region src/react/client/useTranslation.d.ts
4
-
5
- /**
6
- * useTranslation Hook
7
- *
8
- * Returns a translation function `t(hash, source, params?)` that:
9
- * - Returns original text for source locale
10
- * - Returns translated text for target locales
11
- * - Supports rich text with variable and component placeholders
12
- * - Automatically requests missing translations
13
- * - Falls back to source text while loading
14
- *
15
- * This hook is automatically injected by the Babel plugin.
16
- * You typically don't need to call it manually.
17
- *
18
- * @param hashes - Static list of all translation hashes used in this component (injected at build time)
19
- *
20
- * @example
21
- * ```tsx
22
- * 'use client';
23
- *
24
- * export function Welcome() {
25
- * const t = useTranslation(['hash_abc123', 'hash_def456']);
26
- *
27
- * return (
28
- * <div>
29
- * <h1>{t('hash_abc123', 'Welcome')}</h1>
30
- * <p>{t('hash_def456', 'Hello {name}', { name: 'Alice' })}</p>
31
- * <p>{t('hash_def789', 'Click <a0>here</a0>', {
32
- * a0: (chunks) => <a href="/home">{chunks}</a>
33
- * })}</p>
34
- * </div>
35
- * );
36
- * }
37
- * ```
38
- */
39
4
  declare const useTranslation: TranslationHook;
40
5
  //#endregion
41
6
  export { useTranslation };
@@ -1 +1 @@
1
- {"version":3,"file":"useTranslation.d.cts","names":[],"sources":["../../../src/react/client/useTranslation.ts"],"sourcesContent":[],"mappings":";;;;;;AA6CA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,gBAAgB"}
1
+ {"version":3,"file":"useTranslation.d.cts","names":[],"sources":["../../../src/react/client/useTranslation.ts"],"sourcesContent":[],"mappings":";;;cAqDa,gBAAgB"}
@@ -1,41 +1,6 @@
1
1
  import { TranslationHook } from "../types.mjs";
2
2
 
3
3
  //#region src/react/client/useTranslation.d.ts
4
-
5
- /**
6
- * useTranslation Hook
7
- *
8
- * Returns a translation function `t(hash, source, params?)` that:
9
- * - Returns original text for source locale
10
- * - Returns translated text for target locales
11
- * - Supports rich text with variable and component placeholders
12
- * - Automatically requests missing translations
13
- * - Falls back to source text while loading
14
- *
15
- * This hook is automatically injected by the Babel plugin.
16
- * You typically don't need to call it manually.
17
- *
18
- * @param hashes - Static list of all translation hashes used in this component (injected at build time)
19
- *
20
- * @example
21
- * ```tsx
22
- * 'use client';
23
- *
24
- * export function Welcome() {
25
- * const t = useTranslation(['hash_abc123', 'hash_def456']);
26
- *
27
- * return (
28
- * <div>
29
- * <h1>{t('hash_abc123', 'Welcome')}</h1>
30
- * <p>{t('hash_def456', 'Hello {name}', { name: 'Alice' })}</p>
31
- * <p>{t('hash_def789', 'Click <a0>here</a0>', {
32
- * a0: (chunks) => <a href="/home">{chunks}</a>
33
- * })}</p>
34
- * </div>
35
- * );
36
- * }
37
- * ```
38
- */
39
4
  declare const useTranslation: TranslationHook;
40
5
  //#endregion
41
6
  export { useTranslation };
@@ -1 +1 @@
1
- {"version":3,"file":"useTranslation.d.mts","names":[],"sources":["../../../src/react/client/useTranslation.ts"],"sourcesContent":[],"mappings":";;;;;;AA6CA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,gBAAgB"}
1
+ {"version":3,"file":"useTranslation.d.mts","names":[],"sources":["../../../src/react/client/useTranslation.ts"],"sourcesContent":[],"mappings":";;;cAqDa,gBAAgB"}
@@ -3,7 +3,8 @@
3
3
  import { logger } from "../../utils/logger.mjs";
4
4
  import { useWeglotContext } from "../shared/WeglotContext.mjs";
5
5
  import { renderRichText } from "../shared/render-rich-text.mjs";
6
- import { useCallback, useEffect } from "react";
6
+ import { formatMessage, isMessageDescriptor } from "../shared/msg.mjs";
7
+ import { useCallback, useEffect, useRef } from "react";
7
8
 
8
9
  //#region src/react/client/useTranslation.ts
9
10
  /**
@@ -40,8 +41,10 @@ import { useCallback, useEffect } from "react";
40
41
  * }
41
42
  * ```
42
43
  */
43
- const useTranslation = (hashes) => {
44
+ const NO_HASHES = [];
45
+ const useTranslation = (hashes = NO_HASHES) => {
44
46
  const { translations, registerHashes, locale, sourceLocale } = useWeglotContext();
47
+ const messageHashes = useRef(/* @__PURE__ */ new Set());
45
48
  useEffect(() => {
46
49
  logger.debug(`Registering ${hashes.length} hashes for component`);
47
50
  registerHashes(hashes);
@@ -51,8 +54,17 @@ const useTranslation = (hashes) => {
51
54
  locale,
52
55
  sourceLocale
53
56
  ]);
57
+ useEffect(() => {
58
+ if (messageHashes.current.size > 0) registerHashes([...messageHashes.current]);
59
+ });
54
60
  return {
55
- t: useCallback((hash, source, params) => {
61
+ t: useCallback((hashOrMessage, sourceOrParams, params) => {
62
+ if (isMessageDescriptor(hashOrMessage)) {
63
+ if (hashOrMessage.hash) messageHashes.current.add(hashOrMessage.hash);
64
+ return formatMessage(hashOrMessage, sourceOrParams, translations, locale);
65
+ }
66
+ const hash = hashOrMessage;
67
+ const source = sourceOrParams;
56
68
  logger.debug(`Client. The translations for locale ${locale} are: ${JSON.stringify(translations)}`);
57
69
  const text = translations[hash] || source;
58
70
  if (!params) return text;
@@ -1 +1 @@
1
- {"version":3,"file":"useTranslation.mjs","names":["useTranslation: TranslationHook"],"sources":["../../../src/react/client/useTranslation.ts"],"sourcesContent":["\"use client\";\n\nimport { type ReactNode, useCallback, useEffect } from \"react\";\nimport { logger } from \"../../utils/logger\";\nimport {\n renderRichText,\n type RichTextParams,\n} from \"../shared/render-rich-text\";\nimport type { TranslationHook } from \"../types\";\nimport { useWeglotContext } from \"../shared/WeglotContext\";\n\n/**\n * useTranslation Hook\n *\n * Returns a translation function `t(hash, source, params?)` that:\n * - Returns original text for source locale\n * - Returns translated text for target locales\n * - Supports rich text with variable and component placeholders\n * - Automatically requests missing translations\n * - Falls back to source text while loading\n *\n * This hook is automatically injected by the Babel plugin.\n * You typically don't need to call it manually.\n *\n * @param hashes - Static list of all translation hashes used in this component (injected at build time)\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * export function Welcome() {\n * const t = useTranslation(['hash_abc123', 'hash_def456']);\n *\n * return (\n * <div>\n * <h1>{t('hash_abc123', 'Welcome')}</h1>\n * <p>{t('hash_def456', 'Hello {name}', { name: 'Alice' })}</p>\n * <p>{t('hash_def789', 'Click <a0>here</a0>', {\n * a0: (chunks) => <a href=\"/home\">{chunks}</a>\n * })}</p>\n * </div>\n * );\n * }\n * ```\n */\nexport const useTranslation: TranslationHook = (hashes: string[]) => {\n const { translations, registerHashes, locale, sourceLocale } =\n useWeglotContext();\n\n useEffect(() => {\n logger.debug(`Registering ${hashes.length} hashes for component`);\n\n registerHashes(hashes);\n }, [hashes, registerHashes, locale, sourceLocale]);\n\n return {\n t: useCallback(\n (hash: string, source: string, params?: RichTextParams): ReactNode => {\n logger.debug(\n `Client. The translations for locale ${locale} are: ${JSON.stringify(translations)}`,\n );\n const text = translations[hash] || source;\n\n if (!params) {\n return text;\n }\n\n return renderRichText(text, params, locale);\n },\n [translations, locale, sourceLocale],\n ),\n locale,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAaA,kBAAmC,WAAqB;CACnE,MAAM,EAAE,cAAc,gBAAgB,QAAQ,iBAC5C,kBAAkB;AAEpB,iBAAgB;AACd,SAAO,MAAM,eAAe,OAAO,OAAO,uBAAuB;AAEjE,iBAAe,OAAO;IACrB;EAAC;EAAQ;EAAgB;EAAQ;EAAa,CAAC;AAElD,QAAO;EACL,GAAG,aACA,MAAc,QAAgB,WAAuC;AACpE,UAAO,MACL,uCAAuC,OAAO,QAAQ,KAAK,UAAU,aAAa,GACnF;GACD,MAAM,OAAO,aAAa,SAAS;AAEnC,OAAI,CAAC,OACH,QAAO;AAGT,UAAO,eAAe,MAAM,QAAQ,OAAO;KAE7C;GAAC;GAAc;GAAQ;GAAa,CACrC;EACD;EACD"}
1
+ {"version":3,"file":"useTranslation.mjs","names":["NO_HASHES: string[]","useTranslation: TranslationHook"],"sources":["../../../src/react/client/useTranslation.ts"],"sourcesContent":["\"use client\";\n\nimport { type ReactNode, useCallback, useEffect, useRef } from \"react\";\nimport { logger } from \"../../utils/logger\";\nimport {\n renderRichText,\n type RichTextParams,\n} from \"../shared/render-rich-text\";\nimport {\n formatMessage,\n isMessageDescriptor,\n type MessageDescriptor,\n type MessageValues,\n} from \"../shared/msg\";\nimport type { TranslationFunction, TranslationHook } from \"../types\";\nimport { useWeglotContext } from \"../shared/WeglotContext\";\n\n/**\n * useTranslation Hook\n *\n * Returns a translation function `t(hash, source, params?)` that:\n * - Returns original text for source locale\n * - Returns translated text for target locales\n * - Supports rich text with variable and component placeholders\n * - Automatically requests missing translations\n * - Falls back to source text while loading\n *\n * This hook is automatically injected by the Babel plugin.\n * You typically don't need to call it manually.\n *\n * @param hashes - Static list of all translation hashes used in this component (injected at build time)\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * export function Welcome() {\n * const t = useTranslation(['hash_abc123', 'hash_def456']);\n *\n * return (\n * <div>\n * <h1>{t('hash_abc123', 'Welcome')}</h1>\n * <p>{t('hash_def456', 'Hello {name}', { name: 'Alice' })}</p>\n * <p>{t('hash_def789', 'Click <a0>here</a0>', {\n * a0: (chunks) => <a href=\"/home\">{chunks}</a>\n * })}</p>\n * </div>\n * );\n * }\n * ```\n */\nconst NO_HASHES: string[] = [];\n\nexport const useTranslation: TranslationHook = (hashes = NO_HASHES) => {\n const { translations, registerHashes, locale, sourceLocale } =\n useWeglotContext();\n const messageHashes = useRef(new Set<string>());\n\n useEffect(() => {\n logger.debug(`Registering ${hashes.length} hashes for component`);\n\n registerHashes(hashes);\n }, [hashes, registerHashes, locale, sourceLocale]);\n\n // msg() hashes are only known once t() sees them during render.\n useEffect(() => {\n if (messageHashes.current.size > 0) {\n registerHashes([...messageHashes.current]);\n }\n });\n\n return {\n t: useCallback(\n (\n hashOrMessage: string | MessageDescriptor,\n sourceOrParams?: string | MessageValues,\n params?: RichTextParams,\n ): ReactNode => {\n if (isMessageDescriptor(hashOrMessage)) {\n if (hashOrMessage.hash) {\n messageHashes.current.add(hashOrMessage.hash);\n }\n return formatMessage(\n hashOrMessage,\n sourceOrParams as MessageValues | undefined,\n translations,\n locale,\n );\n }\n\n const hash = hashOrMessage;\n const source = sourceOrParams as string;\n logger.debug(\n `Client. The translations for locale ${locale} are: ${JSON.stringify(translations)}`,\n );\n const text = translations[hash] || source;\n\n if (!params) {\n return text;\n }\n\n return renderRichText(text, params, locale);\n },\n [translations, locale, sourceLocale],\n ) as TranslationFunction,\n locale,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAMA,YAAsB,EAAE;AAE9B,MAAaC,kBAAmC,SAAS,cAAc;CACrE,MAAM,EAAE,cAAc,gBAAgB,QAAQ,iBAC5C,kBAAkB;CACpB,MAAM,gBAAgB,uBAAO,IAAI,KAAa,CAAC;AAE/C,iBAAgB;AACd,SAAO,MAAM,eAAe,OAAO,OAAO,uBAAuB;AAEjE,iBAAe,OAAO;IACrB;EAAC;EAAQ;EAAgB;EAAQ;EAAa,CAAC;AAGlD,iBAAgB;AACd,MAAI,cAAc,QAAQ,OAAO,EAC/B,gBAAe,CAAC,GAAG,cAAc,QAAQ,CAAC;GAE5C;AAEF,QAAO;EACL,GAAG,aAEC,eACA,gBACA,WACc;AACd,OAAI,oBAAoB,cAAc,EAAE;AACtC,QAAI,cAAc,KAChB,eAAc,QAAQ,IAAI,cAAc,KAAK;AAE/C,WAAO,cACL,eACA,gBACA,cACA,OACD;;GAGH,MAAM,OAAO;GACb,MAAM,SAAS;AACf,UAAO,MACL,uCAAuC,OAAO,QAAQ,KAAK,UAAU,aAAa,GACnF;GACD,MAAM,OAAO,aAAa,SAAS;AAEnC,OAAI,CAAC,OACH,QAAO;AAGT,UAAO,eAAe,MAAM,QAAQ,OAAO;KAE7C;GAAC;GAAc;GAAQ;GAAa,CACrC;EACD;EACD"}
@@ -1,12 +1,12 @@
1
1
  import { WeglotProviderProps } from "../shared/WeglotProvider.mjs";
2
- import * as react_jsx_runtime3 from "react/jsx-runtime";
2
+ import * as react_jsx_runtime2 from "react/jsx-runtime";
3
3
 
4
4
  //#region src/react/server/ServerWeglotProvider.d.ts
5
5
  declare function WeglotProvider({
6
6
  initialLocale,
7
7
  initialTranslations,
8
8
  ...rest
9
- }: WeglotProviderProps): Promise<react_jsx_runtime3.JSX.Element>;
9
+ }: WeglotProviderProps): Promise<react_jsx_runtime2.JSX.Element>;
10
10
  //#endregion
11
11
  export { WeglotProvider };
12
12
  //# sourceMappingURL=ServerWeglotProvider.d.mts.map
@@ -1,7 +1,9 @@
1
+ const require_msg = require('../shared/msg.cjs');
1
2
  const require_ServerWeglotProvider = require('./ServerWeglotProvider.cjs');
2
3
  const require_LocaleSwitcher = require('../shared/LocaleSwitcher.cjs');
3
4
  const require_useTranslation = require('./useTranslation.cjs');
4
5
 
5
6
  exports.LocaleSwitcher = require_LocaleSwitcher.LocaleSwitcher;
6
7
  exports.WeglotProvider = require_ServerWeglotProvider.WeglotProvider;
8
+ exports.msg = require_msg.msg;
7
9
  exports.useTranslation = require_useTranslation.useTranslation;
@@ -1,4 +1,5 @@
1
+ import { MessageDescriptor, MessageValues, msg } from "../shared/msg.cjs";
1
2
  import { LocaleSwitcher } from "../shared/LocaleSwitcher.cjs";
2
3
  import { WeglotProvider } from "./ServerWeglotProvider.cjs";
3
4
  import { useTranslation } from "./useTranslation.cjs";
4
- export { LocaleSwitcher, WeglotProvider, useTranslation };
5
+ export { LocaleSwitcher, type MessageDescriptor, type MessageValues, WeglotProvider, msg, useTranslation };
@@ -1,4 +1,5 @@
1
+ import { MessageDescriptor, MessageValues, msg } from "../shared/msg.mjs";
1
2
  import { LocaleSwitcher } from "../shared/LocaleSwitcher.mjs";
2
3
  import { WeglotProvider } from "./ServerWeglotProvider.mjs";
3
4
  import { useTranslation } from "./useTranslation.mjs";
4
- export { LocaleSwitcher, WeglotProvider, useTranslation };
5
+ export { LocaleSwitcher, type MessageDescriptor, type MessageValues, WeglotProvider, msg, useTranslation };
@@ -1,5 +1,6 @@
1
+ import { msg } from "../shared/msg.mjs";
1
2
  import { WeglotProvider } from "./ServerWeglotProvider.mjs";
2
3
  import { LocaleSwitcher } from "../shared/LocaleSwitcher.mjs";
3
4
  import { useTranslation } from "./useTranslation.mjs";
4
5
 
5
- export { LocaleSwitcher, WeglotProvider, useTranslation };
6
+ export { LocaleSwitcher, WeglotProvider, msg, useTranslation };
@@ -2,6 +2,7 @@ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
2
  const require_logger = require('../../utils/logger.cjs');
3
3
  const require_translations = require('../server-only/translations.cjs');
4
4
  const require_render_rich_text = require('../shared/render-rich-text.cjs');
5
+ const require_msg = require('../shared/msg.cjs');
5
6
  let react = require("react");
6
7
  let _weglot_translate_react_virtual_locale_server = require("@weglot/translate-react/virtual/locale/server");
7
8
 
@@ -43,15 +44,16 @@ const getTranslations = async (hashes) => {
43
44
  * }
44
45
  * ```
45
46
  */
46
- const useTranslation = (hashes) => {
47
+ const useTranslation = (hashes = []) => {
47
48
  const { locale, translations } = (0, react.use)(getTranslations(hashes));
48
49
  require_logger.logger.debug(`Server. The translations for locale ${locale} are: ${JSON.stringify(translations)}`);
49
50
  return {
50
- t: (hash, source, params) => {
51
- const text = translations[hash] || source;
51
+ t: ((hashOrMessage, sourceOrParams, params) => {
52
+ if (require_msg.isMessageDescriptor(hashOrMessage)) return require_msg.formatMessage(hashOrMessage, sourceOrParams, translations, locale);
53
+ const text = translations[hashOrMessage] || sourceOrParams;
52
54
  if (!params) return text;
53
55
  return require_render_rich_text.renderRichText(text, params, locale);
54
- },
56
+ }),
55
57
  locale
56
58
  };
57
59
  };
@@ -1 +1 @@
1
- {"version":3,"file":"useTranslation.d.cts","names":[],"sources":["../../../src/react/server/useTranslation.ts"],"sourcesContent":[],"mappings":";;;;;;AAyDA;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,gBAAgB"}
1
+ {"version":3,"file":"useTranslation.d.cts","names":[],"sources":["../../../src/react/server/useTranslation.ts"],"sourcesContent":[],"mappings":";;;;;;AA+DA;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,gBAAgB"}
@@ -1 +1 @@
1
- {"version":3,"file":"useTranslation.d.mts","names":[],"sources":["../../../src/react/server/useTranslation.ts"],"sourcesContent":[],"mappings":";;;;;;AAyDA;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,gBAAgB"}
1
+ {"version":3,"file":"useTranslation.d.mts","names":[],"sources":["../../../src/react/server/useTranslation.ts"],"sourcesContent":[],"mappings":";;;;;;AA+DA;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,gBAAgB"}
@@ -1,6 +1,7 @@
1
1
  import { logger } from "../../utils/logger.mjs";
2
2
  import { fetchTranslationsOnServer } from "../server-only/translations.mjs";
3
3
  import { renderRichText } from "../shared/render-rich-text.mjs";
4
+ import { formatMessage, isMessageDescriptor } from "../shared/msg.mjs";
4
5
  import { use } from "react";
5
6
  import { getServerLocale } from "@weglot/translate-react/virtual/locale/server";
6
7
 
@@ -42,15 +43,16 @@ const getTranslations = async (hashes) => {
42
43
  * }
43
44
  * ```
44
45
  */
45
- const useTranslation = (hashes) => {
46
+ const useTranslation = (hashes = []) => {
46
47
  const { locale, translations } = use(getTranslations(hashes));
47
48
  logger.debug(`Server. The translations for locale ${locale} are: ${JSON.stringify(translations)}`);
48
49
  return {
49
- t: (hash, source, params) => {
50
- const text = translations[hash] || source;
50
+ t: ((hashOrMessage, sourceOrParams, params) => {
51
+ if (isMessageDescriptor(hashOrMessage)) return formatMessage(hashOrMessage, sourceOrParams, translations, locale);
52
+ const text = translations[hashOrMessage] || sourceOrParams;
51
53
  if (!params) return text;
52
54
  return renderRichText(text, params, locale);
53
- },
55
+ }),
54
56
  locale
55
57
  };
56
58
  };
@@ -1 +1 @@
1
- {"version":3,"file":"useTranslation.mjs","names":["useTranslation: TranslationHook"],"sources":["../../../src/react/server/useTranslation.ts"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport { use } from \"react\";\nimport { getServerLocale } from \"@weglot/translate-react/virtual/locale/server\";\nimport { fetchTranslationsOnServer } from \"../server-only/translations\";\nimport {\n renderRichText,\n type RichTextParams,\n} from \"../shared/render-rich-text\";\nimport { logger } from \"../../utils/logger\";\nimport type { TranslationHook } from \"../types\";\n\n// TODO (AleksandrSl 01/12/2025): Should we add back the cache?\nconst getTranslations = async (hashes: string[]) => {\n // 1. Resolve locale (framework-specific)\n const locale = await getServerLocale();\n\n // 2. Fetch translations (universal)\n const translations = await fetchTranslationsOnServer(locale, hashes);\n\n logger.debug(\n `Server. The translations for locale ${locale} are: ${JSON.stringify(translations)}`,\n );\n\n return {\n locale,\n translations,\n };\n};\n\n/**\n * Server-side translation hook\n *\n * Works in Server Components WITHOUT async/await!\n * Uses React's use() hook to unwrap the cached promise.\n *\n * This hook has the SAME signature as the client-side version,\n * making components truly isomorphic.\n *\n * @param hashes - List of translation hashes used in component (injected by compiler)\n * @returns Translation function\n *\n * @example\n * ```tsx\n * // Works in Server Components (no async needed!)\n * export default function ServerPage() {\n * const t = useTranslation(['hash_abc', 'hash_def']);\n * return <h1>{t('hash_abc', 'Welcome')}</h1>;\n * }\n *\n * // Also works in Client Components (via conditional exports)\n * 'use client';\n * export default function ClientPage() {\n * const t = useTranslation(['hash_abc', 'hash_def']);\n * return <h1>{t('hash_abc', 'Welcome')}</h1>;\n * }\n * ```\n */\nexport const useTranslation: TranslationHook = (hashes: string[]) => {\n const { locale, translations } = use(getTranslations(hashes));\n logger.debug(\n `Server. The translations for locale ${locale} are: ${JSON.stringify(translations)}`,\n );\n\n return {\n t: (\n hash: string,\n source: string,\n params?: RichTextParams,\n ): string | ReactNode => {\n const text = translations[hash] || source;\n\n if (!params) {\n return text;\n }\n\n return renderRichText(text, params, locale);\n },\n locale,\n };\n};\n"],"mappings":";;;;;;;AAYA,MAAM,kBAAkB,OAAO,WAAqB;CAElD,MAAM,SAAS,MAAM,iBAAiB;CAGtC,MAAM,eAAe,MAAM,0BAA0B,QAAQ,OAAO;AAEpE,QAAO,MACL,uCAAuC,OAAO,QAAQ,KAAK,UAAU,aAAa,GACnF;AAED,QAAO;EACL;EACA;EACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BH,MAAaA,kBAAmC,WAAqB;CACnE,MAAM,EAAE,QAAQ,iBAAiB,IAAI,gBAAgB,OAAO,CAAC;AAC7D,QAAO,MACL,uCAAuC,OAAO,QAAQ,KAAK,UAAU,aAAa,GACnF;AAED,QAAO;EACL,IACE,MACA,QACA,WACuB;GACvB,MAAM,OAAO,aAAa,SAAS;AAEnC,OAAI,CAAC,OACH,QAAO;AAGT,UAAO,eAAe,MAAM,QAAQ,OAAO;;EAE7C;EACD"}
1
+ {"version":3,"file":"useTranslation.mjs","names":["useTranslation: TranslationHook"],"sources":["../../../src/react/server/useTranslation.ts"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport { use } from \"react\";\nimport { getServerLocale } from \"@weglot/translate-react/virtual/locale/server\";\nimport { fetchTranslationsOnServer } from \"../server-only/translations\";\nimport {\n renderRichText,\n type RichTextParams,\n} from \"../shared/render-rich-text\";\nimport { logger } from \"../../utils/logger\";\nimport {\n formatMessage,\n isMessageDescriptor,\n type MessageDescriptor,\n type MessageValues,\n} from \"../shared/msg\";\nimport type { TranslationFunction, TranslationHook } from \"../types\";\n\n// TODO (AleksandrSl 01/12/2025): Should we add back the cache?\nconst getTranslations = async (hashes: string[]) => {\n // 1. Resolve locale (framework-specific)\n const locale = await getServerLocale();\n\n // 2. Fetch translations (universal)\n const translations = await fetchTranslationsOnServer(locale, hashes);\n\n logger.debug(\n `Server. The translations for locale ${locale} are: ${JSON.stringify(translations)}`,\n );\n\n return {\n locale,\n translations,\n };\n};\n\n/**\n * Server-side translation hook\n *\n * Works in Server Components WITHOUT async/await!\n * Uses React's use() hook to unwrap the cached promise.\n *\n * This hook has the SAME signature as the client-side version,\n * making components truly isomorphic.\n *\n * @param hashes - List of translation hashes used in component (injected by compiler)\n * @returns Translation function\n *\n * @example\n * ```tsx\n * // Works in Server Components (no async needed!)\n * export default function ServerPage() {\n * const t = useTranslation(['hash_abc', 'hash_def']);\n * return <h1>{t('hash_abc', 'Welcome')}</h1>;\n * }\n *\n * // Also works in Client Components (via conditional exports)\n * 'use client';\n * export default function ClientPage() {\n * const t = useTranslation(['hash_abc', 'hash_def']);\n * return <h1>{t('hash_abc', 'Welcome')}</h1>;\n * }\n * ```\n */\nexport const useTranslation: TranslationHook = (hashes = []) => {\n const { locale, translations } = use(getTranslations(hashes));\n logger.debug(\n `Server. The translations for locale ${locale} are: ${JSON.stringify(translations)}`,\n );\n\n return {\n t: ((\n hashOrMessage: string | MessageDescriptor,\n sourceOrParams?: string | MessageValues,\n params?: RichTextParams,\n ): string | ReactNode => {\n if (isMessageDescriptor(hashOrMessage)) {\n return formatMessage(\n hashOrMessage,\n sourceOrParams as MessageValues | undefined,\n translations,\n locale,\n );\n }\n\n const text = translations[hashOrMessage] || (sourceOrParams as string);\n\n if (!params) {\n return text;\n }\n\n return renderRichText(text, params, locale);\n }) as TranslationFunction,\n locale,\n };\n};\n"],"mappings":";;;;;;;;AAkBA,MAAM,kBAAkB,OAAO,WAAqB;CAElD,MAAM,SAAS,MAAM,iBAAiB;CAGtC,MAAM,eAAe,MAAM,0BAA0B,QAAQ,OAAO;AAEpE,QAAO,MACL,uCAAuC,OAAO,QAAQ,KAAK,UAAU,aAAa,GACnF;AAED,QAAO;EACL;EACA;EACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BH,MAAaA,kBAAmC,SAAS,EAAE,KAAK;CAC9D,MAAM,EAAE,QAAQ,iBAAiB,IAAI,gBAAgB,OAAO,CAAC;AAC7D,QAAO,MACL,uCAAuC,OAAO,QAAQ,KAAK,UAAU,aAAa,GACnF;AAED,QAAO;EACL,KACE,eACA,gBACA,WACuB;AACvB,OAAI,oBAAoB,cAAc,CACpC,QAAO,cACL,eACA,gBACA,cACA,OACD;GAGH,MAAM,OAAO,aAAa,kBAAmB;AAE7C,OAAI,CAAC,OACH,QAAO;AAGT,UAAO,eAAe,MAAM,QAAQ,OAAO;;EAE7C;EACD"}
@@ -2,6 +2,7 @@ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
2
  const require_logger = require('../../utils/logger.cjs');
3
3
  const require_translations = require('./translations.cjs');
4
4
  const require_render_rich_text = require('../shared/render-rich-text.cjs');
5
+ const require_msg = require('../shared/msg.cjs');
5
6
  let _weglot_translate_react_virtual_locale_server = require("@weglot/translate-react/virtual/locale/server");
6
7
 
7
8
  //#region src/react/server-only/index.ts
@@ -28,11 +29,12 @@ async function getServerTranslations(options) {
28
29
  require_logger.logger.debug(`Async Server. Fetching translations for ${locale}`);
29
30
  const translations = await require_translations.fetchTranslationsOnServer(locale, options.hashes ?? [], { basePath: options.basePath });
30
31
  return {
31
- t: (hash, sourceText, params) => {
32
- const text = translations[hash] || sourceText;
32
+ t: ((hashOrMessage, sourceOrParams, params) => {
33
+ if (require_msg.isMessageDescriptor(hashOrMessage)) return require_msg.formatMessage(hashOrMessage, sourceOrParams, translations, locale);
34
+ const text = translations[hashOrMessage] || sourceOrParams;
33
35
  if (!params) return text;
34
36
  return require_render_rich_text.renderRichText(text, params, locale);
35
- },
37
+ }),
36
38
  locale,
37
39
  translations
38
40
  };
@@ -1,6 +1,5 @@
1
1
  import { LocaleCode } from "../../locale.cjs";
2
- import { RichTextParams } from "../shared/render-rich-text.cjs";
3
- import { ReactNode } from "react";
2
+ import { TranslationFunction } from "../types.cjs";
4
3
 
5
4
  //#region src/react/server-only/index.d.ts
6
5
 
@@ -29,7 +28,7 @@ declare function getServerTranslations(options: {
29
28
  */
30
29
  basePath?: string;
31
30
  }): Promise<{
32
- t: (hash: string, sourceText: string, params?: RichTextParams) => string | ReactNode;
31
+ t: TranslationFunction;
33
32
  locale: LocaleCode;
34
33
  translations: Record<string, string>;
35
34
  }>;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/react/server-only/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;iBA8BsB,qBAAA;;;;WAIX;;;;;;;;;;;IAaP;iDAIS,4BACG;UACN;gBACM"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/react/server-only/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;iBAqCsB,qBAAA;;;;WAIX;;;;;;;;;;;IAaP;KACC;UACK;gBACM"}
@@ -1,6 +1,5 @@
1
1
  import { LocaleCode } from "../../locale.mjs";
2
- import { RichTextParams } from "../shared/render-rich-text.mjs";
3
- import { ReactNode } from "react";
2
+ import { TranslationFunction } from "../types.mjs";
4
3
 
5
4
  //#region src/react/server-only/index.d.ts
6
5
 
@@ -29,7 +28,7 @@ declare function getServerTranslations(options: {
29
28
  */
30
29
  basePath?: string;
31
30
  }): Promise<{
32
- t: (hash: string, sourceText: string, params?: RichTextParams) => string | ReactNode;
31
+ t: TranslationFunction;
33
32
  locale: LocaleCode;
34
33
  translations: Record<string, string>;
35
34
  }>;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/react/server-only/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;iBA8BsB,qBAAA;;;;WAIX;;;;;;;;;;;IAaP;iDAIS,4BACG;UACN;gBACM"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/react/server-only/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;iBAqCsB,qBAAA;;;;WAIX;;;;;;;;;;;IAaP;KACC;UACK;gBACM"}
@@ -1,6 +1,7 @@
1
1
  import { logger } from "../../utils/logger.mjs";
2
2
  import { fetchTranslationsOnServer } from "./translations.mjs";
3
3
  import { renderRichText } from "../shared/render-rich-text.mjs";
4
+ import { formatMessage, isMessageDescriptor } from "../shared/msg.mjs";
4
5
  import { getServerLocale } from "@weglot/translate-react/virtual/locale/server";
5
6
 
6
7
  //#region src/react/server-only/index.ts
@@ -27,11 +28,12 @@ async function getServerTranslations(options) {
27
28
  logger.debug(`Async Server. Fetching translations for ${locale}`);
28
29
  const translations = await fetchTranslationsOnServer(locale, options.hashes ?? [], { basePath: options.basePath });
29
30
  return {
30
- t: (hash, sourceText, params) => {
31
- const text = translations[hash] || sourceText;
31
+ t: ((hashOrMessage, sourceOrParams, params) => {
32
+ if (isMessageDescriptor(hashOrMessage)) return formatMessage(hashOrMessage, sourceOrParams, translations, locale);
33
+ const text = translations[hashOrMessage] || sourceOrParams;
32
34
  if (!params) return text;
33
35
  return renderRichText(text, params, locale);
34
- },
36
+ }),
35
37
  locale,
36
38
  translations
37
39
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/react/server-only/index.ts"],"sourcesContent":["/**\n * Server-side translation utilities for React Server Components\n * Provides async API for explicit locale passing\n *\n * NOTE: For most cases, use the unified `useTranslation()` hook instead.\n * This module is for advanced use cases where you need explicit control.\n *\n * @module @weglot/translate-react/react/server\n */\n\nimport { fetchTranslationsOnServer } from \"./translations\";\nimport {\n renderRichText,\n type RichTextParams,\n} from \"../shared/render-rich-text\";\nimport type { ReactNode } from \"react\";\nimport { logger } from \"../../utils/logger\";\n// Keep this import full for replacement during build.\nimport { getServerLocale } from \"@weglot/translate-react/virtual/locale/server\";\nimport type { LocaleCode } from \"../../locale\";\n\n/**\n * Get server-side translations function\n * This is the async alternative to useTranslation() for Server Components\n *\n * For the most common use case, use the unified `useTranslation()` hook instead.\n *\n * The function automatically fetches translations from static files in production\n * and falls back to the development server in development mode.\n */\nexport async function getServerTranslations(options: {\n /**\n * Target locale for translations (required)\n */\n locale?: LocaleCode;\n\n /**\n * List of translation hashes needed for this component\n * Typically injected at build time by the Babel plugin\n */\n hashes?: string[];\n\n /**\n * Base path for translation files\n * @default process.cwd()\n */\n basePath?: string;\n}): Promise<{\n t: (\n hash: string,\n sourceText: string,\n params?: RichTextParams,\n ) => string | ReactNode;\n locale: LocaleCode;\n translations: Record<string, string>;\n}> {\n const locale = options.locale || (await getServerLocale());\n\n logger.debug(`Async Server. Fetching translations for ${locale}`);\n\n const translations = await fetchTranslationsOnServer(\n locale,\n options.hashes ?? [],\n {\n basePath: options.basePath,\n },\n );\n\n return {\n t: (hash: string, sourceText: string, params?: RichTextParams) => {\n const text = translations[hash] || sourceText;\n\n if (!params) {\n return text;\n }\n\n return renderRichText(text, params, locale);\n },\n locale,\n translations,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA8BA,eAAsB,sBAAsB,SAyBzC;CACD,MAAM,SAAS,QAAQ,UAAW,MAAM,iBAAiB;AAEzD,QAAO,MAAM,2CAA2C,SAAS;CAEjE,MAAM,eAAe,MAAM,0BACzB,QACA,QAAQ,UAAU,EAAE,EACpB,EACE,UAAU,QAAQ,UACnB,CACF;AAED,QAAO;EACL,IAAI,MAAc,YAAoB,WAA4B;GAChE,MAAM,OAAO,aAAa,SAAS;AAEnC,OAAI,CAAC,OACH,QAAO;AAGT,UAAO,eAAe,MAAM,QAAQ,OAAO;;EAE7C;EACA;EACD"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/react/server-only/index.ts"],"sourcesContent":["/**\n * Server-side translation utilities for React Server Components\n * Provides async API for explicit locale passing\n *\n * NOTE: For most cases, use the unified `useTranslation()` hook instead.\n * This module is for advanced use cases where you need explicit control.\n *\n * @module @weglot/translate-react/react/server\n */\n\nimport { fetchTranslationsOnServer } from \"./translations\";\nimport {\n renderRichText,\n type RichTextParams,\n} from \"../shared/render-rich-text\";\nimport type { ReactNode } from \"react\";\nimport { logger } from \"../../utils/logger\";\n// Keep this import full for replacement during build.\nimport { getServerLocale } from \"@weglot/translate-react/virtual/locale/server\";\nimport type { LocaleCode } from \"../../locale\";\nimport {\n formatMessage,\n isMessageDescriptor,\n type MessageDescriptor,\n type MessageValues,\n} from \"../shared/msg\";\nimport type { TranslationFunction } from \"../types\";\n\n/**\n * Get server-side translations function\n * This is the async alternative to useTranslation() for Server Components\n *\n * For the most common use case, use the unified `useTranslation()` hook instead.\n *\n * The function automatically fetches translations from static files in production\n * and falls back to the development server in development mode.\n */\nexport async function getServerTranslations(options: {\n /**\n * Target locale for translations (required)\n */\n locale?: LocaleCode;\n\n /**\n * List of translation hashes needed for this component\n * Typically injected at build time by the Babel plugin\n */\n hashes?: string[];\n\n /**\n * Base path for translation files\n * @default process.cwd()\n */\n basePath?: string;\n}): Promise<{\n t: TranslationFunction;\n locale: LocaleCode;\n translations: Record<string, string>;\n}> {\n const locale = options.locale || (await getServerLocale());\n\n logger.debug(`Async Server. Fetching translations for ${locale}`);\n\n const translations = await fetchTranslationsOnServer(\n locale,\n options.hashes ?? [],\n {\n basePath: options.basePath,\n },\n );\n\n return {\n t: ((\n hashOrMessage: string | MessageDescriptor,\n sourceOrParams?: string | MessageValues,\n params?: RichTextParams,\n ): string | ReactNode => {\n if (isMessageDescriptor(hashOrMessage)) {\n return formatMessage(\n hashOrMessage,\n sourceOrParams as MessageValues | undefined,\n translations,\n locale,\n );\n }\n\n const text = translations[hashOrMessage] || (sourceOrParams as string);\n\n if (!params) {\n return text;\n }\n\n return renderRichText(text, params, locale);\n }) as TranslationFunction,\n locale,\n translations,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,eAAsB,sBAAsB,SAqBzC;CACD,MAAM,SAAS,QAAQ,UAAW,MAAM,iBAAiB;AAEzD,QAAO,MAAM,2CAA2C,SAAS;CAEjE,MAAM,eAAe,MAAM,0BACzB,QACA,QAAQ,UAAU,EAAE,EACpB,EACE,UAAU,QAAQ,UACnB,CACF;AAED,QAAO;EACL,KACE,eACA,gBACA,WACuB;AACvB,OAAI,oBAAoB,cAAc,CACpC,QAAO,cACL,eACA,gBACA,cACA,OACD;GAGH,MAAM,OAAO,aAAa,kBAAmB;AAE7C,OAAI,CAAC,OACH,QAAO;AAGT,UAAO,eAAe,MAAM,QAAQ,OAAO;;EAE7C;EACA;EACD"}
@@ -69,7 +69,8 @@ async function readFromFilesystem(locale, basePath = process.cwd()) {
69
69
  * ```
70
70
  */
71
71
  async function fetchTranslationsOnServer(locale, hashes, config = {}) {
72
- if (process.env.NODE_ENV === "development" && _weglot_translate_react_virtual_config.serverUrl && hashes.length > 0) {
72
+ const isDev = process.env.NODE_ENV === "development";
73
+ if (isDev && _weglot_translate_react_virtual_config.serverUrl && hashes.length > 0) {
73
74
  require_logger.logger.debug(`Server. Fetching translations for ${locale} and ${hashes.join(", ")} from dev server (${_weglot_translate_react_virtual_config.serverUrl})`);
74
75
  try {
75
76
  return await require_utils.fetchTranslations(locale, hashes, _weglot_translate_react_virtual_config.serverUrl);
@@ -78,9 +79,28 @@ async function fetchTranslationsOnServer(locale, hashes, config = {}) {
78
79
  return {};
79
80
  }
80
81
  }
82
+ if (isDev && _weglot_translate_react_virtual_config.serverUrl && locale !== _weglot_translate_react_virtual_config.sourceLocale) try {
83
+ return await fetchDictionaryFromDevServer(locale, _weglot_translate_react_virtual_config.serverUrl);
84
+ } catch (error) {
85
+ require_logger.logger.warn(`Failed to fetch the ${locale} dictionary from translation server: ${error}.`);
86
+ }
81
87
  require_logger.logger.debug(`Reading translations for ${locale} from filesystem`);
82
88
  return await readFromFilesystem(locale, config.basePath);
83
89
  }
90
+ async function fetchDictionaryFromDevServer(locale, url) {
91
+ const controller = new AbortController();
92
+ const timeoutId = setTimeout(() => controller.abort(), 3e4);
93
+ try {
94
+ const response = await fetch(`${url}/translations/${locale}`, {
95
+ cache: "no-store",
96
+ signal: controller.signal
97
+ });
98
+ if (!response.ok) throw new Error(`Translation server error: ${response.statusText}`);
99
+ return (await response.json()).translations || {};
100
+ } finally {
101
+ clearTimeout(timeoutId);
102
+ }
103
+ }
84
104
 
85
105
  //#endregion
86
106
  exports.fetchTranslationsOnServer = fetchTranslationsOnServer;
@@ -1,6 +1,6 @@
1
1
  import { logger } from "../../utils/logger.mjs";
2
2
  import { fetchTranslations } from "../shared/utils.mjs";
3
- import { cacheDir, serverUrl } from "@weglot/translate-react/virtual/config";
3
+ import { cacheDir, serverUrl, sourceLocale } from "@weglot/translate-react/virtual/config";
4
4
  import { readFile } from "fs/promises";
5
5
  import { isAbsolute, join } from "path";
6
6
 
@@ -68,7 +68,8 @@ async function readFromFilesystem(locale, basePath = process.cwd()) {
68
68
  * ```
69
69
  */
70
70
  async function fetchTranslationsOnServer(locale, hashes, config = {}) {
71
- if (process.env.NODE_ENV === "development" && serverUrl && hashes.length > 0) {
71
+ const isDev = process.env.NODE_ENV === "development";
72
+ if (isDev && serverUrl && hashes.length > 0) {
72
73
  logger.debug(`Server. Fetching translations for ${locale} and ${hashes.join(", ")} from dev server (${serverUrl})`);
73
74
  try {
74
75
  return await fetchTranslations(locale, hashes, serverUrl);
@@ -77,9 +78,28 @@ async function fetchTranslationsOnServer(locale, hashes, config = {}) {
77
78
  return {};
78
79
  }
79
80
  }
81
+ if (isDev && serverUrl && locale !== sourceLocale) try {
82
+ return await fetchDictionaryFromDevServer(locale, serverUrl);
83
+ } catch (error) {
84
+ logger.warn(`Failed to fetch the ${locale} dictionary from translation server: ${error}.`);
85
+ }
80
86
  logger.debug(`Reading translations for ${locale} from filesystem`);
81
87
  return await readFromFilesystem(locale, config.basePath);
82
88
  }
89
+ async function fetchDictionaryFromDevServer(locale, url) {
90
+ const controller = new AbortController();
91
+ const timeoutId = setTimeout(() => controller.abort(), 3e4);
92
+ try {
93
+ const response = await fetch(`${url}/translations/${locale}`, {
94
+ cache: "no-store",
95
+ signal: controller.signal
96
+ });
97
+ if (!response.ok) throw new Error(`Translation server error: ${response.statusText}`);
98
+ return (await response.json()).translations || {};
99
+ } finally {
100
+ clearTimeout(timeoutId);
101
+ }
102
+ }
83
103
 
84
104
  //#endregion
85
105
  export { fetchTranslationsOnServer };
@@ -1 +1 @@
1
- {"version":3,"file":"translations.mjs","names":["fetchFromDevServer"],"sources":["../../../src/react/server-only/translations.ts"],"sourcesContent":["/**\n * Core translation service - framework-agnostic\n * Handles fetching translations from dev server or filesystem\n *\n * This is the UNIVERSAL pattern that works across all frameworks:\n * Given a locale, fetch the translation dictionary for that locale.\n *\n * @module @weglot/translate-react/react/server/translations\n */\n\nimport { readFile } from \"fs/promises\";\nimport { isAbsolute, join } from \"path\";\nimport { logger } from \"../../utils/logger\";\nimport { fetchTranslations as fetchFromDevServer } from \"../shared/utils\";\nimport { cacheDir, serverUrl } from \"@weglot/translate-react/virtual/config\";\nimport type { LocaleCode } from \"../../locale\";\n\n/**\n * Configuration for translation fetching\n */\nexport interface TranslationFetchConfig {\n /**\n * Base path for translation files (default: process.cwd())\n */\n basePath?: string;\n}\n\n/**\n * Read translations from filesystem\n * Used in production builds or as fallback in development\n *\n * Tries multiple common locations for translation files:\n * - weglot/cache/{locale}.json (dev cache)\n * - .next/{locale}.json (Next.js)\n *\n * @param locale - Target locale\n * @param basePath - Base directory to search from (default: cwd)\n * @returns Translation dictionary (hash -> translated text)\n */\nasync function readFromFilesystem(\n locale: LocaleCode,\n basePath: string = process.cwd(),\n): Promise<Record<string, string>> {\n // TODO (AleksandrSl 15/12/2025): What should be the correct way here to load translations on server for other frameworks?\n // Build output is authoritative: the dev cache must never stand in for it.\n const possiblePaths = [join(basePath, \".next\", `${locale}.json`)];\n\n if (process.env.NODE_ENV === \"development\") {\n // cacheDir is emitted absolute, and join() would append it to basePath.\n possiblePaths.push(\n isAbsolute(cacheDir)\n ? join(cacheDir, `${locale}.json`)\n : join(basePath, cacheDir, `${locale}.json`),\n );\n }\n\n // Try each path until we find the file\n for (const filePath of possiblePaths) {\n try {\n const fileContent = await readFile(filePath, \"utf-8\");\n const data = JSON.parse(fileContent);\n const translations = data.entries || {};\n\n logger.debug(\n `Loaded ${Object.keys(translations).length} translations from ${filePath}`,\n );\n return translations;\n } catch {\n // File doesn't exist at this path, try next one\n continue;\n }\n }\n\n // No translations found\n if (process.env.NODE_ENV === \"development\") {\n logger.warn(\n `Translation file not found for locale: ${locale}. Tried: ${possiblePaths.join(\", \")}`,\n );\n }\n\n return {};\n}\n\n/**\n * Fetch translations for a given locale\n *\n * This is the CORE UNIVERSAL function that works across all frameworks.\n * It handles the logic of fetching translations from either:\n * - Development server (if running)\n * - Filesystem (production or fallback)\n *\n * Framework-specific code should NOT duplicate this logic.\n * Instead, they should:\n * 1. Resolve the locale (framework-specific: cookies, URL, headers, etc.)\n * 2. Call this function to get translations\n *\n * @example\n * ```typescript\n * // In Next.js locale resolver\n * const locale = await getLocaleFromCookies();\n * const translations = await fetchTranslations(locale);\n * ```\n *\n * @example\n * ```typescript\n * // In React Router loader\n * const locale = getLocaleFromUrl(request.url);\n * const translations = await fetchTranslations(locale);\n * ```\n */\nexport async function fetchTranslationsOnServer(\n locale: LocaleCode,\n hashes: string[],\n config: TranslationFetchConfig = {},\n): Promise<Record<string, string>> {\n const isDev = process.env.NODE_ENV === \"development\";\n\n // A provider wrapping the whole tree has no hashes to ask for; without the\n // cache below, SSR would render source text and the client would swap it.\n if (isDev && serverUrl && hashes.length > 0) {\n logger.debug(\n `Server. Fetching translations for ${locale} and ${hashes.join(\", \")} from dev server (${serverUrl})`,\n );\n try {\n return await fetchFromDevServer(locale, hashes, serverUrl);\n } catch (error) {\n logger.warn(\n `Failed to fetch translations from translation server: ${error}.`,\n );\n return {};\n }\n }\n\n logger.debug(`Reading translations for ${locale} from filesystem`);\n return await readFromFilesystem(locale, config.basePath);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,eAAe,mBACb,QACA,WAAmB,QAAQ,KAAK,EACC;CAGjC,MAAM,gBAAgB,CAAC,KAAK,UAAU,SAAS,GAAG,OAAO,OAAO,CAAC;AAEjE,KAAI,QAAQ,IAAI,aAAa,cAE3B,eAAc,KACZ,WAAW,SAAS,GAChB,KAAK,UAAU,GAAG,OAAO,OAAO,GAChC,KAAK,UAAU,UAAU,GAAG,OAAO,OAAO,CAC/C;AAIH,MAAK,MAAM,YAAY,cACrB,KAAI;EACF,MAAM,cAAc,MAAM,SAAS,UAAU,QAAQ;EAErD,MAAM,eADO,KAAK,MAAM,YAAY,CACV,WAAW,EAAE;AAEvC,SAAO,MACL,UAAU,OAAO,KAAK,aAAa,CAAC,OAAO,qBAAqB,WACjE;AACD,SAAO;SACD;AAEN;;AAKJ,KAAI,QAAQ,IAAI,aAAa,cAC3B,QAAO,KACL,0CAA0C,OAAO,WAAW,cAAc,KAAK,KAAK,GACrF;AAGH,QAAO,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BX,eAAsB,0BACpB,QACA,QACA,SAAiC,EAAE,EACF;AAKjC,KAJc,QAAQ,IAAI,aAAa,iBAI1B,aAAa,OAAO,SAAS,GAAG;AAC3C,SAAO,MACL,qCAAqC,OAAO,OAAO,OAAO,KAAK,KAAK,CAAC,oBAAoB,UAAU,GACpG;AACD,MAAI;AACF,UAAO,MAAMA,kBAAmB,QAAQ,QAAQ,UAAU;WACnD,OAAO;AACd,UAAO,KACL,yDAAyD,MAAM,GAChE;AACD,UAAO,EAAE;;;AAIb,QAAO,MAAM,4BAA4B,OAAO,kBAAkB;AAClE,QAAO,MAAM,mBAAmB,QAAQ,OAAO,SAAS"}
1
+ {"version":3,"file":"translations.mjs","names":["fetchFromDevServer"],"sources":["../../../src/react/server-only/translations.ts"],"sourcesContent":["/**\n * Core translation service - framework-agnostic\n * Handles fetching translations from dev server or filesystem\n *\n * This is the UNIVERSAL pattern that works across all frameworks:\n * Given a locale, fetch the translation dictionary for that locale.\n *\n * @module @weglot/translate-react/react/server/translations\n */\n\nimport { readFile } from \"fs/promises\";\nimport { isAbsolute, join } from \"path\";\nimport { logger } from \"../../utils/logger\";\nimport { fetchTranslations as fetchFromDevServer } from \"../shared/utils\";\nimport {\n cacheDir,\n serverUrl,\n sourceLocale,\n} from \"@weglot/translate-react/virtual/config\";\nimport type { LocaleCode } from \"../../locale\";\n\n/**\n * Configuration for translation fetching\n */\nexport interface TranslationFetchConfig {\n /**\n * Base path for translation files (default: process.cwd())\n */\n basePath?: string;\n}\n\n/**\n * Read translations from filesystem\n * Used in production builds or as fallback in development\n *\n * Tries multiple common locations for translation files:\n * - weglot/cache/{locale}.json (dev cache)\n * - .next/{locale}.json (Next.js)\n *\n * @param locale - Target locale\n * @param basePath - Base directory to search from (default: cwd)\n * @returns Translation dictionary (hash -> translated text)\n */\nasync function readFromFilesystem(\n locale: LocaleCode,\n basePath: string = process.cwd(),\n): Promise<Record<string, string>> {\n // TODO (AleksandrSl 15/12/2025): What should be the correct way here to load translations on server for other frameworks?\n // Build output is authoritative: the dev cache must never stand in for it.\n const possiblePaths = [join(basePath, \".next\", `${locale}.json`)];\n\n if (process.env.NODE_ENV === \"development\") {\n // cacheDir is emitted absolute, and join() would append it to basePath.\n possiblePaths.push(\n isAbsolute(cacheDir)\n ? join(cacheDir, `${locale}.json`)\n : join(basePath, cacheDir, `${locale}.json`),\n );\n }\n\n // Try each path until we find the file\n for (const filePath of possiblePaths) {\n try {\n const fileContent = await readFile(filePath, \"utf-8\");\n const data = JSON.parse(fileContent);\n const translations = data.entries || {};\n\n logger.debug(\n `Loaded ${Object.keys(translations).length} translations from ${filePath}`,\n );\n return translations;\n } catch {\n // File doesn't exist at this path, try next one\n continue;\n }\n }\n\n // No translations found\n if (process.env.NODE_ENV === \"development\") {\n logger.warn(\n `Translation file not found for locale: ${locale}. Tried: ${possiblePaths.join(\", \")}`,\n );\n }\n\n return {};\n}\n\n/**\n * Fetch translations for a given locale\n *\n * This is the CORE UNIVERSAL function that works across all frameworks.\n * It handles the logic of fetching translations from either:\n * - Development server (if running)\n * - Filesystem (production or fallback)\n *\n * Framework-specific code should NOT duplicate this logic.\n * Instead, they should:\n * 1. Resolve the locale (framework-specific: cookies, URL, headers, etc.)\n * 2. Call this function to get translations\n *\n * @example\n * ```typescript\n * // In Next.js locale resolver\n * const locale = await getLocaleFromCookies();\n * const translations = await fetchTranslations(locale);\n * ```\n *\n * @example\n * ```typescript\n * // In React Router loader\n * const locale = getLocaleFromUrl(request.url);\n * const translations = await fetchTranslations(locale);\n * ```\n */\nexport async function fetchTranslationsOnServer(\n locale: LocaleCode,\n hashes: string[],\n config: TranslationFetchConfig = {},\n): Promise<Record<string, string>> {\n const isDev = process.env.NODE_ENV === \"development\";\n\n if (isDev && serverUrl && hashes.length > 0) {\n logger.debug(\n `Server. Fetching translations for ${locale} and ${hashes.join(\", \")} from dev server (${serverUrl})`,\n );\n try {\n return await fetchFromDevServer(locale, hashes, serverUrl);\n } catch (error) {\n logger.warn(\n `Failed to fetch translations from translation server: ${error}.`,\n );\n return {};\n }\n }\n\n // No hashes: a provider, whose client components need the whole dictionary.\n if (isDev && serverUrl && locale !== sourceLocale) {\n try {\n return await fetchDictionaryFromDevServer(locale, serverUrl);\n } catch (error) {\n logger.warn(\n `Failed to fetch the ${locale} dictionary from translation server: ${error}.`,\n );\n }\n }\n\n logger.debug(`Reading translations for ${locale} from filesystem`);\n return await readFromFilesystem(locale, config.basePath);\n}\n\nasync function fetchDictionaryFromDevServer(\n locale: LocaleCode,\n url: string,\n): Promise<Record<string, string>> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 30000);\n try {\n const response = await fetch(`${url}/translations/${locale}`, {\n cache: \"no-store\",\n signal: controller.signal,\n });\n if (!response.ok) {\n throw new Error(`Translation server error: ${response.statusText}`);\n }\n const result = await response.json();\n return result.translations || {};\n } finally {\n clearTimeout(timeoutId);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,eAAe,mBACb,QACA,WAAmB,QAAQ,KAAK,EACC;CAGjC,MAAM,gBAAgB,CAAC,KAAK,UAAU,SAAS,GAAG,OAAO,OAAO,CAAC;AAEjE,KAAI,QAAQ,IAAI,aAAa,cAE3B,eAAc,KACZ,WAAW,SAAS,GAChB,KAAK,UAAU,GAAG,OAAO,OAAO,GAChC,KAAK,UAAU,UAAU,GAAG,OAAO,OAAO,CAC/C;AAIH,MAAK,MAAM,YAAY,cACrB,KAAI;EACF,MAAM,cAAc,MAAM,SAAS,UAAU,QAAQ;EAErD,MAAM,eADO,KAAK,MAAM,YAAY,CACV,WAAW,EAAE;AAEvC,SAAO,MACL,UAAU,OAAO,KAAK,aAAa,CAAC,OAAO,qBAAqB,WACjE;AACD,SAAO;SACD;AAEN;;AAKJ,KAAI,QAAQ,IAAI,aAAa,cAC3B,QAAO,KACL,0CAA0C,OAAO,WAAW,cAAc,KAAK,KAAK,GACrF;AAGH,QAAO,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BX,eAAsB,0BACpB,QACA,QACA,SAAiC,EAAE,EACF;CACjC,MAAM,QAAQ,QAAQ,IAAI,aAAa;AAEvC,KAAI,SAAS,aAAa,OAAO,SAAS,GAAG;AAC3C,SAAO,MACL,qCAAqC,OAAO,OAAO,OAAO,KAAK,KAAK,CAAC,oBAAoB,UAAU,GACpG;AACD,MAAI;AACF,UAAO,MAAMA,kBAAmB,QAAQ,QAAQ,UAAU;WACnD,OAAO;AACd,UAAO,KACL,yDAAyD,MAAM,GAChE;AACD,UAAO,EAAE;;;AAKb,KAAI,SAAS,aAAa,WAAW,aACnC,KAAI;AACF,SAAO,MAAM,6BAA6B,QAAQ,UAAU;UACrD,OAAO;AACd,SAAO,KACL,uBAAuB,OAAO,uCAAuC,MAAM,GAC5E;;AAIL,QAAO,MAAM,4BAA4B,OAAO,kBAAkB;AAClE,QAAO,MAAM,mBAAmB,QAAQ,OAAO,SAAS;;AAG1D,eAAe,6BACb,QACA,KACiC;CACjC,MAAM,aAAa,IAAI,iBAAiB;CACxC,MAAM,YAAY,iBAAiB,WAAW,OAAO,EAAE,IAAM;AAC7D,KAAI;EACF,MAAM,WAAW,MAAM,MAAM,GAAG,IAAI,gBAAgB,UAAU;GAC5D,OAAO;GACP,QAAQ,WAAW;GACpB,CAAC;AACF,MAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MAAM,6BAA6B,SAAS,aAAa;AAGrE,UADe,MAAM,SAAS,MAAM,EACtB,gBAAgB,EAAE;WACxB;AACR,eAAa,UAAU"}
@@ -1,6 +1,6 @@
1
1
  import { LocaleCode } from "../../locale.mjs";
2
2
  import { CSSProperties } from "react";
3
- import * as react_jsx_runtime1 from "react/jsx-runtime";
3
+ import * as react_jsx_runtime3 from "react/jsx-runtime";
4
4
 
5
5
  //#region src/react/shared/LocaleSwitcher.d.ts
6
6
  interface LocaleConfig {
@@ -65,7 +65,7 @@ declare function LocaleSwitcher({
65
65
  style,
66
66
  className,
67
67
  showLoadingState
68
- }: LocaleSwitcherProps): react_jsx_runtime1.JSX.Element;
68
+ }: LocaleSwitcherProps): react_jsx_runtime3.JSX.Element;
69
69
  //#endregion
70
70
  export { LocaleSwitcher };
71
71
  //# sourceMappingURL=LocaleSwitcher.d.mts.map
@@ -1,4 +1,5 @@
1
1
  import { LocaleCode } from "../../locale.mjs";
2
+ import "react";
2
3
 
3
4
  //#region src/react/shared/WeglotContext.d.ts
4
5
  interface WeglotContextType {
@@ -1 +1 @@
1
- {"version":3,"file":"WeglotContext.d.mts","names":[],"sources":["../../../src/react/shared/WeglotContext.ts"],"sourcesContent":[],"mappings":";;;UAKU,iBAAA;;AAFqC;;EAWrC,YAAA,EALM,UAKN;EAKY;;;EAKA,MAAA,EAVZ,UAUY;EA4BN;;;sBAjCM,eAAe;;;;gBAKrB;;;;;;;;;;;;iBA4BA,gBAAA,CAAA,GAAoB"}
1
+ {"version":3,"file":"WeglotContext.d.mts","names":[],"sources":["../../../src/react/shared/WeglotContext.ts"],"sourcesContent":[],"mappings":";;;;UAKU,iBAAA;;;AAFqC;EAM/B,YAAA,EAAA,UAAA;EAKN;;;EAUM,MAAA,EAVN,UAUM;EAAM;AA4BtB;;sBAjCsB,eAAe;;;;gBAKrB;;;;;;;;;;;;iBA4BA,gBAAA,CAAA,GAAoB"}
@@ -1,6 +1,6 @@
1
1
  import { LocaleCode } from "../../locale.mjs";
2
2
  import { PropsWithChildren } from "react";
3
- import * as react_jsx_runtime2 from "react/jsx-runtime";
3
+ import * as react_jsx_runtime1 from "react/jsx-runtime";
4
4
 
5
5
  //#region src/react/shared/WeglotProvider.d.ts
6
6
  /**
@@ -54,7 +54,7 @@ declare function WeglotProvider__Dev({
54
54
  initialTranslations,
55
55
  router,
56
56
  children
57
- }: WeglotProviderProps): react_jsx_runtime2.JSX.Element;
57
+ }: WeglotProviderProps): react_jsx_runtime1.JSX.Element;
58
58
  //#endregion
59
59
  export { WeglotProvider, WeglotProviderProps };
60
60
  //# sourceMappingURL=WeglotProvider.d.mts.map