@weglot/translate-react 0.2.1 → 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.
- package/README.md +118 -12
- package/build/metadata/manager.cjs +18 -5
- package/build/metadata/manager.mjs +17 -5
- package/build/metadata/manager.mjs.map +1 -1
- package/build/plugin/next-compiler-loader.cjs +1 -4
- package/build/plugin/next-compiler-loader.mjs +2 -5
- package/build/plugin/next-compiler-loader.mjs.map +1 -1
- package/build/plugin/next-traces.cjs +38 -0
- package/build/plugin/next-traces.mjs +36 -0
- package/build/plugin/next-traces.mjs.map +1 -0
- package/build/plugin/next.cjs +43 -12
- package/build/plugin/next.d.cts.map +1 -1
- package/build/plugin/next.d.mts.map +1 -1
- package/build/plugin/next.mjs +41 -13
- package/build/plugin/next.mjs.map +1 -1
- package/build/plugin/transform/index.cjs +17 -3
- package/build/plugin/transform/index.mjs +17 -3
- package/build/plugin/transform/index.mjs.map +1 -1
- package/build/plugin/transform/msg.cjs +66 -0
- package/build/plugin/transform/msg.mjs +64 -0
- package/build/plugin/transform/msg.mjs.map +1 -0
- package/build/plugin/transform/process-file.cjs +18 -7
- package/build/plugin/transform/process-file.mjs +18 -7
- package/build/plugin/transform/process-file.mjs.map +1 -1
- package/build/plugin/transform/utils.cjs +1 -0
- package/build/plugin/transform/utils.mjs +1 -1
- package/build/plugin/transform/utils.mjs.map +1 -1
- package/build/plugin/unplugin.cjs +6 -7
- package/build/plugin/unplugin.d.cts.map +1 -1
- package/build/plugin/unplugin.d.mts.map +1 -1
- package/build/plugin/unplugin.mjs +7 -8
- package/build/plugin/unplugin.mjs.map +1 -1
- package/build/react/client/index.cjs +2 -0
- package/build/react/client/index.d.cts +2 -1
- package/build/react/client/index.d.mts +2 -1
- package/build/react/client/index.mjs +2 -1
- package/build/react/client/useTranslation.cjs +14 -2
- package/build/react/client/useTranslation.d.cts +0 -35
- package/build/react/client/useTranslation.d.cts.map +1 -1
- package/build/react/client/useTranslation.d.mts +0 -35
- package/build/react/client/useTranslation.d.mts.map +1 -1
- package/build/react/client/useTranslation.mjs +15 -3
- package/build/react/client/useTranslation.mjs.map +1 -1
- package/build/react/server/ServerWeglotProvider.d.cts +2 -2
- package/build/react/server/ServerWeglotProvider.d.mts +2 -2
- package/build/react/server/index.cjs +2 -0
- package/build/react/server/index.d.cts +2 -1
- package/build/react/server/index.d.mts +2 -1
- package/build/react/server/index.mjs +2 -1
- package/build/react/server/useTranslation.cjs +6 -4
- package/build/react/server/useTranslation.d.cts.map +1 -1
- package/build/react/server/useTranslation.d.mts.map +1 -1
- package/build/react/server/useTranslation.mjs +6 -4
- package/build/react/server/useTranslation.mjs.map +1 -1
- package/build/react/server-only/index.cjs +5 -3
- package/build/react/server-only/index.d.cts +2 -3
- package/build/react/server-only/index.d.cts.map +1 -1
- package/build/react/server-only/index.d.mts +2 -3
- package/build/react/server-only/index.d.mts.map +1 -1
- package/build/react/server-only/index.mjs +5 -3
- package/build/react/server-only/index.mjs.map +1 -1
- package/build/react/server-only/translations.cjs +21 -1
- package/build/react/server-only/translations.mjs +22 -2
- package/build/react/server-only/translations.mjs.map +1 -1
- package/build/react/shared/LocaleSwitcher.d.mts +2 -2
- package/build/react/shared/WeglotContext.cjs +18 -2
- package/build/react/shared/WeglotContext.d.cts +1 -0
- package/build/react/shared/WeglotContext.d.cts.map +1 -1
- package/build/react/shared/WeglotContext.d.mts +2 -0
- package/build/react/shared/WeglotContext.d.mts.map +1 -1
- package/build/react/shared/WeglotContext.mjs +18 -2
- package/build/react/shared/WeglotContext.mjs.map +1 -1
- package/build/react/shared/WeglotProvider.cjs +4 -0
- package/build/react/shared/WeglotProvider.d.cts +2 -2
- package/build/react/shared/WeglotProvider.d.cts.map +1 -1
- package/build/react/shared/WeglotProvider.d.mts +2 -2
- package/build/react/shared/WeglotProvider.d.mts.map +1 -1
- package/build/react/shared/WeglotProvider.mjs +4 -0
- package/build/react/shared/WeglotProvider.mjs.map +1 -1
- package/build/react/shared/msg.cjs +50 -0
- package/build/react/shared/msg.d.cts +26 -0
- package/build/react/shared/msg.d.cts.map +1 -0
- package/build/react/shared/msg.d.mts +26 -0
- package/build/react/shared/msg.d.mts.map +1 -0
- package/build/react/shared/msg.mjs +47 -0
- package/build/react/shared/msg.mjs.map +1 -0
- package/build/react/types.d.cts +7 -3
- package/build/react/types.d.cts.map +1 -1
- package/build/react/types.d.mts +7 -3
- package/build/react/types.d.mts.map +1 -1
- package/build/runtime/lru-cache.cjs +38 -0
- package/build/runtime/lru-cache.mjs +38 -0
- package/build/runtime/lru-cache.mjs.map +1 -0
- package/build/runtime/translate-dynamic.cjs +71 -17
- package/build/runtime/translate-dynamic.d.cts +2 -0
- package/build/runtime/translate-dynamic.d.cts.map +1 -1
- package/build/runtime/translate-dynamic.d.mts +2 -0
- package/build/runtime/translate-dynamic.d.mts.map +1 -1
- package/build/runtime/translate-dynamic.mjs +71 -17
- package/build/runtime/translate-dynamic.mjs.map +1 -1
- package/build/translators/weglot/api-client.cjs +4 -1
- package/build/translators/weglot/api-client.mjs +4 -1
- package/build/translators/weglot/api-client.mjs.map +1 -1
- package/build/types.d.cts +7 -1
- package/build/types.d.cts.map +1 -1
- package/build/types.d.mts +7 -1
- package/build/types.d.mts.map +1 -1
- package/build/utils/package-version.cjs +12 -0
- package/build/utils/package-version.mjs +12 -0
- package/build/utils/package-version.mjs.map +1 -0
- package/package.json +4 -2
|
@@ -1,12 +1,28 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_logger = require('../../utils/logger.cjs');
|
|
2
3
|
let react = require("react");
|
|
4
|
+
let _weglot_translate_react_virtual_config = require("@weglot/translate-react/virtual/config");
|
|
3
5
|
|
|
4
6
|
//#region src/react/shared/WeglotContext.ts
|
|
5
7
|
const WeglotContext = (0, react.createContext)(null);
|
|
8
|
+
const withoutProvider = {
|
|
9
|
+
sourceLocale: _weglot_translate_react_virtual_config.sourceLocale,
|
|
10
|
+
locale: _weglot_translate_react_virtual_config.sourceLocale,
|
|
11
|
+
setLocale: async () => {},
|
|
12
|
+
translations: {},
|
|
13
|
+
registerHashes: () => {},
|
|
14
|
+
isLoading: false
|
|
15
|
+
};
|
|
16
|
+
let warnedWithoutProvider = false;
|
|
17
|
+
/** Without a provider, such as in Next's global-not-found, text stays in the source language. */
|
|
6
18
|
function useWeglotContext() {
|
|
7
19
|
const context = (0, react.useContext)(WeglotContext);
|
|
8
|
-
if (
|
|
9
|
-
|
|
20
|
+
if (context) return context;
|
|
21
|
+
if (process.env.NODE_ENV === "development" && !warnedWithoutProvider) {
|
|
22
|
+
warnedWithoutProvider = true;
|
|
23
|
+
require_logger.logger.warn("A component is rendered outside WeglotProvider, so it stays in the source language. Wrap it in WeglotProvider to translate it.");
|
|
24
|
+
}
|
|
25
|
+
return withoutProvider;
|
|
10
26
|
}
|
|
11
27
|
|
|
12
28
|
//#endregion
|
|
@@ -28,6 +28,7 @@ interface WeglotContextType {
|
|
|
28
28
|
*/
|
|
29
29
|
isLoading: boolean;
|
|
30
30
|
}
|
|
31
|
+
/** Without a provider, such as in Next's global-not-found, text stays in the source language. */
|
|
31
32
|
declare function useWeglotContext(): WeglotContextType;
|
|
32
33
|
//#endregion
|
|
33
34
|
export { useWeglotContext };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WeglotContext.d.cts","names":[],"sources":["../../../src/react/shared/WeglotContext.ts"],"sourcesContent":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"WeglotContext.d.cts","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,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 {
|
|
@@ -28,6 +29,7 @@ interface WeglotContextType {
|
|
|
28
29
|
*/
|
|
29
30
|
isLoading: boolean;
|
|
30
31
|
}
|
|
32
|
+
/** Without a provider, such as in Next's global-not-found, text stays in the source language. */
|
|
31
33
|
declare function useWeglotContext(): WeglotContextType;
|
|
32
34
|
//#endregion
|
|
33
35
|
export { useWeglotContext };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WeglotContext.d.mts","names":[],"sources":["../../../src/react/shared/WeglotContext.ts"],"sourcesContent":[],"mappings":"
|
|
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,11 +1,27 @@
|
|
|
1
|
+
import { logger } from "../../utils/logger.mjs";
|
|
1
2
|
import { createContext, useContext } from "react";
|
|
3
|
+
import { sourceLocale } from "@weglot/translate-react/virtual/config";
|
|
2
4
|
|
|
3
5
|
//#region src/react/shared/WeglotContext.ts
|
|
4
6
|
const WeglotContext = createContext(null);
|
|
7
|
+
const withoutProvider = {
|
|
8
|
+
sourceLocale,
|
|
9
|
+
locale: sourceLocale,
|
|
10
|
+
setLocale: async () => {},
|
|
11
|
+
translations: {},
|
|
12
|
+
registerHashes: () => {},
|
|
13
|
+
isLoading: false
|
|
14
|
+
};
|
|
15
|
+
let warnedWithoutProvider = false;
|
|
16
|
+
/** Without a provider, such as in Next's global-not-found, text stays in the source language. */
|
|
5
17
|
function useWeglotContext() {
|
|
6
18
|
const context = useContext(WeglotContext);
|
|
7
|
-
if (
|
|
8
|
-
|
|
19
|
+
if (context) return context;
|
|
20
|
+
if (process.env.NODE_ENV === "development" && !warnedWithoutProvider) {
|
|
21
|
+
warnedWithoutProvider = true;
|
|
22
|
+
logger.warn("A component is rendered outside WeglotProvider, so it stays in the source language. Wrap it in WeglotProvider to translate it.");
|
|
23
|
+
}
|
|
24
|
+
return withoutProvider;
|
|
9
25
|
}
|
|
10
26
|
|
|
11
27
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WeglotContext.mjs","names":[],"sources":["../../../src/react/shared/WeglotContext.ts"],"sourcesContent":["import { createContext, useContext } from \"react\";\nimport type { LocaleCode } from \"../../locale\";\n\ninterface WeglotContextType {\n /**\n * Source locale (default language)\n */\n sourceLocale: LocaleCode;\n\n /**\n * Current locale (e.g., 'en', 'de', 'fr')\n */\n locale: LocaleCode;\n\n /**\n * Change the current locale and dynamically load translations\n */\n setLocale: (locale: LocaleCode) => Promise<void>;\n\n /**\n * Translation dictionary: hash -> translated text\n */\n translations: Record<string, string>;\n\n /**\n * Register a hash as being used in a component\n * The provider will automatically request missing translations\n */\n registerHashes: (hashes: string[]) => void;\n\n /**\n * Whether translations are currently being loaded\n */\n isLoading: boolean;\n}\n\nexport const WeglotContext = createContext<WeglotContextType | null>(null);\n\nexport function useWeglotContext(): WeglotContextType {\n const context = useContext(WeglotContext);\n
|
|
1
|
+
{"version":3,"file":"WeglotContext.mjs","names":["withoutProvider: WeglotContextType"],"sources":["../../../src/react/shared/WeglotContext.ts"],"sourcesContent":["import { createContext, useContext } from \"react\";\nimport { sourceLocale } from \"@weglot/translate-react/virtual/config\";\nimport { logger } from \"../../utils/logger\";\nimport type { LocaleCode } from \"../../locale\";\n\ninterface WeglotContextType {\n /**\n * Source locale (default language)\n */\n sourceLocale: LocaleCode;\n\n /**\n * Current locale (e.g., 'en', 'de', 'fr')\n */\n locale: LocaleCode;\n\n /**\n * Change the current locale and dynamically load translations\n */\n setLocale: (locale: LocaleCode) => Promise<void>;\n\n /**\n * Translation dictionary: hash -> translated text\n */\n translations: Record<string, string>;\n\n /**\n * Register a hash as being used in a component\n * The provider will automatically request missing translations\n */\n registerHashes: (hashes: string[]) => void;\n\n /**\n * Whether translations are currently being loaded\n */\n isLoading: boolean;\n}\n\nexport const WeglotContext = createContext<WeglotContextType | null>(null);\n\nconst withoutProvider: WeglotContextType = {\n sourceLocale,\n locale: sourceLocale,\n setLocale: async () => {},\n translations: {},\n registerHashes: () => {},\n isLoading: false,\n};\n\nlet warnedWithoutProvider = false;\n\n/** Without a provider, such as in Next's global-not-found, text stays in the source language. */\nexport function useWeglotContext(): WeglotContextType {\n const context = useContext(WeglotContext);\n if (context) return context;\n\n if (process.env.NODE_ENV === \"development\" && !warnedWithoutProvider) {\n warnedWithoutProvider = true;\n logger.warn(\n \"A component is rendered outside WeglotProvider, so it stays in the source language. Wrap it in WeglotProvider to translate it.\",\n );\n }\n return withoutProvider;\n}\n"],"mappings":";;;;;AAsCA,MAAa,gBAAgB,cAAwC,KAAK;AAE1E,MAAMA,kBAAqC;CACzC;CACA,QAAQ;CACR,WAAW,YAAY;CACvB,cAAc,EAAE;CAChB,sBAAsB;CACtB,WAAW;CACZ;AAED,IAAI,wBAAwB;;AAG5B,SAAgB,mBAAsC;CACpD,MAAM,UAAU,WAAW,cAAc;AACzC,KAAI,QAAS,QAAO;AAEpB,KAAI,QAAQ,IAAI,aAAa,iBAAiB,CAAC,uBAAuB;AACpE,0BAAwB;AACxB,SAAO,KACL,iIACD;;AAEH,QAAO"}
|
|
@@ -60,6 +60,10 @@ function WeglotProvider__Prod({ initialLocale, initialTranslations = {}, router,
|
|
|
60
60
|
*/
|
|
61
61
|
const loadTranslations = (0, react.useCallback)(async (targetLocale) => {
|
|
62
62
|
if (Object.keys(initialTranslations).length > 0) return;
|
|
63
|
+
if (targetLocale === _weglot_translate_react_virtual_config.sourceLocale) {
|
|
64
|
+
setTranslations({});
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
63
67
|
setIsLoading(true);
|
|
64
68
|
try {
|
|
65
69
|
const response = await fetch(`/translations/${targetLocale}.json`);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { LocaleCode } from "../../locale.cjs";
|
|
2
|
-
import * as
|
|
2
|
+
import * as react_jsx_runtime3 from "react/jsx-runtime";
|
|
3
3
|
import { PropsWithChildren } from "react";
|
|
4
4
|
|
|
5
5
|
//#region src/react/shared/WeglotProvider.d.ts
|
|
@@ -54,7 +54,7 @@ declare function WeglotProvider__Dev({
|
|
|
54
54
|
initialTranslations,
|
|
55
55
|
router,
|
|
56
56
|
children
|
|
57
|
-
}: WeglotProviderProps):
|
|
57
|
+
}: WeglotProviderProps): react_jsx_runtime3.JSX.Element;
|
|
58
58
|
//#endregion
|
|
59
59
|
export { WeglotProvider, WeglotProviderProps };
|
|
60
60
|
//# sourceMappingURL=WeglotProvider.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WeglotProvider.d.cts","names":[],"sources":["../../../src/react/shared/WeglotProvider.tsx"],"sourcesContent":[],"mappings":";;;;;;;;AAwBY,KAAA,mBAAA,GAAsB,iBAAH,CAAA;EAIb;;;EAJiC,aAAA,CAAA,EAIjC,UAJiC;EA+CtC;AAAqE;;
|
|
1
|
+
{"version":3,"file":"WeglotProvider.d.cts","names":[],"sources":["../../../src/react/shared/WeglotProvider.tsx"],"sourcesContent":[],"mappings":";;;;;;;;AAwBY,KAAA,mBAAA,GAAsB,iBAAH,CAAA;EAIb;;;EAJiC,aAAA,CAAA,EAIjC,UAJiC;EA+CtC;AAAqE;;EAyIhF,mBAAA,CAAA,EA/KsB,MA+KtB,CAAA,MAAA,EAAA,MAAA,CAAA;EACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA1IW,uBAAc;iBAuIlB,mBAAA;;;;;GAKN,sBAAmB,kBAAA,CAAA,GAAA,CAAA"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { LocaleCode } from "../../locale.mjs";
|
|
2
2
|
import { PropsWithChildren } from "react";
|
|
3
|
-
import * as
|
|
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):
|
|
57
|
+
}: WeglotProviderProps): react_jsx_runtime1.JSX.Element;
|
|
58
58
|
//#endregion
|
|
59
59
|
export { WeglotProvider, WeglotProviderProps };
|
|
60
60
|
//# sourceMappingURL=WeglotProvider.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WeglotProvider.d.mts","names":[],"sources":["../../../src/react/shared/WeglotProvider.tsx"],"sourcesContent":[],"mappings":";;;;;;;;AAwBY,KAAA,mBAAA,GAAsB,iBAAH,CAAA;EAIb;;;EAJiC,aAAA,CAAA,EAIjC,UAJiC;EA+CtC;AAAqE;;
|
|
1
|
+
{"version":3,"file":"WeglotProvider.d.mts","names":[],"sources":["../../../src/react/shared/WeglotProvider.tsx"],"sourcesContent":[],"mappings":";;;;;;;;AAwBY,KAAA,mBAAA,GAAsB,iBAAH,CAAA;EAIb;;;EAJiC,aAAA,CAAA,EAIjC,UAJiC;EA+CtC;AAAqE;;EAyIhF,mBAAA,CAAA,EA/KsB,MA+KtB,CAAA,MAAA,EAAA,MAAA,CAAA;EACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA1IW,uBAAc;iBAuIlB,mBAAA;;;;;GAKN,sBAAmB,kBAAA,CAAA,GAAA,CAAA"}
|
|
@@ -59,6 +59,10 @@ function WeglotProvider__Prod({ initialLocale, initialTranslations = {}, router,
|
|
|
59
59
|
*/
|
|
60
60
|
const loadTranslations = useCallback(async (targetLocale) => {
|
|
61
61
|
if (Object.keys(initialTranslations).length > 0) return;
|
|
62
|
+
if (targetLocale === sourceLocale) {
|
|
63
|
+
setTranslations({});
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
62
66
|
setIsLoading(true);
|
|
63
67
|
try {
|
|
64
68
|
const response = await fetch(`/translations/${targetLocale}.json`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WeglotProvider.mjs","names":["missingHashes: string[]","missingHashes"],"sources":["../../../src/react/shared/WeglotProvider.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n type PropsWithChildren,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from \"react\";\nimport { logger } from \"../../utils/logger\";\nimport { fetchTranslations } from \"./utils\";\nimport { serverUrl, sourceLocale } from \"@weglot/translate-react/virtual/config\";\nimport {\n getClientLocale,\n persistLocale,\n} from \"@weglot/translate-react/virtual/locale/client\";\nimport { WeglotContext } from \"./WeglotContext\";\nimport type { LocaleCode } from \"../../locale\";\n\nconst noop = () => {};\n\n/**\n * Translation provider props\n */\nexport type WeglotProviderProps = PropsWithChildren<{\n /**\n * Initial locale to use\n */\n initialLocale?: LocaleCode;\n\n /**\n * Initial translations (pre-loaded)\n */\n initialTranslations?: Record<string, string>;\n\n /**\n * Optional router instance for Next.js integration\n * If provided, calls router.refresh() after locale change\n * This ensures Server Components re-render with new locale\n */\n router?: { refresh: () => void };\n}>;\n\nconst IS_DEV = process.env.NODE_ENV === \"development\";\nconst BATCH_DELAY = 200;\n\n/**\n * Translation Provider Component\n *\n * Wraps your app to provide translation context to all components.\n * Handles locale switching and on-demand translation loading.\n *\n * @example\n * ```tsx\n * // In your root layout\n * import { WeglotProvider } from '@weglot/translate-react/react';\n *\n * export default function RootLayout({ children }) {\n * return (\n * <html>\n * <body>\n * <WeglotProvider initialLocale=\"en\">\n * {children}\n * </WeglotProvider>\n * </body>\n * </html>\n * );\n * }\n * ```\n */\n// Export the appropriate provider directly\nexport const WeglotProvider = IS_DEV ? WeglotProvider__Dev : WeglotProvider__Prod;\n\nfunction WeglotProvider__Prod({\n initialLocale,\n initialTranslations = {},\n router,\n children,\n}: WeglotProviderProps) {\n // Use client locale detection if no initialLocale provided\n const [locale, setLocaleState] = useState<LocaleCode>(() => {\n if (initialLocale) return initialLocale;\n // Only detect on client-side (not during SSR)\n if (typeof window !== \"undefined\") {\n return getClientLocale();\n }\n return sourceLocale;\n });\n const [translations, setTranslations] =\n useState<Record<string, string>>(initialTranslations);\n const [isLoading, setIsLoading] = useState(false);\n\n logger.debug(\n `WeglotProvider initialized with locale: ${locale}`,\n initialTranslations,\n );\n\n /**\n * Update HTML lang attribute when locale changes\n * This ensures screen readers and SEO understand the page language\n */\n useEffect(() => {\n if (typeof document !== \"undefined\") {\n document.documentElement.lang = locale;\n }\n }, [locale]);\n\n /**\n * Load translations from public/translations/{locale}.json\n * Lazy loads on-demand for SPAs\n */\n const loadTranslations = useCallback(\n async (targetLocale: LocaleCode) => {\n // If we already have initialTranslations (Next.js SSR), don't fetch\n if (Object.keys(initialTranslations).length > 0) {\n return;\n }\n\n setIsLoading(true);\n try {\n const response = await fetch(`/translations/${targetLocale}.json`);\n if (!response.ok) {\n throw new Error(\n `Failed to load translations for ${targetLocale}: ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n // Translation files have format: { version, locale, entries: {...} }\n setTranslations(data.entries || data);\n logger.debug(\n `Loaded translations for ${targetLocale}:`,\n Object.keys(data.entries || data).length,\n );\n } catch (error) {\n logger.error(`Failed to load translations for ${targetLocale}:`, error);\n // Fallback to empty translations\n setTranslations({});\n } finally {\n setIsLoading(false);\n }\n },\n [initialTranslations],\n );\n\n // Load translations on mount if not provided via initialTranslations\n useEffect(() => {\n if (Object.keys(initialTranslations).length === 0) {\n loadTranslations(locale);\n }\n }, []); // Only run on mount\n\n useEffect(() => {\n // TODO (AleksandrSl 08/12/2025): More elegant solution required.\n // This is used to update the client part when next app changes locale\n if (router) {\n setTranslations(initialTranslations);\n }\n }, [initialTranslations, router]);\n\n /**\n * Change locale\n * - For Next.js SSR: triggers server re-render via router.refresh()\n * - For SPAs: lazy loads translations from /translations/{locale}.json\n */\n const setLocale = useCallback(\n async (newLocale: LocaleCode) => {\n // 1. Persist to cookie so server can read it on next render\n persistLocale(newLocale);\n\n // 2. Update local state for immediate UI feedback\n setLocaleState(newLocale);\n\n // 3a. Next.js pattern: Trigger server re-render\n if (router) {\n router.refresh();\n }\n // 3b. SPA pattern: Lazy load translations\n else {\n await loadTranslations(newLocale);\n }\n },\n [router, loadTranslations],\n );\n\n return (\n <WeglotContext.Provider\n value={{\n locale,\n setLocale,\n translations,\n registerHashes: noop,\n isLoading,\n sourceLocale,\n }}\n >\n {children}\n </WeglotContext.Provider>\n );\n}\n\nfunction WeglotProvider__Dev({\n initialLocale,\n initialTranslations = {},\n router,\n children,\n}: WeglotProviderProps) {\n // Use client locale detection if no initialLocale provided\n const [locale, setLocaleState] = useState(() => {\n if (initialLocale) {\n return initialLocale;\n }\n return getClientLocale();\n });\n const [translations, setTranslations] =\n useState<Record<string, string>>(initialTranslations);\n const [isLoading, setIsLoading] = useState(false);\n\n const [allSeenHashes, setAllSeenHashes] = useState<Set<string>>(new Set());\n const registeredHashesRef = useRef<Set<string>>(new Set());\n const pendingHashesRef = useRef<Set<string>>(new Set());\n const erroredHashesRef = useRef<Set<string>>(new Set());\n const batchTimerRef = useRef<NodeJS.Timeout | null>(null);\n\n // Use ref to track translations to avoid stale closures\n const translationsRef = useRef<Record<string, string>>(initialTranslations);\n const localeRef = useRef(locale);\n\n useEffect(() => {\n translationsRef.current = translations;\n }, [translations]);\n\n useEffect(() => {\n localeRef.current = locale;\n }, [locale]);\n\n /**\n * Update HTML lang attribute when locale changes\n * This ensures screen readers and SEO understand the page language\n */\n useEffect(() => {\n if (typeof document !== \"undefined\") {\n document.documentElement.lang = locale;\n }\n }, [locale]);\n\n /**\n * Register a hash as being used in a component\n * Called during render - must not trigger state updates immediately\n */\n const registerHashes = useCallback((hashes: string[]) => {\n let wasNew = false;\n hashes.forEach((hash) => {\n wasNew = wasNew || !registeredHashesRef.current.has(hash);\n registeredHashesRef.current.add(hash);\n });\n\n logger.debug(\n `Registering hashes: ${hashes.join(\", \")}. Registered hashes: ${registeredHashesRef.current.values()}. wasNew: ${wasNew}`,\n );\n\n // Schedule a state update for the next tick to track all hashes\n if (wasNew) {\n setAllSeenHashes((prev) => {\n const next = prev.union(new Set(hashes));\n // TODO (AleksandrSl 25/11/2025): Should be a cheaper solution\n logger.debug(`New allSeenHashes: ${[...next.values()]}`);\n return next;\n });\n }\n }, []);\n\n /**\n * Check for missing translations and request them (batched)\n * This runs when allSeenHashes changes (hot reload or new components mount)\n */\n useEffect(() => {\n logger.debug(\n `WeglotProvider checking translations for locale ${locale}, seen hashes: ${allSeenHashes.size}`,\n );\n\n // The source locale has no dictionary; asking would mark every hash failed\n // and stop it being fetched for later locales.\n if (locale === sourceLocale) {\n return;\n }\n\n // Find hashes that are seen but not translated and not already pending\n const missingHashes: string[] = [];\n logger.debug(\n \"allSeenHashes: \",\n [...allSeenHashes.values()],\n [...pendingHashesRef.current.values()],\n );\n for (const hash of allSeenHashes) {\n if (\n !translations[hash] &&\n !pendingHashesRef.current.has(hash) &&\n !erroredHashesRef.current.has(hash)\n ) {\n missingHashes.push(hash);\n pendingHashesRef.current.add(hash);\n }\n }\n logger.debug(\"Missing hashes: \", missingHashes.join(\",\"));\n\n // If no missing hashes, nothing to do\n if (missingHashes.length === 0 && localeRef.current == locale) return;\n\n logger.debug(\n `Requesting translations for ${missingHashes.length} hashes in locale ${locale}`,\n );\n\n // Cancel existing timer\n if (batchTimerRef.current) {\n clearTimeout(batchTimerRef.current);\n }\n\n // Batch the request\n batchTimerRef.current = setTimeout(async () => {\n const hashesToFetch = Array.from(pendingHashesRef.current);\n pendingHashesRef.current.clear();\n\n logger.debug(`Fetching translations for ${hashesToFetch.length} hashes`);\n if (hashesToFetch.length === 0) return;\n\n setIsLoading(true);\n try {\n const newTranslations = await fetchTranslations(\n localeRef.current,\n hashesToFetch,\n serverUrl,\n );\n\n logger.debug(\n `Fetched translations for ${hashesToFetch.length} hashes:`,\n newTranslations,\n );\n\n const receivedHashes = new Set(Object.keys(newTranslations));\n const missingHashes = hashesToFetch.filter(\n (hash) => !receivedHashes.has(hash),\n );\n\n if (missingHashes.length > 0) {\n logger.warn(\n `Server did not return translations for ${missingHashes.length} hashes: ${missingHashes.join(\", \")}`,\n );\n for (const hash of missingHashes) {\n erroredHashesRef.current.add(hash);\n }\n }\n\n setTranslations((prev) => ({ ...prev, ...newTranslations }));\n for (const hash of hashesToFetch) {\n registeredHashesRef.current.add(hash);\n }\n } catch (error) {\n logger.warn(\n `Failed to fetch translations from translation server: ${error}.`,\n );\n // Remove from pending so they can be retried\n for (const hash of hashesToFetch) {\n pendingHashesRef.current.delete(hash);\n erroredHashesRef.current.add(hash);\n }\n } finally {\n setIsLoading(false);\n }\n }, BATCH_DELAY);\n }, [allSeenHashes, locale, translations]);\n\n /**\n * Clear batch timer on unmount\n */\n useEffect(() => {\n return () => {\n if (batchTimerRef.current) {\n clearTimeout(batchTimerRef.current);\n }\n };\n }, []);\n\n /**\n * Change locale and load translations dynamically\n */\n const setLocale = useCallback(\n async (newLocale: LocaleCode) => {\n // 1. Persist to cookie (unless disabled)\n persistLocale(newLocale);\n\n // 2. Update state\n setLocaleState(newLocale);\n\n // 3. Reload Server Components (if router provided)\n if (router) {\n router.refresh();\n }\n\n setIsLoading(true);\n const startTime = performance.now();\n\n try {\n logger.info(\n `Fetching translations for locale: ${newLocale}. Server url: ${serverUrl}`,\n );\n\n // Everything on the page in one request; later mounts go through batching.\n const hashes = [...registeredHashesRef.current];\n pendingHashesRef.current.clear();\n // A hash that failed for one locale may well exist for the next.\n erroredHashesRef.current.clear();\n\n const newTranslations = hashes.length\n ? await fetchTranslations(newLocale, hashes, serverUrl)\n : {};\n\n const endTime = performance.now();\n logger.info(\n `Translation fetch complete for ${newLocale} in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n logger.debug(`Translations loaded for ${newLocale}:`, newTranslations);\n\n // Replace rather than merge: entries of the previous locale must go.\n setTranslations(newTranslations);\n } catch (error) {\n logger.error(`Failed to load translations for ${newLocale}:`, error);\n // Clear translations on error - components will request individually\n setTranslations({});\n } finally {\n setIsLoading(false);\n }\n },\n [router],\n );\n\n // TODO (AleksandrSl 24/11/2025): Should I memo the value?\n return (\n <WeglotContext.Provider\n value={{\n locale,\n setLocale,\n translations,\n registerHashes,\n isLoading,\n sourceLocale,\n }}\n >\n {children}\n </WeglotContext.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;AAmBA,MAAM,aAAa;AAwBnB,MAAM,SAAS,QAAQ,IAAI,aAAa;AACxC,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;AA2BpB,MAAa,iBAAiB,SAAS,sBAAsB;AAE7D,SAAS,qBAAqB,EAC5B,eACA,sBAAsB,EAAE,EACxB,QACA,YACsB;CAEtB,MAAM,CAAC,QAAQ,kBAAkB,eAA2B;AAC1D,MAAI,cAAe,QAAO;AAE1B,MAAI,OAAO,WAAW,YACpB,QAAO,iBAAiB;AAE1B,SAAO;GACP;CACF,MAAM,CAAC,cAAc,mBACnB,SAAiC,oBAAoB;CACvD,MAAM,CAAC,WAAW,gBAAgB,SAAS,MAAM;AAEjD,QAAO,MACL,2CAA2C,UAC3C,oBACD;;;;;AAMD,iBAAgB;AACd,MAAI,OAAO,aAAa,YACtB,UAAS,gBAAgB,OAAO;IAEjC,CAAC,OAAO,CAAC;;;;;CAMZ,MAAM,mBAAmB,YACvB,OAAO,iBAA6B;AAElC,MAAI,OAAO,KAAK,oBAAoB,CAAC,SAAS,EAC5C;AAGF,eAAa,KAAK;AAClB,MAAI;GACF,MAAM,WAAW,MAAM,MAAM,iBAAiB,aAAa,OAAO;AAClE,OAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,mCAAmC,aAAa,IAAI,SAAS,aAC9D;GAGH,MAAM,OAAO,MAAM,SAAS,MAAM;AAElC,mBAAgB,KAAK,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M,YAAY,YAAY,KAAK;AAEnC,MAAI;AACF,UAAO,KACL,qCAAqC,UAAU,gBAAgB,YAChE;GAGD,MAAM,SAAS,CAAC,GAAG,oBAAoB,QAAQ;AAC/C,oBAAiB,QAAQ,OAAO;AAEhC,oBAAiB,QAAQ,OAAO;GAEhC,MAAM,kBAAkB,OAAO,SAC3B,MAAM,kBAAkB,WAAW,QAAQ,UAAU,GACrD,EAAE;GAEN,MAAM,UAAU,YAAY,KAAK;AACjC,UAAO,KACL,kCAAkC,UAAU,OAAO,UAAU,WAAW,QAAQ,EAAE,CAAC,IACpF;AAED,UAAO,MAAM,2BAA2B,UAAU,IAAI,gBAAgB;AAGtE,mBAAgB,gBAAgB;WACzB,OAAO;AACd,UAAO,MAAM,mCAAmC,UAAU,IAAI,MAAM;AAEpE,mBAAgB,EAAE,CAAC;YACX;AACR,gBAAa,MAAM;;IAGvB,CAAC,OAAO,CACT;AAGD,QACE,oBAAC,cAAc;EACb,OAAO;GACL;GACA;GACA;GACA;GACA;GACA;GACD;EAEA;GACsB"}
|
|
1
|
+
{"version":3,"file":"WeglotProvider.mjs","names":["missingHashes: string[]","missingHashes"],"sources":["../../../src/react/shared/WeglotProvider.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n type PropsWithChildren,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from \"react\";\nimport { logger } from \"../../utils/logger\";\nimport { fetchTranslations } from \"./utils\";\nimport { serverUrl, sourceLocale } from \"@weglot/translate-react/virtual/config\";\nimport {\n getClientLocale,\n persistLocale,\n} from \"@weglot/translate-react/virtual/locale/client\";\nimport { WeglotContext } from \"./WeglotContext\";\nimport type { LocaleCode } from \"../../locale\";\n\nconst noop = () => {};\n\n/**\n * Translation provider props\n */\nexport type WeglotProviderProps = PropsWithChildren<{\n /**\n * Initial locale to use\n */\n initialLocale?: LocaleCode;\n\n /**\n * Initial translations (pre-loaded)\n */\n initialTranslations?: Record<string, string>;\n\n /**\n * Optional router instance for Next.js integration\n * If provided, calls router.refresh() after locale change\n * This ensures Server Components re-render with new locale\n */\n router?: { refresh: () => void };\n}>;\n\nconst IS_DEV = process.env.NODE_ENV === \"development\";\nconst BATCH_DELAY = 200;\n\n/**\n * Translation Provider Component\n *\n * Wraps your app to provide translation context to all components.\n * Handles locale switching and on-demand translation loading.\n *\n * @example\n * ```tsx\n * // In your root layout\n * import { WeglotProvider } from '@weglot/translate-react/react';\n *\n * export default function RootLayout({ children }) {\n * return (\n * <html>\n * <body>\n * <WeglotProvider initialLocale=\"en\">\n * {children}\n * </WeglotProvider>\n * </body>\n * </html>\n * );\n * }\n * ```\n */\n// Export the appropriate provider directly\nexport const WeglotProvider = IS_DEV ? WeglotProvider__Dev : WeglotProvider__Prod;\n\nfunction WeglotProvider__Prod({\n initialLocale,\n initialTranslations = {},\n router,\n children,\n}: WeglotProviderProps) {\n // Use client locale detection if no initialLocale provided\n const [locale, setLocaleState] = useState<LocaleCode>(() => {\n if (initialLocale) return initialLocale;\n // Only detect on client-side (not during SSR)\n if (typeof window !== \"undefined\") {\n return getClientLocale();\n }\n return sourceLocale;\n });\n const [translations, setTranslations] =\n useState<Record<string, string>>(initialTranslations);\n const [isLoading, setIsLoading] = useState(false);\n\n logger.debug(\n `WeglotProvider initialized with locale: ${locale}`,\n initialTranslations,\n );\n\n /**\n * Update HTML lang attribute when locale changes\n * This ensures screen readers and SEO understand the page language\n */\n useEffect(() => {\n if (typeof document !== \"undefined\") {\n document.documentElement.lang = locale;\n }\n }, [locale]);\n\n /**\n * Load translations from public/translations/{locale}.json\n * Lazy loads on-demand for SPAs\n */\n const loadTranslations = useCallback(\n async (targetLocale: LocaleCode) => {\n // If we already have initialTranslations (Next.js SSR), don't fetch\n if (Object.keys(initialTranslations).length > 0) {\n return;\n }\n\n if (targetLocale === sourceLocale) {\n setTranslations({});\n return;\n }\n\n setIsLoading(true);\n try {\n const response = await fetch(`/translations/${targetLocale}.json`);\n if (!response.ok) {\n throw new Error(\n `Failed to load translations for ${targetLocale}: ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n // Translation files have format: { version, locale, entries: {...} }\n setTranslations(data.entries || data);\n logger.debug(\n `Loaded translations for ${targetLocale}:`,\n Object.keys(data.entries || data).length,\n );\n } catch (error) {\n logger.error(`Failed to load translations for ${targetLocale}:`, error);\n // Fallback to empty translations\n setTranslations({});\n } finally {\n setIsLoading(false);\n }\n },\n [initialTranslations],\n );\n\n // Load translations on mount if not provided via initialTranslations\n useEffect(() => {\n if (Object.keys(initialTranslations).length === 0) {\n loadTranslations(locale);\n }\n }, []); // Only run on mount\n\n useEffect(() => {\n // TODO (AleksandrSl 08/12/2025): More elegant solution required.\n // This is used to update the client part when next app changes locale\n if (router) {\n setTranslations(initialTranslations);\n }\n }, [initialTranslations, router]);\n\n /**\n * Change locale\n * - For Next.js SSR: triggers server re-render via router.refresh()\n * - For SPAs: lazy loads translations from /translations/{locale}.json\n */\n const setLocale = useCallback(\n async (newLocale: LocaleCode) => {\n // 1. Persist to cookie so server can read it on next render\n persistLocale(newLocale);\n\n // 2. Update local state for immediate UI feedback\n setLocaleState(newLocale);\n\n // 3a. Next.js pattern: Trigger server re-render\n if (router) {\n router.refresh();\n }\n // 3b. SPA pattern: Lazy load translations\n else {\n await loadTranslations(newLocale);\n }\n },\n [router, loadTranslations],\n );\n\n return (\n <WeglotContext.Provider\n value={{\n locale,\n setLocale,\n translations,\n registerHashes: noop,\n isLoading,\n sourceLocale,\n }}\n >\n {children}\n </WeglotContext.Provider>\n );\n}\n\nfunction WeglotProvider__Dev({\n initialLocale,\n initialTranslations = {},\n router,\n children,\n}: WeglotProviderProps) {\n // Use client locale detection if no initialLocale provided\n const [locale, setLocaleState] = useState(() => {\n if (initialLocale) {\n return initialLocale;\n }\n return getClientLocale();\n });\n const [translations, setTranslations] =\n useState<Record<string, string>>(initialTranslations);\n const [isLoading, setIsLoading] = useState(false);\n\n const [allSeenHashes, setAllSeenHashes] = useState<Set<string>>(new Set());\n const registeredHashesRef = useRef<Set<string>>(new Set());\n const pendingHashesRef = useRef<Set<string>>(new Set());\n const erroredHashesRef = useRef<Set<string>>(new Set());\n const batchTimerRef = useRef<NodeJS.Timeout | null>(null);\n\n // Use ref to track translations to avoid stale closures\n const translationsRef = useRef<Record<string, string>>(initialTranslations);\n const localeRef = useRef(locale);\n\n useEffect(() => {\n translationsRef.current = translations;\n }, [translations]);\n\n useEffect(() => {\n localeRef.current = locale;\n }, [locale]);\n\n /**\n * Update HTML lang attribute when locale changes\n * This ensures screen readers and SEO understand the page language\n */\n useEffect(() => {\n if (typeof document !== \"undefined\") {\n document.documentElement.lang = locale;\n }\n }, [locale]);\n\n /**\n * Register a hash as being used in a component\n * Called during render - must not trigger state updates immediately\n */\n const registerHashes = useCallback((hashes: string[]) => {\n let wasNew = false;\n hashes.forEach((hash) => {\n wasNew = wasNew || !registeredHashesRef.current.has(hash);\n registeredHashesRef.current.add(hash);\n });\n\n logger.debug(\n `Registering hashes: ${hashes.join(\", \")}. Registered hashes: ${registeredHashesRef.current.values()}. wasNew: ${wasNew}`,\n );\n\n // Schedule a state update for the next tick to track all hashes\n if (wasNew) {\n setAllSeenHashes((prev) => {\n const next = prev.union(new Set(hashes));\n // TODO (AleksandrSl 25/11/2025): Should be a cheaper solution\n logger.debug(`New allSeenHashes: ${[...next.values()]}`);\n return next;\n });\n }\n }, []);\n\n /**\n * Check for missing translations and request them (batched)\n * This runs when allSeenHashes changes (hot reload or new components mount)\n */\n useEffect(() => {\n logger.debug(\n `WeglotProvider checking translations for locale ${locale}, seen hashes: ${allSeenHashes.size}`,\n );\n\n // The source locale has no dictionary; asking would mark every hash failed\n // and stop it being fetched for later locales.\n if (locale === sourceLocale) {\n return;\n }\n\n // Find hashes that are seen but not translated and not already pending\n const missingHashes: string[] = [];\n logger.debug(\n \"allSeenHashes: \",\n [...allSeenHashes.values()],\n [...pendingHashesRef.current.values()],\n );\n for (const hash of allSeenHashes) {\n if (\n !translations[hash] &&\n !pendingHashesRef.current.has(hash) &&\n !erroredHashesRef.current.has(hash)\n ) {\n missingHashes.push(hash);\n pendingHashesRef.current.add(hash);\n }\n }\n logger.debug(\"Missing hashes: \", missingHashes.join(\",\"));\n\n // If no missing hashes, nothing to do\n if (missingHashes.length === 0 && localeRef.current == locale) return;\n\n logger.debug(\n `Requesting translations for ${missingHashes.length} hashes in locale ${locale}`,\n );\n\n // Cancel existing timer\n if (batchTimerRef.current) {\n clearTimeout(batchTimerRef.current);\n }\n\n // Batch the request\n batchTimerRef.current = setTimeout(async () => {\n const hashesToFetch = Array.from(pendingHashesRef.current);\n pendingHashesRef.current.clear();\n\n logger.debug(`Fetching translations for ${hashesToFetch.length} hashes`);\n if (hashesToFetch.length === 0) return;\n\n setIsLoading(true);\n try {\n const newTranslations = await fetchTranslations(\n localeRef.current,\n hashesToFetch,\n serverUrl,\n );\n\n logger.debug(\n `Fetched translations for ${hashesToFetch.length} hashes:`,\n newTranslations,\n );\n\n const receivedHashes = new Set(Object.keys(newTranslations));\n const missingHashes = hashesToFetch.filter(\n (hash) => !receivedHashes.has(hash),\n );\n\n if (missingHashes.length > 0) {\n logger.warn(\n `Server did not return translations for ${missingHashes.length} hashes: ${missingHashes.join(\", \")}`,\n );\n for (const hash of missingHashes) {\n erroredHashesRef.current.add(hash);\n }\n }\n\n setTranslations((prev) => ({ ...prev, ...newTranslations }));\n for (const hash of hashesToFetch) {\n registeredHashesRef.current.add(hash);\n }\n } catch (error) {\n logger.warn(\n `Failed to fetch translations from translation server: ${error}.`,\n );\n // Remove from pending so they can be retried\n for (const hash of hashesToFetch) {\n pendingHashesRef.current.delete(hash);\n erroredHashesRef.current.add(hash);\n }\n } finally {\n setIsLoading(false);\n }\n }, BATCH_DELAY);\n }, [allSeenHashes, locale, translations]);\n\n /**\n * Clear batch timer on unmount\n */\n useEffect(() => {\n return () => {\n if (batchTimerRef.current) {\n clearTimeout(batchTimerRef.current);\n }\n };\n }, []);\n\n /**\n * Change locale and load translations dynamically\n */\n const setLocale = useCallback(\n async (newLocale: LocaleCode) => {\n // 1. Persist to cookie (unless disabled)\n persistLocale(newLocale);\n\n // 2. Update state\n setLocaleState(newLocale);\n\n // 3. Reload Server Components (if router provided)\n if (router) {\n router.refresh();\n }\n\n setIsLoading(true);\n const startTime = performance.now();\n\n try {\n logger.info(\n `Fetching translations for locale: ${newLocale}. Server url: ${serverUrl}`,\n );\n\n // Everything on the page in one request; later mounts go through batching.\n const hashes = [...registeredHashesRef.current];\n pendingHashesRef.current.clear();\n // A hash that failed for one locale may well exist for the next.\n erroredHashesRef.current.clear();\n\n const newTranslations = hashes.length\n ? await fetchTranslations(newLocale, hashes, serverUrl)\n : {};\n\n const endTime = performance.now();\n logger.info(\n `Translation fetch complete for ${newLocale} in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n logger.debug(`Translations loaded for ${newLocale}:`, newTranslations);\n\n // Replace rather than merge: entries of the previous locale must go.\n setTranslations(newTranslations);\n } catch (error) {\n logger.error(`Failed to load translations for ${newLocale}:`, error);\n // Clear translations on error - components will request individually\n setTranslations({});\n } finally {\n setIsLoading(false);\n }\n },\n [router],\n );\n\n // TODO (AleksandrSl 24/11/2025): Should I memo the value?\n return (\n <WeglotContext.Provider\n value={{\n locale,\n setLocale,\n translations,\n registerHashes,\n isLoading,\n sourceLocale,\n }}\n >\n {children}\n </WeglotContext.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;AAmBA,MAAM,aAAa;AAwBnB,MAAM,SAAS,QAAQ,IAAI,aAAa;AACxC,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;AA2BpB,MAAa,iBAAiB,SAAS,sBAAsB;AAE7D,SAAS,qBAAqB,EAC5B,eACA,sBAAsB,EAAE,EACxB,QACA,YACsB;CAEtB,MAAM,CAAC,QAAQ,kBAAkB,eAA2B;AAC1D,MAAI,cAAe,QAAO;AAE1B,MAAI,OAAO,WAAW,YACpB,QAAO,iBAAiB;AAE1B,SAAO;GACP;CACF,MAAM,CAAC,cAAc,mBACnB,SAAiC,oBAAoB;C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|
1
|
+
const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_logger = require('../../utils/logger.cjs');
|
|
3
|
+
let intl_messageformat = require("intl-messageformat");
|
|
4
|
+
intl_messageformat = require_rolldown_runtime.__toESM(intl_messageformat);
|
|
5
|
+
|
|
6
|
+
//#region src/react/shared/msg.ts
|
|
7
|
+
/**
|
|
8
|
+
* Marks a string for translation where the compiler cannot see it being
|
|
9
|
+
* rendered, such as a nav array in a data file. The compiler adds the string
|
|
10
|
+
* to the dictionary and fills in `hash` and `values`; never pass them yourself.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { msg } from "@weglot/translate-react/react";
|
|
15
|
+
* export const NAV = [{ href: "/billing", label: msg("Billing") }];
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
function msg(text, hash = "", values) {
|
|
19
|
+
return values ? {
|
|
20
|
+
hash,
|
|
21
|
+
text,
|
|
22
|
+
values
|
|
23
|
+
} : {
|
|
24
|
+
hash,
|
|
25
|
+
text
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function isMessageDescriptor(value) {
|
|
29
|
+
return typeof value === "object" && value !== null && typeof value.hash === "string" && typeof value.text === "string";
|
|
30
|
+
}
|
|
31
|
+
function formatMessage(message, params, translations, locale) {
|
|
32
|
+
const text = message.hash && translations[message.hash] || message.text;
|
|
33
|
+
const values = params ? {
|
|
34
|
+
...message.values,
|
|
35
|
+
...params
|
|
36
|
+
} : message.values;
|
|
37
|
+
if (!values) return text;
|
|
38
|
+
try {
|
|
39
|
+
const result = new intl_messageformat.default(text, locale).format(values);
|
|
40
|
+
return Array.isArray(result) ? result.join("") : String(result);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
require_logger.logger.warn(`Error formatting message (${text}): ${error}`);
|
|
43
|
+
return text;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
//#endregion
|
|
48
|
+
exports.formatMessage = formatMessage;
|
|
49
|
+
exports.isMessageDescriptor = isMessageDescriptor;
|
|
50
|
+
exports.msg = msg;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/react/shared/msg.d.ts
|
|
2
|
+
type MessageValues = Record<string, string | number | boolean | Date | null | undefined>;
|
|
3
|
+
/**
|
|
4
|
+
* A string marked for translation outside a component, returned by {@link msg}.
|
|
5
|
+
* Pass it to `t()` from `useTranslation()` to get the translated string.
|
|
6
|
+
*/
|
|
7
|
+
interface MessageDescriptor {
|
|
8
|
+
hash: string;
|
|
9
|
+
text: string;
|
|
10
|
+
values?: MessageValues;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Marks a string for translation where the compiler cannot see it being
|
|
14
|
+
* rendered, such as a nav array in a data file. The compiler adds the string
|
|
15
|
+
* to the dictionary and fills in `hash` and `values`; never pass them yourself.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* import { msg } from "@weglot/translate-react/react";
|
|
20
|
+
* export const NAV = [{ href: "/billing", label: msg("Billing") }];
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
declare function msg(text: string, hash?: string, values?: MessageValues): MessageDescriptor;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { MessageDescriptor, MessageValues, msg };
|
|
26
|
+
//# sourceMappingURL=msg.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"msg.d.cts","names":[],"sources":["../../../src/react/shared/msg.ts"],"sourcesContent":[],"mappings":";AAIY,KAAA,aAAA,GAAgB,MAEE,CAAA,MAFF,EAAA,MAAM,GAAA,MAAA,GAAA,OAAA,GAEJ,IAFI,GAAA,IAAA,GAAA,SAAA,CAAA;AASlC;AAiBA;;;UAjBiB,iBAAA;;;WAGN;;;;;;;;;;;;;iBAcK,GAAA,uCAGL,gBACR"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/react/shared/msg.d.ts
|
|
2
|
+
type MessageValues = Record<string, string | number | boolean | Date | null | undefined>;
|
|
3
|
+
/**
|
|
4
|
+
* A string marked for translation outside a component, returned by {@link msg}.
|
|
5
|
+
* Pass it to `t()` from `useTranslation()` to get the translated string.
|
|
6
|
+
*/
|
|
7
|
+
interface MessageDescriptor {
|
|
8
|
+
hash: string;
|
|
9
|
+
text: string;
|
|
10
|
+
values?: MessageValues;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Marks a string for translation where the compiler cannot see it being
|
|
14
|
+
* rendered, such as a nav array in a data file. The compiler adds the string
|
|
15
|
+
* to the dictionary and fills in `hash` and `values`; never pass them yourself.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* import { msg } from "@weglot/translate-react/react";
|
|
20
|
+
* export const NAV = [{ href: "/billing", label: msg("Billing") }];
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
declare function msg(text: string, hash?: string, values?: MessageValues): MessageDescriptor;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { MessageDescriptor, MessageValues, msg };
|
|
26
|
+
//# sourceMappingURL=msg.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"msg.d.mts","names":[],"sources":["../../../src/react/shared/msg.ts"],"sourcesContent":[],"mappings":";AAIY,KAAA,aAAA,GAAgB,MAEE,CAAA,MAFF,EAAA,MAAM,GAAA,MAAA,GAAA,OAAA,GAEJ,IAFI,GAAA,IAAA,GAAA,SAAA,CAAA;AASlC;AAiBA;;;UAjBiB,iBAAA;;;WAGN;;;;;;;;;;;;;iBAcK,GAAA,uCAGL,gBACR"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { logger } from "../../utils/logger.mjs";
|
|
2
|
+
import IntlMessageFormat from "intl-messageformat";
|
|
3
|
+
|
|
4
|
+
//#region src/react/shared/msg.ts
|
|
5
|
+
/**
|
|
6
|
+
* Marks a string for translation where the compiler cannot see it being
|
|
7
|
+
* rendered, such as a nav array in a data file. The compiler adds the string
|
|
8
|
+
* to the dictionary and fills in `hash` and `values`; never pass them yourself.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { msg } from "@weglot/translate-react/react";
|
|
13
|
+
* export const NAV = [{ href: "/billing", label: msg("Billing") }];
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
function msg(text, hash = "", values) {
|
|
17
|
+
return values ? {
|
|
18
|
+
hash,
|
|
19
|
+
text,
|
|
20
|
+
values
|
|
21
|
+
} : {
|
|
22
|
+
hash,
|
|
23
|
+
text
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function isMessageDescriptor(value) {
|
|
27
|
+
return typeof value === "object" && value !== null && typeof value.hash === "string" && typeof value.text === "string";
|
|
28
|
+
}
|
|
29
|
+
function formatMessage(message, params, translations, locale) {
|
|
30
|
+
const text = message.hash && translations[message.hash] || message.text;
|
|
31
|
+
const values = params ? {
|
|
32
|
+
...message.values,
|
|
33
|
+
...params
|
|
34
|
+
} : message.values;
|
|
35
|
+
if (!values) return text;
|
|
36
|
+
try {
|
|
37
|
+
const result = new IntlMessageFormat(text, locale).format(values);
|
|
38
|
+
return Array.isArray(result) ? result.join("") : String(result);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
logger.warn(`Error formatting message (${text}): ${error}`);
|
|
41
|
+
return text;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
//#endregion
|
|
46
|
+
export { formatMessage, isMessageDescriptor, msg };
|
|
47
|
+
//# sourceMappingURL=msg.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"msg.mjs","names":[],"sources":["../../../src/react/shared/msg.ts"],"sourcesContent":["import IntlMessageFormat from \"intl-messageformat\";\nimport { logger } from \"../../utils/logger\";\nimport type { LocaleCode } from \"../../locale\";\n\nexport type MessageValues = Record<\n string,\n string | number | boolean | Date | null | undefined\n>;\n\n/**\n * A string marked for translation outside a component, returned by {@link msg}.\n * Pass it to `t()` from `useTranslation()` to get the translated string.\n */\nexport interface MessageDescriptor {\n hash: string;\n text: string;\n values?: MessageValues;\n}\n\n/**\n * Marks a string for translation where the compiler cannot see it being\n * rendered, such as a nav array in a data file. The compiler adds the string\n * to the dictionary and fills in `hash` and `values`; never pass them yourself.\n *\n * @example\n * ```ts\n * import { msg } from \"@weglot/translate-react/react\";\n * export const NAV = [{ href: \"/billing\", label: msg(\"Billing\") }];\n * ```\n */\nexport function msg(\n text: string,\n hash: string = \"\",\n values?: MessageValues,\n): MessageDescriptor {\n return values ? { hash, text, values } : { hash, text };\n}\n\nexport function isMessageDescriptor(\n value: unknown,\n): value is MessageDescriptor {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as MessageDescriptor).hash === \"string\" &&\n typeof (value as MessageDescriptor).text === \"string\"\n );\n}\n\nexport function formatMessage(\n message: MessageDescriptor,\n params: MessageValues | undefined,\n translations: Record<string, string>,\n locale: LocaleCode,\n): string {\n const text = (message.hash && translations[message.hash]) || message.text;\n const values = params ? { ...message.values, ...params } : message.values;\n\n if (!values) {\n return text;\n }\n\n try {\n const result = new IntlMessageFormat(text, locale).format(values);\n return Array.isArray(result) ? result.join(\"\") : String(result);\n } catch (error) {\n logger.warn(`Error formatting message (${text}): ${error}`);\n return text;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,SAAgB,IACd,MACA,OAAe,IACf,QACmB;AACnB,QAAO,SAAS;EAAE;EAAM;EAAM;EAAQ,GAAG;EAAE;EAAM;EAAM;;AAGzD,SAAgB,oBACd,OAC4B;AAC5B,QACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA4B,SAAS,YAC7C,OAAQ,MAA4B,SAAS;;AAIjD,SAAgB,cACd,SACA,QACA,cACA,QACQ;CACR,MAAM,OAAQ,QAAQ,QAAQ,aAAa,QAAQ,SAAU,QAAQ;CACrE,MAAM,SAAS,SAAS;EAAE,GAAG,QAAQ;EAAQ,GAAG;EAAQ,GAAG,QAAQ;AAEnE,KAAI,CAAC,OACH,QAAO;AAGT,KAAI;EACF,MAAM,SAAS,IAAI,kBAAkB,MAAM,OAAO,CAAC,OAAO,OAAO;AACjE,SAAO,MAAM,QAAQ,OAAO,GAAG,OAAO,KAAK,GAAG,GAAG,OAAO,OAAO;UACxD,OAAO;AACd,SAAO,KAAK,6BAA6B,KAAK,KAAK,QAAQ;AAC3D,SAAO"}
|
package/build/react/types.d.cts
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
import { LocaleCode } from "../locale.cjs";
|
|
2
2
|
import { RichTextParams } from "./shared/render-rich-text.cjs";
|
|
3
|
+
import { MessageDescriptor, MessageValues } from "./shared/msg.cjs";
|
|
3
4
|
import { ReactNode } from "react";
|
|
4
5
|
|
|
5
6
|
//#region src/react/types.d.ts
|
|
6
|
-
type TranslationHook = (hashes
|
|
7
|
+
type TranslationHook = (hashes?: string[]) => {
|
|
7
8
|
t: TranslationFunction;
|
|
8
9
|
locale: LocaleCode;
|
|
9
10
|
};
|
|
10
11
|
/**
|
|
11
12
|
* Translation function type
|
|
12
13
|
*/
|
|
13
|
-
|
|
14
|
+
interface TranslationFunction {
|
|
15
|
+
(message: MessageDescriptor, params?: MessageValues): string;
|
|
16
|
+
(hash: string, source: string, params?: RichTextParams): string | ReactNode;
|
|
17
|
+
}
|
|
14
18
|
//#endregion
|
|
15
|
-
export { TranslationHook };
|
|
19
|
+
export { TranslationFunction, TranslationHook };
|
|
16
20
|
//# sourceMappingURL=types.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.cts","names":[],"sources":["../../src/react/types.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.cts","names":[],"sources":["../../src/react/types.ts"],"sourcesContent":[],"mappings":";;;;;;KAKY,eAAA;KACP;EADO,MAAA,EAEF,UAFiB;AAQ3B,CAAA;;;;AAEoE,UAFnD,mBAAA,CAEmD;EAAS,CAAA,OAAA,EADjE,iBACiE,EAAA,MAAA,CAAA,EADrC,aACqC,CAAA,EAAA,MAAA;0CAAnC,0BAA0B"}
|
package/build/react/types.d.mts
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
import { LocaleCode } from "../locale.mjs";
|
|
2
2
|
import { RichTextParams } from "./shared/render-rich-text.mjs";
|
|
3
|
+
import { MessageDescriptor, MessageValues } from "./shared/msg.mjs";
|
|
3
4
|
import { ReactNode } from "react";
|
|
4
5
|
|
|
5
6
|
//#region src/react/types.d.ts
|
|
6
|
-
type TranslationHook = (hashes
|
|
7
|
+
type TranslationHook = (hashes?: string[]) => {
|
|
7
8
|
t: TranslationFunction;
|
|
8
9
|
locale: LocaleCode;
|
|
9
10
|
};
|
|
10
11
|
/**
|
|
11
12
|
* Translation function type
|
|
12
13
|
*/
|
|
13
|
-
|
|
14
|
+
interface TranslationFunction {
|
|
15
|
+
(message: MessageDescriptor, params?: MessageValues): string;
|
|
16
|
+
(hash: string, source: string, params?: RichTextParams): string | ReactNode;
|
|
17
|
+
}
|
|
14
18
|
//#endregion
|
|
15
|
-
export { TranslationHook };
|
|
19
|
+
export { TranslationFunction, TranslationHook };
|
|
16
20
|
//# sourceMappingURL=types.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../../src/react/types.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../../src/react/types.ts"],"sourcesContent":[],"mappings":";;;;;;KAKY,eAAA;KACP;EADO,MAAA,EAEF,UAFiB;AAQ3B,CAAA;;;;AAEoE,UAFnD,mBAAA,CAEmD;EAAS,CAAA,OAAA,EADjE,iBACiE,EAAA,MAAA,CAAA,EADrC,aACqC,CAAA,EAAA,MAAA;0CAAnC,0BAA0B"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/runtime/lru-cache.ts
|
|
3
|
+
/** A Map kept in recency order: the first key is the least recently used. */
|
|
4
|
+
var LruCache = class {
|
|
5
|
+
entries = /* @__PURE__ */ new Map();
|
|
6
|
+
constructor(maxSize) {
|
|
7
|
+
this.maxSize = maxSize;
|
|
8
|
+
}
|
|
9
|
+
get size() {
|
|
10
|
+
return this.entries.size;
|
|
11
|
+
}
|
|
12
|
+
get(key) {
|
|
13
|
+
const value = this.entries.get(key);
|
|
14
|
+
if (value === void 0) return void 0;
|
|
15
|
+
this.entries.delete(key);
|
|
16
|
+
this.entries.set(key, value);
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
set(key, value) {
|
|
20
|
+
this.entries.delete(key);
|
|
21
|
+
if (this.maxSize <= 0) return;
|
|
22
|
+
this.entries.set(key, value);
|
|
23
|
+
this.evict();
|
|
24
|
+
}
|
|
25
|
+
resize(maxSize) {
|
|
26
|
+
this.maxSize = maxSize;
|
|
27
|
+
this.evict();
|
|
28
|
+
}
|
|
29
|
+
clear() {
|
|
30
|
+
this.entries.clear();
|
|
31
|
+
}
|
|
32
|
+
evict() {
|
|
33
|
+
while (this.entries.size > Math.max(this.maxSize, 0)) this.entries.delete(this.entries.keys().next().value);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
//#endregion
|
|
38
|
+
exports.LruCache = LruCache;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
//#region src/runtime/lru-cache.ts
|
|
2
|
+
/** A Map kept in recency order: the first key is the least recently used. */
|
|
3
|
+
var LruCache = class {
|
|
4
|
+
entries = /* @__PURE__ */ new Map();
|
|
5
|
+
constructor(maxSize) {
|
|
6
|
+
this.maxSize = maxSize;
|
|
7
|
+
}
|
|
8
|
+
get size() {
|
|
9
|
+
return this.entries.size;
|
|
10
|
+
}
|
|
11
|
+
get(key) {
|
|
12
|
+
const value = this.entries.get(key);
|
|
13
|
+
if (value === void 0) return void 0;
|
|
14
|
+
this.entries.delete(key);
|
|
15
|
+
this.entries.set(key, value);
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
set(key, value) {
|
|
19
|
+
this.entries.delete(key);
|
|
20
|
+
if (this.maxSize <= 0) return;
|
|
21
|
+
this.entries.set(key, value);
|
|
22
|
+
this.evict();
|
|
23
|
+
}
|
|
24
|
+
resize(maxSize) {
|
|
25
|
+
this.maxSize = maxSize;
|
|
26
|
+
this.evict();
|
|
27
|
+
}
|
|
28
|
+
clear() {
|
|
29
|
+
this.entries.clear();
|
|
30
|
+
}
|
|
31
|
+
evict() {
|
|
32
|
+
while (this.entries.size > Math.max(this.maxSize, 0)) this.entries.delete(this.entries.keys().next().value);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
//#endregion
|
|
37
|
+
export { LruCache };
|
|
38
|
+
//# sourceMappingURL=lru-cache.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lru-cache.mjs","names":["maxSize: number"],"sources":["../../src/runtime/lru-cache.ts"],"sourcesContent":["/** A Map kept in recency order: the first key is the least recently used. */\nexport class LruCache<V> {\n private readonly entries = new Map<string, V>();\n\n constructor(private maxSize: number) {}\n\n get size(): number {\n return this.entries.size;\n }\n\n get(key: string): V | undefined {\n const value = this.entries.get(key);\n if (value === undefined) return undefined;\n this.entries.delete(key);\n this.entries.set(key, value);\n return value;\n }\n\n set(key: string, value: V): void {\n this.entries.delete(key);\n if (this.maxSize <= 0) return;\n this.entries.set(key, value);\n this.evict();\n }\n\n resize(maxSize: number): void {\n this.maxSize = maxSize;\n this.evict();\n }\n\n clear(): void {\n this.entries.clear();\n }\n\n private evict(): void {\n while (this.entries.size > Math.max(this.maxSize, 0)) {\n this.entries.delete(this.entries.keys().next().value!);\n }\n }\n}\n"],"mappings":";;AACA,IAAa,WAAb,MAAyB;CACvB,AAAiB,0BAAU,IAAI,KAAgB;CAE/C,YAAY,AAAQA,SAAiB;EAAjB;;CAEpB,IAAI,OAAe;AACjB,SAAO,KAAK,QAAQ;;CAGtB,IAAI,KAA4B;EAC9B,MAAM,QAAQ,KAAK,QAAQ,IAAI,IAAI;AACnC,MAAI,UAAU,OAAW,QAAO;AAChC,OAAK,QAAQ,OAAO,IAAI;AACxB,OAAK,QAAQ,IAAI,KAAK,MAAM;AAC5B,SAAO;;CAGT,IAAI,KAAa,OAAgB;AAC/B,OAAK,QAAQ,OAAO,IAAI;AACxB,MAAI,KAAK,WAAW,EAAG;AACvB,OAAK,QAAQ,IAAI,KAAK,MAAM;AAC5B,OAAK,OAAO;;CAGd,OAAO,SAAuB;AAC5B,OAAK,UAAU;AACf,OAAK,OAAO;;CAGd,QAAc;AACZ,OAAK,QAAQ,OAAO;;CAGtB,AAAQ,QAAc;AACpB,SAAO,KAAK,QAAQ,OAAO,KAAK,IAAI,KAAK,SAAS,EAAE,CAClD,MAAK,QAAQ,OAAO,KAAK,QAAQ,MAAM,CAAC,MAAM,CAAC,MAAO"}
|